diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml new file mode 100644 index 000000000..143914cb6 --- /dev/null +++ b/.github/workflows/desktop.yml @@ -0,0 +1,104 @@ +name: Desktop + +on: + push: + paths: + - 'desktop/**' + - 'PipePipeExtractor' + - '.github/workflows/desktop.yml' + tags: + - 'desktop-v*' + pull_request: + paths: + - 'desktop/**' + workflow_dispatch: + +permissions: + contents: write + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + name: linux-x64 + - os: windows-latest + name: windows-x64 + - os: macos-latest + name: macos-arm64 + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + + # only the extractor is needed (the other submodules use SSH URLs) + - name: Checkout PipePipeExtractor submodule + run: git submodule update --init --depth 1 PipePipeExtractor + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + cache: gradle + + - name: Build fat jar + working-directory: desktop + run: ./gradlew --no-daemon fatJar + + - name: Package self-contained app (bundled JRE) + working-directory: desktop + run: | + VERSION=$(grep "^version" build.gradle | sed "s/.*'\(.*\)'.*/\1/") + mkdir -p dist + ICON="" + if [ "${{ runner.os }}" = "Linux" ]; then ICON="--icon src/main/resources/web/icon.png"; fi + jpackage --type app-image \ + --name PipePipe \ + --app-version "$VERSION" \ + --vendor "PipePipe Desktop" \ + --input build/libs \ + --main-jar "pipepipe-desktop-${VERSION}-all.jar" \ + --java-options "-XX:+UseSerialGC -Xss512k" \ + --add-modules java.base,java.desktop,java.naming,java.net.http,java.sql,jdk.httpserver,jdk.unsupported,jdk.crypto.ec,java.management,java.logging,jdk.localedata,java.xml \ + --jlink-options "--strip-debug --no-man-pages --no-header-files --compress=zip-6" \ + $ICON \ + --dest dist + find dist -name "*.debuginfo" -delete + cd dist + if [ "${{ runner.os }}" = "Windows" ]; then + 7z a "../PipePipe-${{ matrix.name }}.zip" PipePipe > /dev/null + elif [ "${{ runner.os }}" = "macOS" ]; then + ditto -c -k --keepParent PipePipe.app "../PipePipe-${{ matrix.name }}.zip" + else + tar czf "../PipePipe-${{ matrix.name }}.tar.gz" PipePipe + fi + + - uses: actions/upload-artifact@v4 + with: + name: PipePipe-${{ matrix.name }} + path: | + desktop/PipePipe-${{ matrix.name }}.* + + - uses: actions/upload-artifact@v4 + if: matrix.name == 'linux-x64' + with: + name: pipepipe-desktop-jar + path: desktop/build/libs/*-all.jar + + release: + if: startsWith(github.ref, 'refs/tags/desktop-v') + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + path: out + merge-multiple: true + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "${GITHUB_REF_NAME}" out/* --repo "${GITHUB_REPOSITORY}" --title "PipePipe Desktop ${GITHUB_REF_NAME#desktop-v}" --generate-notes diff --git a/.gitmodules b/.gitmodules index 8b8af6bf8..7b1b3d21e 100644 --- a/.gitmodules +++ b/.gitmodules @@ -12,7 +12,7 @@ branch = main [submodule "PipePipeClient"] path = PipePipeClient - url = git@github.com:InfinityLoop1308/PipePipeClient.git + url = https://github.com/InfinityLoop1308/PipePipeClient.git [submodule "PipePipeExtractor"] path = PipePipeExtractor - url = git@github.com:InfinityLoop1308/PipePipeExtractor.git + url = https://github.com/InfinityLoop1308/PipePipeExtractor.git diff --git a/PipePipeExtractor b/PipePipeExtractor index 1a09d20e6..56379dcd5 160000 --- a/PipePipeExtractor +++ b/PipePipeExtractor @@ -1 +1 @@ -Subproject commit 1a09d20e68dbd0892995bc58ffa539049a656690 +Subproject commit 56379dcd546e9723dddca52d59aa6d8c562188d2 diff --git a/README.md b/README.md index 899baa5b1..60c8c6773 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ NewPipe, reimagined: faster, more stable, and packed with more features. Get it on IzzyOnDroid


+> **Desktop (Windows · macOS · Linux):** this fork adds a PC client built on the same PipePipeExtractor — see [`desktop/`](desktop/README.md). + ## Beyond NewPipe #### YouTube Enhancements diff --git a/desktop/.gitignore b/desktop/.gitignore new file mode 100644 index 000000000..837c9938a --- /dev/null +++ b/desktop/.gitignore @@ -0,0 +1,5 @@ +build/ +.gradle/ +dist/ +*.tar.gz +*.zip diff --git a/desktop/README.md b/desktop/README.md new file mode 100644 index 000000000..280926524 --- /dev/null +++ b/desktop/README.md @@ -0,0 +1,67 @@ +# PipePipe Desktop + +PipePipe의 데스크톱(PC) 클라이언트입니다. 안드로이드 앱과 같은 **PipePipeExtractor**(이 저장소의 서브모듈)를 그대로 엔진으로 쓰고, 그 위에 로컬 웹 서버와 PC 전용 UI를 얹었습니다. + +- YouTube · BiliBili · NicoNico 검색/재생/채널/재생목록/댓글 +- 최대 4K60 적응형 재생 (DASH/HLS, shaka-player), 화질·속도·자막·오디오 트랙 선택 +- 구독 피드, 시청 기록(이어보기), 나중에 볼 동영상, 로컬 재생목록 +- NewPipe / PipePipe 구독 JSON 가져오기·내보내기 +- 미니 플레이어, 영화관 모드, PIP, 키보드 단축키, 미디어 키 +- 계정·광고·추적 없음. 모든 데이터는 이 컴퓨터에만 저장됩니다. + +## 실행 + +### 설치 파일 (Java 불필요) +[Actions](https://github.com/ssiloh/PipePipe/actions/workflows/desktop.yml) 또는 Releases에서 OS별 `PipePipe-*.zip / .tar.gz`를 받아 압축을 풀고 `PipePipe`를 실행합니다. +설치된 Chrome / Edge / Chromium / Brave가 있으면 독립된 앱 창으로 열리고, 창을 닫으면 앱도 종료됩니다. (없으면 기본 브라우저 + 트레이 아이콘) + +### 소스에서 +JDK 25가 필요합니다. + +```bash +git submodule update --init PipePipeExtractor +cd desktop +./gradlew fatJar +java -jar build/libs/pipepipe-desktop-0.1.0-all.jar # 앱 창으로 실행 +java -jar build/libs/pipepipe-desktop-0.1.0-all.jar --server # 웹 서버만 (http://127.0.0.1:47615) +``` + +옵션: `--host 0.0.0.0`(LAN에 공개 — 같은 네트워크의 누구나 사용 가능), `--port N`, `--data DIR`, `--web DIR`(UI를 디스크에서 바로 제공, 개발용). +환경변수 `PIPEPIPE_BROWSER`로 앱 창에 쓸 브라우저 실행 파일을 지정할 수 있습니다. + +데이터 위치: Windows `%APPDATA%\PipePipe Desktop`, macOS `~/Library/Application Support/PipePipe Desktop`, Linux `~/.local/share/pipepipe-desktop`. + +## 구조 + +``` +desktop/ + src/main/java/dev/pipepipe/desktop/ + Main.java 실행, 앱 창(Chromium --app) 띄우기, 트레이 + Server.java JDK HttpServer + 가상 스레드, 라우팅, 정적 파일 + Api.java PipePipeExtractor → JSON (검색, 스트림, 채널, 재생목록, 댓글, 피드) + DesktopDownloader.java 안드로이드 DownloaderImpl의 OkHttp 포팅 + MediaProxy.java 서명된 미디어/HLS 프록시 (CORS·Referer·쿠키 처리, YouTube 청크) + Mpd.java 바이트 범위 인덱스 스트림 → DASH 매니페스트 (YouTube, BiliBili) + Store.java 구독/기록/재생목록/설정 JSON 저장 + src/main/resources/web/ UI (빌드 단계 없는 순수 ES 모듈) + index.html app.css app.js player.js vendor/shaka-player.compiled.js +``` + +재생 방식: 서버가 추출기 결과로 DASH 매니페스트(YouTube·BiliBili) 또는 HLS 마스터 플레이리스트(NicoNico, 라이브)를 만들고, 모든 미디어 요청은 로컬 프록시(`/px/…`, HMAC 서명)를 거칩니다. 브라우저는 MSE로 재생하므로 CORS나 서비스별 헤더 문제가 없습니다. + +## 단축키 + +| 키 | 동작 | +|---|---| +| `/` | 검색 | +| `K` / `Space` | 재생·일시정지 | +| `J` / `L`, `←` / `→` | 10초 / 5초 이동 | +| `↑` / `↓` | 볼륨 | +| `M` `F` `T` `I` `C` | 음소거 · 전체화면 · 영화관 · PIP · 자막 | +| `Shift+N` | 다음 동영상 | +| `<` / `>` | 재생 속도 | +| `0`–`9` | 10% 단위 이동 | +| `Ctrl+B` | 사이드바 | + +## 라이선스 +GPLv3 (PipePipe와 동일). shaka-player는 Apache-2.0 (`web/vendor/shaka-LICENSE.txt`). diff --git a/desktop/build.gradle b/desktop/build.gradle new file mode 100644 index 000000000..5c49f47c2 --- /dev/null +++ b/desktop/build.gradle @@ -0,0 +1,48 @@ +plugins { + id 'java' + id 'application' +} + +group = 'dev.pipepipe.desktop' +version = '0.1.0' + +java { + toolchain { languageVersion = JavaLanguageVersion.of(25) } +} + +repositories { + mavenCentral() + maven { url 'https://jitpack.io' } +} + +dependencies { + // Substituted by the included build in ../PipePipeExtractor + implementation 'com.github.InfinityLoop1308.PipePipeExtractor:extractor' + implementation 'com.squareup.okhttp3:okhttp:5.4.0' + implementation 'org.json:json:20260522' // provided by Android at runtime, needed on desktop + compileOnly 'com.github.spotbugs:spotbugs-annotations:4.10.2' +} + +tasks.withType(JavaCompile).configureEach { options.encoding = "UTF-8" } + + +application { + mainClass = 'dev.pipepipe.desktop.Main' + applicationDefaultJvmArgs = ['-XX:+UseSerialGC', '-Xss512k', '-Xshare:auto'] +} + +jar { + manifest { attributes 'Main-Class': application.mainClass.get() } +} + +// Single runnable fat jar: build/libs/pipepipe-desktop-all.jar +tasks.register('fatJar', Jar) { + archiveClassifier = 'all' + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + manifest { attributes 'Main-Class': application.mainClass.get() } + from sourceSets.main.output + dependsOn configurations.runtimeClasspath + from { configurations.runtimeClasspath.findAll { it.name.endsWith('.jar') }.collect { zipTree(it) } } { + exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/versions/*/module-info.class', 'module-info.class' + } +} diff --git a/desktop/gradle/wrapper/gradle-wrapper.jar b/desktop/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..7454180f2 Binary files /dev/null and b/desktop/gradle/wrapper/gradle-wrapper.jar differ diff --git a/desktop/gradle/wrapper/gradle-wrapper.properties b/desktop/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..9937dae91 --- /dev/null +++ b/desktop/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/desktop/gradlew b/desktop/gradlew new file mode 100755 index 000000000..744e882ed --- /dev/null +++ b/desktop/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MSYS* | MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/desktop/gradlew.bat b/desktop/gradlew.bat new file mode 100644 index 000000000..ac1b06f93 --- /dev/null +++ b/desktop/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/desktop/settings.gradle b/desktop/settings.gradle new file mode 100644 index 000000000..ca2ab241d --- /dev/null +++ b/desktop/settings.gradle @@ -0,0 +1,3 @@ +rootProject.name = 'pipepipe-desktop' +// Build directly against the PipePipeExtractor submodule of this fork. +includeBuild('../PipePipeExtractor') diff --git a/desktop/src/main/java/dev/pipepipe/desktop/Api.java b/desktop/src/main/java/dev/pipepipe/desktop/Api.java new file mode 100644 index 000000000..53911690f --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/Api.java @@ -0,0 +1,580 @@ +package dev.pipepipe.desktop; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.schabi.newpipe.extractor.InfoItem; +import org.schabi.newpipe.extractor.ListExtractor.InfoItemsPage; +import org.schabi.newpipe.extractor.NewPipe; +import org.schabi.newpipe.extractor.Page; +import org.schabi.newpipe.extractor.StreamingService; +import org.schabi.newpipe.extractor.channel.ChannelInfo; +import org.schabi.newpipe.extractor.channel.ChannelInfoItem; +import org.schabi.newpipe.extractor.comments.CommentsInfo; +import org.schabi.newpipe.extractor.comments.CommentsInfoItem; +import org.schabi.newpipe.extractor.feed.FeedExtractor; +import org.schabi.newpipe.extractor.feed.FeedInfo; +import org.schabi.newpipe.extractor.kiosk.KioskInfo; +import org.schabi.newpipe.extractor.linkhandler.SearchQueryHandler; +import org.schabi.newpipe.extractor.localization.DateWrapper; +import org.schabi.newpipe.extractor.playlist.PlaylistInfo; +import org.schabi.newpipe.extractor.playlist.PlaylistInfoItem; +import org.schabi.newpipe.extractor.search.SearchInfo; +import org.schabi.newpipe.extractor.search.filter.FilterItem; +import org.schabi.newpipe.extractor.ServiceList; +import org.schabi.newpipe.extractor.stream.AudioStream; +import org.schabi.newpipe.extractor.stream.DeliveryMethod; +import org.schabi.newpipe.extractor.stream.Stream; +import org.schabi.newpipe.extractor.stream.Description; +import org.schabi.newpipe.extractor.stream.StreamInfo; +import org.schabi.newpipe.extractor.stream.StreamInfoItem; +import org.schabi.newpipe.extractor.stream.StreamSegment; +import org.schabi.newpipe.extractor.stream.StreamType; +import org.schabi.newpipe.extractor.stream.SubtitlesStream; +import org.schabi.newpipe.extractor.stream.VideoStream; +import org.schabi.newpipe.extractor.MediaFormat; + +import java.security.SecureRandom; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** Maps PipePipeExtractor results to the JSON consumed by the web UI. */ +final class Api { + private final MediaProxy proxy; + private final SecureRandom random = new SecureRandom(); + private final ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor(); + + /** Opaque continuation tokens: Pages stay server side, the UI only sees a random id. */ + private record Cont(String kind, int service, String url, Object handler, Page page) { } + + private final Map continuations = lru(2000); + private final Map> streams = lru(64); + private final Map>> feedCache = new ConcurrentHashMap<>(); + + private record Timed(T value, long at) { + boolean fresh(final long maxAgeMs) { + return System.currentTimeMillis() - at < maxAgeMs; + } + } + + Api(final MediaProxy proxy) { + this.proxy = proxy; + } + + private static Map lru(final int max) { + return Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(final Map.Entry e) { + return size() > max; + } + }); + } + + private String cont(final String kind, final int service, final String url, final Object handler, + final Page page) { + if (!Page.isValid(page)) { + return null; + } + final byte[] b = new byte[9]; + random.nextBytes(b); + final String id = HexFormat.of().formatHex(b); + continuations.put(id, new Cont(kind, service, url, handler, page)); + return id; + } + + private static StreamingService service(final String id) throws Exception { + return NewPipe.getService(id == null || id.isBlank() ? 0 : Integer.parseInt(id)); + } + + // ---------------------------------------------------------------- serialisation + + private static String best(final List images, final String fallback) { + if (images == null || images.isEmpty()) { + return fallback; + } + org.schabi.newpipe.extractor.Image pick = images.get(images.size() - 1); + for (final var img : images) { + if (img.getHeight() >= 180 && img.getHeight() <= 720) { + pick = img; + break; + } + } + return pick.getUrl(); + } + + private static Object date(final DateWrapper d) { + if (d == null) { + return JSONObject.NULL; + } + try { + return d.offsetDateTime().toInstant().toEpochMilli(); + } catch (final Exception e) { + return JSONObject.NULL; + } + } + + static JSONObject item(final InfoItem it) { + final JSONObject o = new JSONObject() + .put("service", it.getServiceId()) + .put("url", it.getUrl()) + .put("name", it.getName()) + .put("thumb", it.getThumbnailUrl()); + if (it instanceof StreamInfoItem s) { + o.put("type", "stream") + .put("uploader", s.getUploaderName()) + .put("uploaderUrl", s.getUploaderUrl()) + .put("uploaderAvatar", s.getUploaderAvatarUrl()) + .put("verified", s.isUploaderVerified()) + .put("duration", s.getDuration()) + .put("views", s.getViewCount()) + .put("date", date(s.getUploadDate())) + .put("dateText", s.getTextualUploadDate()) + .put("live", s.getStreamType() == StreamType.LIVE_STREAM + || s.getStreamType() == StreamType.AUDIO_LIVE_STREAM) + .put("short", s.isShortFormContent()); + } else if (it instanceof ChannelInfoItem c) { + o.put("type", "channel") + .put("subs", c.getSubscriberCount()) + .put("streams", c.getStreamCount()) + .put("description", c.getDescription()) + .put("verified", c.isVerified()); + } else if (it instanceof PlaylistInfoItem p) { + o.put("type", "playlist") + .put("uploader", p.getUploaderName()) + .put("uploaderUrl", p.getUploaderUrl()) + .put("streams", p.getStreamCount()); + } else { + o.put("type", "other"); + } + return o; + } + + private static JSONArray items(final List list) { + final JSONArray a = new JSONArray(); + if (list != null) { + for (final InfoItem i : list) { + a.put(item(i)); + } + } + return a; + } + + private JSONObject list(final List list, final String next) { + return new JSONObject().put("items", items(list)).put("next", next == null ? JSONObject.NULL : next); + } + + // ---------------------------------------------------------------- endpoints + + JSONArray services() { + final JSONArray a = new JSONArray(); + for (final StreamingService s : NewPipe.getServices()) { + final JSONArray kiosks = new JSONArray(); + try { + for (final String k : s.getKioskList().getAvailableKiosks()) { + kiosks.put(k); + } + } catch (final Exception ignored) { + // service without kiosks + } + String defaultKiosk = null; + try { + defaultKiosk = s.getKioskList().getDefaultKioskId(); + } catch (final Exception ignored) { + // none + } + a.put(new JSONObject().put("id", s.getServiceId()).put("name", s.getServiceInfo().getName()) + .put("kiosks", kiosks).put("defaultKiosk", defaultKiosk == null ? JSONObject.NULL : defaultKiosk)); + } + return a; + } + + JSONObject kiosk(final Map q) throws Exception { + final StreamingService s = service(q.get("service")); + final String id = q.getOrDefault("id", s.getKioskList().getDefaultKioskId()); + final var extractor = s.getKioskList().getExtractorById(id, null); + extractor.fetchPage(); + final KioskInfo info = KioskInfo.getInfo(extractor); + return list(info.getRelatedItems(), cont("kiosk", s.getServiceId(), info.getUrl(), null, info.getNextPage())) + .put("title", info.getName()); + } + + JSONObject search(final Map q) throws Exception { + final StreamingService s = service(q.get("service")); + final var factory = s.getSearchQHFactory(); + final int filterId = q.containsKey("filter") ? Integer.parseInt(q.get("filter")) : 0; + FilterItem selected = factory.getFilterItem(filterId); + if (selected == null) { + selected = factory.getFilterItem(0); + } + final SearchQueryHandler handler = factory.fromQuery(Http.require(q, "q"), List.of(selected), null); + final SearchInfo info = SearchInfo.getInfo(s, handler); + final JSONArray filters = new JSONArray(); + try { + for (final var group : factory.getAvailableContentFilter().getFilterGroups()) { + for (final FilterItem f : group.filterItems) { + filters.put(new JSONObject().put("id", f.getIdentifier()).put("name", f.getName()) + .put("group", group.groupName == null ? "" : group.groupName)); + } + } + } catch (final Exception ignored) { + // service without filters + } + return list(info.getRelatedItems(), cont("search", s.getServiceId(), null, handler, info.getNextPage())) + .put("filters", filters).put("filter", selected.getIdentifier()) + .put("suggestion", info.getSearchSuggestion() == null ? JSONObject.NULL : info.getSearchSuggestion()) + .put("corrected", info.isCorrectedSearch()); + } + + JSONArray suggest(final Map q) throws Exception { + final StreamingService s = service(q.get("service")); + return new JSONArray(s.getSuggestionExtractor().suggestionList(Http.require(q, "q"))); + } + + /** Next page for any list produced earlier. */ + JSONObject more(final Map q) throws Exception { + final Cont c = continuations.get(Http.require(q, "next")); + if (c == null) { + throw new Http.HttpError(410, "continuation expired"); + } + final StreamingService s = NewPipe.getService(c.service()); + final InfoItemsPage page = switch (c.kind()) { + case "search" -> SearchInfo.getMoreItems(s, (SearchQueryHandler) c.handler(), c.page()); + case "kiosk" -> KioskInfo.getMoreItems(s, c.url(), c.page()); + case "channel" -> ChannelInfo.getMoreItems(s, c.url(), c.page()); + case "playlist" -> PlaylistInfo.getMoreItems(s, c.url(), c.page()); + case "comments" -> CommentsInfo.getMoreItems(s, c.url(), c.page()); + default -> throw new Http.HttpError(400, "unknown continuation"); + }; + final String next = cont(c.kind(), c.service(), c.url(), c.handler(), page.getNextPage()); + if ("comments".equals(c.kind())) { + return comments(page.getItems(), next); + } + return list(page.getItems(), next); + } + + JSONObject channel(final Map q) throws Exception { + final String url = Http.require(q, "url"); + final StreamingService s = NewPipe.getServiceByUrl(url); + final ChannelInfo info = ChannelInfo.getInfo(s, url); + return list(info.getRelatedItems(), cont("channel", s.getServiceId(), info.getUrl(), null, info.getNextPage())) + .put("service", s.getServiceId()) + .put("url", info.getUrl()) + .put("name", info.getName()) + .put("avatar", info.getAvatarUrl()) + .put("banner", info.getBannerUrl()) + .put("subs", info.getSubscriberCount()) + .put("description", info.getDescription()); + } + + JSONObject playlist(final Map q) throws Exception { + final String url = Http.require(q, "url"); + final StreamingService s = NewPipe.getServiceByUrl(url); + final PlaylistInfo info = PlaylistInfo.getInfo(s, url); + return list(info.getRelatedItems(), cont("playlist", s.getServiceId(), info.getUrl(), null, info.getNextPage())) + .put("service", s.getServiceId()) + .put("url", info.getUrl()) + .put("name", info.getName()) + .put("thumb", info.getThumbnailUrl()) + .put("uploader", info.getUploaderName()) + .put("uploaderUrl", info.getUploaderUrl()) + .put("count", info.getStreamCount()); + } + + private static JSONObject comments(final List list, final String next) { + final JSONArray a = new JSONArray(); + for (final InfoItem i : list) { + if (!(i instanceof CommentsInfoItem c)) { + continue; + } + final Description d = c.getCommentText(); + a.put(new JSONObject() + .put("author", c.getUploaderName()) + .put("authorUrl", c.getUploaderUrl()) + .put("avatar", c.getUploaderAvatarUrl()) + .put("text", d == null ? "" : d.getContent()) + .put("html", d != null && d.getType() == Description.HTML) + .put("likes", c.getLikeCount()) + .put("likesText", c.getTextualLikeCount()) + .put("date", c.getTextualUploadDate()) + .put("at", commentDate(c)) + .put("replies", c.getReplyCount())); + } + return new JSONObject().put("items", a).put("next", next == null ? JSONObject.NULL : next); + } + + private static Object commentDate(final CommentsInfoItem c) { + try { + return date(c.getUploadDate()); + } catch (final Exception e) { + return JSONObject.NULL; + } + } + + JSONObject commentsFor(final Map q) throws Exception { + final String url = Http.require(q, "url"); + final StreamingService s = NewPipe.getServiceByUrl(url); + final CommentsInfo info = CommentsInfo.getInfo(s, url); + if (info == null) { + return new JSONObject().put("items", new JSONArray()).put("disabled", true); + } + return comments(info.getRelatedItems(), cont("comments", s.getServiceId(), info.getUrl(), null, info.getNextPage())) + .put("disabled", info.isCommentsDisabled()); + } + + private StreamInfo streamInfo(final String url) throws Exception { + final Timed cached = streams.get(url); + if (cached != null && cached.fresh(TimeUnit.MINUTES.toMillis(90))) { + return cached.value(); + } + final StreamInfo info = StreamInfo.getInfo(NewPipe.getServiceByUrl(url), url); + streams.put(url, new Timed<>(info, System.currentTimeMillis())); + streams.put(info.getUrl(), new Timed<>(info, System.currentTimeMillis())); + return info; + } + + String mpd(final Map q) throws Exception { + final StreamInfo info = streamInfo(Http.require(q, "url")); + return Mpd.build(info, proxy, st -> headers(info, st)); + } + + /** Headers a service needs for media requests (see PipePipeClient MediaSourceBuilder). */ + static Map headers(final StreamInfo info, final Stream st) { + final Map h = new LinkedHashMap<>(); + if (info.getServiceId() == ServiceList.BiliBili.getServiceId()) { + h.put("Referer", "https://www.bilibili.com"); + } + if (st != null && st.getRequestHeaders() != null) { + h.putAll(st.getRequestHeaders()); + } + if (st != null && st.getContent().contains(COOKIE_MARKER)) { + final String frag = java.net.URLDecoder.decode( + st.getContent().substring(st.getContent().indexOf(COOKIE_MARKER) + COOKIE_MARKER.length()), + java.nio.charset.StandardCharsets.UTF_8); + final int len = frag.indexOf("&length="); + h.put("Cookie", len < 0 ? frag : frag.substring(0, len)); + } + return h; + } + + private static final String COOKIE_MARKER = "#cookie="; + + private static String bareUrl(final Stream st) { + final String c = st.getContent(); + final int i = c.indexOf(COOKIE_MARKER); + return i < 0 ? c : c.substring(0, i); + } + + private static boolean isHls(final Stream st) { + return st.isUrl() && (st.getDeliveryMethod() == DeliveryMethod.HLS + || java.net.URI.create(bareUrl(st)).getPath().endsWith(".m3u8")); + } + + private static boolean hlsSplit(final StreamInfo info) { + return info.getVideoOnlyStreams().stream().anyMatch(Api::isHls) + && info.getAudioStreams().stream().anyMatch(Api::isHls); + } + + /** Master playlist pairing separate video-only and audio HLS media playlists (NicoNico). */ + String hlsMaster(final Map q) throws Exception { + final StreamInfo info = streamInfo(Http.require(q, "url")); + final StringBuilder sb = new StringBuilder("#EXTM3U\n#EXT-X-INDEPENDENT-SEGMENTS\n"); + boolean first = true; + for (final AudioStream a : info.getAudioStreams()) { + if (!isHls(a)) { + continue; + } + sb.append("#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud\",NAME=\"") + .append(a.getAudioTrackName() == null ? "main" : a.getAudioTrackName().replace("\"", "")) + .append("\",DEFAULT=").append(first ? "YES" : "NO").append(",AUTOSELECT=YES,URI=\"") + .append(proxy.hls(bareUrl(a), headers(info, a))).append("\"\n"); + first = false; + } + for (final VideoStream v : info.getVideoOnlyStreams()) { + if (!isHls(v)) { + continue; + } + final int h = v.getHeight() > 0 ? v.getHeight() : parseHeight(v.getResolution()); + final int w = h * 16 / 9; + sb.append("#EXT-X-STREAM-INF:BANDWIDTH=").append(v.getBitrate() > 0 ? v.getBitrate() : Math.max(1, h) * 3000) + .append(",RESOLUTION=").append(w).append('x').append(h) + .append(",AUDIO=\"aud\"\n").append(proxy.hls(bareUrl(v), headers(info, v))).append('\n'); + } + return sb.toString(); + } + + private static int parseHeight(final String res) { + final var m = java.util.regex.Pattern.compile("(\\d{3,4})").matcher(res == null ? "" : res); + return m.find() ? Integer.parseInt(m.group(1)) : 720; + } + + JSONObject stream(final Map q) throws Exception { + final String url = Http.require(q, "url"); + final StreamInfo info = streamInfo(url); + final boolean live = info.getStreamType() == StreamType.LIVE_STREAM + || info.getStreamType() == StreamType.AUDIO_LIVE_STREAM; + + final JSONObject player = new JSONObject(); + final Map manifestHeaders = new LinkedHashMap<>(headers(info, null)); + if (info.getManifestRequestHeaders() != null) { + manifestHeaders.putAll(info.getManifestRequestHeaders()); + } + final String enc = java.net.URLEncoder.encode(info.getUrl(), java.nio.charset.StandardCharsets.UTF_8); + if (live && info.getHlsUrl() != null && !info.getHlsUrl().isEmpty()) { + player.put("mode", "hls").put("src", proxy.hls(info.getHlsUrl(), manifestHeaders)); + } else if (Mpd.canBuild(info)) { + player.put("mode", "dash").put("src", "/api/mpd?url=" + enc); + } else if (hlsSplit(info)) { + player.put("mode", "hls").put("src", "/api/hls?url=" + enc); + } else if (info.getHlsUrl() != null && !info.getHlsUrl().isEmpty()) { + player.put("mode", "hls").put("src", proxy.hls(info.getHlsUrl(), manifestHeaders)); + } else { + player.put("mode", "file"); + } + // progressive / split sources for the fallback player and for audio-only mode + final JSONArray muxed = new JSONArray(); + for (final VideoStream v : info.getVideoStreams()) { + if (v.isUrl()) { + muxed.put(new JSONObject().put("q", v.getResolution()).put("h", v.getHeight()) + .put("mime", v.getFormat() == null ? "" : v.getFormat().getMimeType()) + .put("src", proxy.media(bareUrl(v), headers(info, v)))); + } + } + final JSONArray videoOnly = new JSONArray(); + for (final VideoStream v : info.getVideoOnlyStreams()) { + if (v.isUrl()) { + videoOnly.put(new JSONObject().put("q", v.getResolution()).put("h", v.getHeight()) + .put("codec", v.getCodec()) + .put("mime", v.getFormat() == null ? "" : v.getFormat().getMimeType()) + .put("src", proxy.media(bareUrl(v), headers(info, v)))); + } + } + final JSONArray audio = new JSONArray(); + for (final AudioStream a : info.getAudioStreams()) { + if (a.isUrl()) { + audio.put(new JSONObject().put("kbps", a.getAverageBitrate()) + .put("mime", a.getFormat() == null ? "" : a.getFormat().getMimeType()) + .put("track", a.getAudioTrackName() == null ? JSONObject.NULL : a.getAudioTrackName()) + .put("src", proxy.media(bareUrl(a), headers(info, a)))); + } + } + player.put("muxed", muxed).put("videoOnly", videoOnly).put("audio", audio); + + final JSONArray subs = new JSONArray(); + for (final SubtitlesStream st : info.getSubtitles()) { + if (st.getFormat() == MediaFormat.VTT && st.isUrl()) { + subs.put(new JSONObject().put("lang", st.getLanguageTag()) + .put("name", st.getDisplayLanguageName() + (st.isAutoGenerated() ? " (auto)" : "")) + .put("auto", st.isAutoGenerated()) + .put("src", proxy.media(st.getContent(), headers(info, st)))); + } + } + final JSONArray chapters = new JSONArray(); + for (final StreamSegment seg : info.getStreamSegments()) { + chapters.put(new JSONObject().put("t", seg.getStartTimeSeconds()).put("title", seg.getTitle()) + .put("thumb", seg.getPreviewUrl() == null ? JSONObject.NULL : seg.getPreviewUrl())); + } + final Description d = info.getDescription(); + final JSONArray tags = new JSONArray(); + if (info.getTags() != null) { + info.getTags().forEach(tags::put); + } + return new JSONObject() + .put("service", info.getServiceId()) + .put("id", info.getId()) + .put("url", info.getUrl()) + .put("name", info.getName()) + .put("thumb", info.getThumbnailUrl()) + .put("duration", info.getDuration()) + .put("views", info.getViewCount()) + .put("likes", info.getLikeCount()) + .put("date", date(info.getUploadDate())) + .put("dateText", info.getTextualUploadDate()) + .put("live", live) + .put("uploader", new JSONObject() + .put("name", info.getUploaderName()) + .put("url", info.getUploaderUrl()) + .put("avatar", info.getUploaderAvatarUrl()) + .put("subs", info.getUploaderSubscriberCount()) + .put("verified", info.isUploaderVerified())) + .put("description", new JSONObject() + .put("html", d != null && d.getType() == Description.HTML) + .put("text", d == null ? "" : d.getContent())) + .put("tags", tags) + .put("category", info.getCategory()) + .put("startAt", info.getStartPosition()) + .put("player", player) + .put("subtitles", subs) + .put("chapters", chapters) + .put("related", items(info.getRelatedItems())); + } + + // ---------------------------------------------------------------- subscriptions feed + + private List channelFeed(final String url) throws Exception { + final Timed> c = feedCache.get(url); + if (c != null && c.fresh(TimeUnit.MINUTES.toMillis(20))) { + return c.value(); + } + final StreamingService s = NewPipe.getServiceByUrl(url); + List result; + final FeedExtractor fe = s.getFeedExtractor(url); + if (fe != null) { + result = FeedInfo.getInfo(fe).getRelatedItems(); + } else { + result = ChannelInfo.getInfo(s, url).getRelatedItems(); + } + if (result == null) { + result = List.of(); + } + feedCache.put(url, new Timed<>(result, System.currentTimeMillis())); + return result; + } + + JSONObject feed(final JSONArray subscriptions, final boolean refresh) throws Exception { + if (refresh) { + feedCache.clear(); + } + final Semaphore gate = new Semaphore(8); + final List>> jobs = new ArrayList<>(); + for (int i = 0; i < subscriptions.length(); i++) { + final String url = subscriptions.getJSONObject(i).getString("url"); + jobs.add(pool.submit(() -> { + gate.acquire(); + try { + return channelFeed(url); + } finally { + gate.release(); + } + })); + } + final List all = new ArrayList<>(); + int failed = 0; + for (final Future> f : jobs) { + try { + all.addAll(f.get(45, TimeUnit.SECONDS)); + } catch (final Exception e) { + failed++; + } + } + all.sort(Comparator.comparing((StreamInfoItem s) -> { + try { + return s.getUploadDate() == null ? OffsetDateTime.MIN : s.getUploadDate().offsetDateTime(); + } catch (final Exception e) { + return OffsetDateTime.MIN; + } + }).reversed()); + return new JSONObject().put("items", items(all.size() > 600 ? all.subList(0, 600) : all)) + .put("failed", failed).put("next", JSONObject.NULL); + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/DesktopDownloader.java b/desktop/src/main/java/dev/pipepipe/desktop/DesktopDownloader.java new file mode 100644 index 000000000..6818b427f --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/DesktopDownloader.java @@ -0,0 +1,190 @@ +package dev.pipepipe.desktop; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import org.schabi.newpipe.extractor.downloader.CancellableCall; +import org.schabi.newpipe.extractor.downloader.Downloader; +import org.schabi.newpipe.extractor.downloader.Request; +import org.schabi.newpipe.extractor.downloader.Response; +import org.schabi.newpipe.extractor.downloader.StreamingResponse; +import org.schabi.newpipe.extractor.exceptions.ReCaptchaException; +import org.schabi.newpipe.extractor.localization.Localization; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Desktop port of PipePipeClient's DownloaderImpl: OkHttp based, no Android dependencies. + */ +public final class DesktopDownloader extends Downloader { + public static final String USER_AGENT = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"; + + private final OkHttpClient client; + + public DesktopDownloader() { + final Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequests(64); + dispatcher.setMaxRequestsPerHost(16); + this.client = new OkHttpClient.Builder() + .dispatcher(dispatcher) + .connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES)) + .connectTimeout(15, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .build(); + } + + public OkHttpClient client() { + return client; + } + + private static boolean isChallenge(final okhttp3.Response r) { + if (r.code() == 429 || "challenge".equalsIgnoreCase(r.header("cf-mitigated"))) { + return true; + } + final String host = r.request().url().host(); + return host.endsWith("google.com") && r.request().url().encodedPath().startsWith("/sorry"); + } + + private okhttp3.Request build(final Request request) { + final byte[] data = request.dataToSend(); + RequestBody body = null; + if (data != null) { + body = RequestBody.create(data); + } else if ("POST".equals(request.httpMethod())) { + body = RequestBody.create(new byte[0]); + } + final okhttp3.Request.Builder b = new okhttp3.Request.Builder() + .method(request.httpMethod(), body).url(request.url()); + final Map> headers = request.headers(); + if (!headers.containsKey("User-Agent")) { + b.header("User-Agent", USER_AGENT); + } + for (final Map.Entry> e : headers.entrySet()) { + final List values = e.getValue(); + if (values.size() > 1) { + b.removeHeader(e.getKey()); + for (final String v : values) { + b.addHeader(e.getKey(), v); + } + } else if (values.size() == 1) { + b.header(e.getKey(), values.get(0)); + } + } + return b.build(); + } + + private OkHttpClient clientFor(final Request request) { + if (request.followRedirects()) { + return client; + } + return client.newBuilder().followRedirects(false).followSslRedirects(false).build(); + } + + private static Response toResponse(final okhttp3.Response response) throws IOException { + final ResponseBody body = response.body(); + final byte[] raw = body.bytes(); + return new Response(response.code(), response.message(), response.headers().toMultimap(), + new String(raw, StandardCharsets.UTF_8), raw, response.request().url().toString()); + } + + @Override + public Response execute(@Nonnull final Request request) throws IOException, ReCaptchaException { + try (okhttp3.Response response = clientFor(request).newCall(build(request)).execute()) { + if (isChallenge(response)) { + throw new ReCaptchaException("reCaptcha Challenge requested", request.url()); + } + return toResponse(response); + } + } + + @Override + public StreamingResponse getStreaming(final String url, + @Nullable final Map> headers, + @Nullable final Localization localization) + throws IOException, ReCaptchaException { + return streaming(Request.newBuilder().get(url).headers(headers) + .localization(localization).build(), client); + } + + @Override + public StreamingResponse getStreaming(final String url, + @Nullable final Map> headers, + @Nullable final Localization localization, + final long timeoutMs) + throws IOException, ReCaptchaException { + final long t = Math.max(1, timeoutMs); + return streaming(Request.newBuilder().get(url).headers(headers) + .localization(localization).build(), client.newBuilder() + .callTimeout(t, TimeUnit.MILLISECONDS) + .readTimeout(t, TimeUnit.MILLISECONDS).build()); + } + + @Override + public StreamingResponse postStreaming(final String url, + @Nullable final Map> headers, + @Nullable final byte[] dataToSend, + @Nullable final Localization localization) + throws IOException, ReCaptchaException { + return streaming(Request.newBuilder().post(url, dataToSend).headers(headers) + .localization(localization).build(), client); + } + + private StreamingResponse streaming(final Request request, final OkHttpClient c) + throws IOException, ReCaptchaException { + final okhttp3.Response response = c.newCall(build(request)).execute(); + if (isChallenge(response)) { + response.close(); + throw new ReCaptchaException("reCaptcha Challenge requested", request.url()); + } + final ResponseBody body = response.body(); + final InputStream in = body == null ? new ByteArrayInputStream(new byte[0]) : body.byteStream(); + return new StreamingResponse(response.code(), response.headers().toMultimap(), in); + } + + @Override + public CancellableCall executeAsync(@Nonnull final Request request, + final AsyncCallback callback) { + final Call call = clientFor(request).newCall(build(request)); + final CancellableCall cancellable = new CancellableCall(call); + call.enqueue(new Callback() { + @Override + public void onFailure(@Nonnull final Call c, @Nonnull final IOException e) { + try { + callback.onError(e); + } finally { + cancellable.setFinished(); + } + } + + @Override + public void onResponse(@Nonnull final Call c, @Nonnull final okhttp3.Response response) { + try (response) { + if (isChallenge(response)) { + callback.onError(new ReCaptchaException("reCaptcha Challenge requested", + request.url())); + return; + } + callback.onSuccess(toResponse(response)); + } catch (final Exception e) { + callback.onError(e); + } finally { + cancellable.setFinished(); + } + } + }); + return cancellable; + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/Http.java b/desktop/src/main/java/dev/pipepipe/desktop/Http.java new file mode 100644 index 000000000..0cc5747fe --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/Http.java @@ -0,0 +1,78 @@ +package dev.pipepipe.desktop; + +import com.sun.net.httpserver.HttpExchange; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +/** Small helpers around the JDK HttpServer exchange. */ +final class Http { + private Http() { } + + static final class HttpError extends RuntimeException { + final int status; + + HttpError(final int status, final String message) { + super(message); + this.status = status; + } + } + + static Map query(final HttpExchange ex) { + final Map out = new HashMap<>(); + final String raw = ex.getRequestURI().getRawQuery(); + if (raw == null || raw.isEmpty()) { + return out; + } + for (final String part : raw.split("&")) { + final int i = part.indexOf('='); + final String k = i < 0 ? part : part.substring(0, i); + final String v = i < 0 ? "" : part.substring(i + 1); + out.put(URLDecoder.decode(k, StandardCharsets.UTF_8), + URLDecoder.decode(v, StandardCharsets.UTF_8)); + } + return out; + } + + static String require(final Map q, final String key) { + final String v = q.get(key); + if (v == null || v.isBlank()) { + throw new HttpError(400, "missing parameter: " + key); + } + return v; + } + + static byte[] body(final HttpExchange ex) throws IOException { + try (InputStream in = ex.getRequestBody()) { + return in.readAllBytes(); + } + } + + static void json(final HttpExchange ex, final int status, final Object payload) throws IOException { + final String text = payload instanceof JSONObject o ? o.toString() + : payload instanceof JSONArray a ? a.toString() : String.valueOf(payload); + send(ex, status, "application/json; charset=utf-8", text.getBytes(StandardCharsets.UTF_8)); + } + + static void send(final HttpExchange ex, final int status, final String type, final byte[] data) + throws IOException { + ex.getResponseHeaders().set("Content-Type", type); + if (!ex.getResponseHeaders().containsKey("Cache-Control")) { + ex.getResponseHeaders().set("Cache-Control", "no-store"); + } + ex.sendResponseHeaders(status, data.length == 0 ? -1 : data.length); + if (data.length > 0) { + try (OutputStream os = ex.getResponseBody()) { + os.write(data); + } + } + ex.close(); + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/Main.java b/desktop/src/main/java/dev/pipepipe/desktop/Main.java new file mode 100644 index 000000000..6201d2063 --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/Main.java @@ -0,0 +1,234 @@ +package dev.pipepipe.desktop; + +import org.schabi.newpipe.extractor.NewPipe; + +import java.awt.Desktop; +import java.io.File; +import java.net.HttpURLConnection; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * PipePipe Desktop entry point. + *
+ *   pipepipe-desktop                 start + open an app window (Chrome/Edge/Chromium app mode)
+ *   pipepipe-desktop --server        headless web server only
+ *   options: --host 127.0.0.1  --port 47615  --data DIR  --web DIR (serve UI from disk, dev)
+ * 
+ */ +public final class Main { + static final int DEFAULT_PORT = 47615; + + private Main() { } + + public static void main(final String[] args) throws Exception { + String host = "127.0.0.1"; + int port = DEFAULT_PORT; + boolean serverOnly = false; + Path data = defaultDataDir(); + Path web = null; + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--server" -> serverOnly = true; + case "--host" -> host = args[++i]; + case "--port" -> port = Integer.parseInt(args[++i]); + case "--data" -> data = Path.of(args[++i]); + case "--web" -> web = Path.of(args[++i]); + case "-h", "--help" -> { + System.out.println("usage: pipepipe-desktop [--server] [--host H] [--port P] [--data DIR]"); + return; + } + default -> System.err.println("unknown option " + args[i]); + } + } + Files.createDirectories(data); + + final String local = "http://127.0.0.1:" + port + "/"; + if (!serverOnly && isOurs(local)) { + // already running: just bring up another window + openWindow(local, data); + return; + } + + final DesktopDownloader downloader = new DesktopDownloader(); + NewPipe.init(downloader); + silenceExtractorLogs(); + Server server; + try { + server = new Server(host, port, downloader, new Store(data), web); + } catch (final java.net.BindException e) { + server = new Server(host, 0, downloader, new Store(data), web); + } + server.start(); + final String url = "http://127.0.0.1:" + server.port() + "/"; + System.out.println("PipePipe Desktop running at " + url + " (data: " + data + ")"); + if (!"127.0.0.1".equals(host) && !"localhost".equals(host)) { + System.out.println("WARNING: listening on " + host + " - anyone on this network can use it."); + } + if (serverOnly) { + return; // HTTP server threads keep the JVM alive + } + final Process window = openWindow(url, data); + if (window != null) { + // dedicated browser profile: when the window closes, the app quits. + // A process that exits right away handed off to an already running browser + // instance, so we cannot tell when the window closes -> keep running with a tray icon. + final long started = System.currentTimeMillis(); + window.waitFor(); + if (System.currentTimeMillis() - started > 4000) { + server.stop(); + System.exit(0); + } + } + final Server s = server; + tray(url, data, () -> { + s.stop(); + System.exit(0); + }); + } + + /** Tray icon with open / quit, used when we do not own the window process. */ + private static void tray(final String url, final Path data, final Runnable quit) { + try { + if (java.awt.GraphicsEnvironment.isHeadless() || !java.awt.SystemTray.isSupported()) { + System.out.println("Running. Press Ctrl+C to quit."); + return; + } + final java.awt.Image img; + try (var in = Main.class.getResourceAsStream("/web/icon.png")) { + img = javax.imageio.ImageIO.read(in); + } + final java.awt.PopupMenu menu = new java.awt.PopupMenu(); + final java.awt.MenuItem open = new java.awt.MenuItem("Open PipePipe"); + open.addActionListener(e -> openWindow(url, data)); + final java.awt.MenuItem exit = new java.awt.MenuItem("Quit"); + exit.addActionListener(e -> quit.run()); + menu.add(open); + menu.add(exit); + final java.awt.TrayIcon icon = new java.awt.TrayIcon(img, "PipePipe", menu); + icon.setImageAutoSize(true); + icon.addActionListener(e -> openWindow(url, data)); + java.awt.SystemTray.getSystemTray().add(icon); + } catch (final Exception e) { + System.out.println("Running at " + url + " - press Ctrl+C to quit."); + } + } + + /** The extractor prints a YT_PERF timing line per request; hide them unless debugging. */ + private static void silenceExtractorLogs() { + if (!"1".equals(System.getenv("PIPEPIPE_DEBUG"))) { + final var original = System.out; + System.setOut(new java.io.PrintStream(original, true) { + @Override + public void println(final String x) { + if (x == null || !x.startsWith("YT_PERF")) { + super.println(x); + } + } + }); + } + } + + private static boolean isOurs(final String base) { + try { + final HttpURLConnection c = (HttpURLConnection) URI.create(base + "api/ping").toURL().openConnection(); + c.setConnectTimeout(300); + c.setReadTimeout(600); + return c.getResponseCode() == 200 + && new String(c.getInputStream().readAllBytes()).contains("pipepipe-desktop"); + } catch (final Exception e) { + return false; + } + } + + static Path defaultDataDir() { + final String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); + final String home = System.getProperty("user.home"); + if (os.contains("win")) { + final String appData = System.getenv("APPDATA"); + return Path.of(appData != null ? appData : home, "PipePipe Desktop"); + } + if (os.contains("mac")) { + return Path.of(home, "Library", "Application Support", "PipePipe Desktop"); + } + final String xdg = System.getenv("XDG_DATA_HOME"); + return Path.of(xdg != null && !xdg.isBlank() ? xdg : home + "/.local/share", "pipepipe-desktop"); + } + + private static List browserCandidates() { + final String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); + final List c = new ArrayList<>(); + final String custom = System.getenv("PIPEPIPE_BROWSER"); + if (custom != null && !custom.isBlank()) { + c.add(custom); + } + if (os.contains("win")) { + for (final String env : new String[]{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"}) { + final String base = System.getenv(env); + if (base == null) { + continue; + } + c.add(base + "\\Microsoft\\Edge\\Application\\msedge.exe"); + c.add(base + "\\Google\\Chrome\\Application\\chrome.exe"); + c.add(base + "\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"); + c.add(base + "\\Chromium\\Application\\chrome.exe"); + } + } else if (os.contains("mac")) { + for (final String app : new String[]{"Google Chrome", "Microsoft Edge", "Chromium", "Brave Browser", "Vivaldi"}) { + c.add("/Applications/" + app + ".app/Contents/MacOS/" + app); + c.add(System.getProperty("user.home") + "/Applications/" + app + ".app/Contents/MacOS/" + app); + } + } else { + final String path = System.getenv("PATH") == null ? "/usr/bin" : System.getenv("PATH"); + for (final String name : new String[]{"google-chrome", "google-chrome-stable", "chromium", + "chromium-browser", "microsoft-edge", "microsoft-edge-stable", "brave-browser", "vivaldi"}) { + for (final String dir : path.split(File.pathSeparator)) { + c.add(dir + "/" + name); + } + } + c.add("/var/lib/flatpak/exports/bin/com.google.Chrome"); + c.add("/var/lib/flatpak/exports/bin/org.chromium.Chromium"); + c.add("/snap/bin/chromium"); + } + return c; + } + + /** @return the window process when launched in a dedicated app-mode profile, else null */ + static Process openWindow(final String url, final Path data) { + for (final String exe : browserCandidates()) { + final File f = new File(exe); + if (!f.isFile() || !f.canExecute()) { + continue; + } + try { + return new ProcessBuilder(exe, + "--app=" + url, + "--user-data-dir=" + data.resolve("window"), + "--window-size=1440,900", + "--no-first-run", "--no-default-browser-check", + "--disable-features=Translate,MediaRouter", + "--autoplay-policy=no-user-gesture-required", + "--class=PipePipe") + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (final Exception e) { + System.err.println("could not start " + exe + ": " + e.getMessage()); + } + } + try { + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + Desktop.getDesktop().browse(URI.create(url)); + } else { + System.out.println("Open " + url + " in your browser."); + } + } catch (final Exception e) { + System.out.println("Open " + url + " in your browser."); + } + return null; + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/MediaProxy.java b/desktop/src/main/java/dev/pipepipe/desktop/MediaProxy.java new file mode 100644 index 000000000..c263f5389 --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/MediaProxy.java @@ -0,0 +1,189 @@ +package dev.pipepipe.desktop; + +import com.sun.net.httpserver.HttpExchange; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.json.JSONObject; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Streams remote media through the local server so the browser never needs CORS or special + * headers (Referer for BiliBili etc). Targets are HMAC-signed so the proxy cannot be abused as + * an open relay when the server is exposed on a LAN. + */ +final class MediaProxy { + /** YouTube throttles very long open-ended range requests; serve them in chunks instead. */ + private static final long CHUNK = 8L * 1024 * 1024; + private static final Pattern URI_ATTR = Pattern.compile("URI=\"([^\"]+)\""); + + private final OkHttpClient client; + private final byte[] key = new byte[32]; + + MediaProxy(final OkHttpClient client) { + this.client = client.newBuilder().followRedirects(true).build(); + new SecureRandom().nextBytes(key); + } + + /** @return local path for proxied media */ + String media(final String url, final Map headers) { + return "/px/" + sign(url, headers); + } + + /** @return local path for a proxied (rewritten) HLS playlist */ + String hls(final String url, final Map headers) { + return "/hx/" + sign(url, headers) + "/index.m3u8"; + } + + private String sign(final String url, final Map headers) { + final JSONObject o = new JSONObject().put("u", url); + if (headers != null && !headers.isEmpty()) { + o.put("h", new JSONObject(headers)); + } + final String payload = Base64.getUrlEncoder().withoutPadding() + .encodeToString(o.toString().getBytes(StandardCharsets.UTF_8)); + return payload + "." + mac(payload); + } + + private String mac(final String payload) { + try { + final Mac m = Mac.getInstance("HmacSHA256"); + m.init(new SecretKeySpec(key, "HmacSHA256")); + final byte[] d = m.doFinal(payload.getBytes(StandardCharsets.US_ASCII)); + return Base64.getUrlEncoder().withoutPadding().encodeToString(d).substring(0, 22); + } catch (final Exception e) { + throw new IllegalStateException(e); + } + } + + private JSONObject verify(final String token) { + final int dot = token.lastIndexOf('.'); + if (dot < 0) { + throw new Http.HttpError(403, "bad token"); + } + final String payload = token.substring(0, dot); + if (!MessageDigest.isEqual(mac(payload).getBytes(StandardCharsets.US_ASCII), + token.substring(dot + 1).getBytes(StandardCharsets.US_ASCII))) { + throw new Http.HttpError(403, "bad signature"); + } + return new JSONObject(new String(Base64.getUrlDecoder().decode(payload), + StandardCharsets.UTF_8)); + } + + private Request.Builder request(final JSONObject target) { + final Request.Builder b = new Request.Builder().url(target.getString("u")) + .header("User-Agent", DesktopDownloader.USER_AGENT); + final JSONObject h = target.optJSONObject("h"); + if (h != null) { + for (final String k : h.keySet()) { + b.header(k, h.getString(k)); + } + } + return b; + } + + void handleMedia(final HttpExchange ex, final String token) throws IOException { + final JSONObject target = verify(token); + final Request.Builder rb = request(target); + String range = ex.getRequestHeaders().getFirst("Range"); + final boolean youtube = target.getString("u").contains("googlevideo.com"); + if (youtube) { + // open ended "bytes=N-" -> bounded chunk, the browser asks for the rest itself + final Matcher m = Pattern.compile("bytes=(\\d+)-$").matcher(range == null ? "bytes=0-" : range); + if (m.matches()) { + final long start = Long.parseLong(m.group(1)); + range = "bytes=" + start + "-" + (start + CHUNK - 1); + } + } + if (range != null) { + rb.header("Range", range); + } + if ("HEAD".equals(ex.getRequestMethod())) { + rb.head(); + } + try (Response r = client.newCall(rb.build()).execute()) { + final var out = ex.getResponseHeaders(); + for (final String h : new String[]{"Content-Type", "Content-Length", "Content-Range", + "Accept-Ranges", "Last-Modified", "ETag"}) { + final String v = r.header(h); + if (v != null) { + out.set(h, v); + } + } + out.set("Accept-Ranges", "bytes"); + out.set("Cache-Control", "private, max-age=3600"); + out.set("Access-Control-Allow-Origin", "*"); + final String len = r.header("Content-Length"); + final long length = len == null ? 0 : Long.parseLong(len); + if ("HEAD".equals(ex.getRequestMethod())) { + ex.sendResponseHeaders(r.code(), -1); + ex.close(); + return; + } + ex.sendResponseHeaders(r.code(), length > 0 ? length : 0); + try (InputStream in = r.body().byteStream(); OutputStream os = ex.getResponseBody()) { + in.transferTo(os); + } catch (final IOException ignored) { + // client went away (seek / quality switch) - normal + } + } finally { + ex.close(); + } + } + + void handleHls(final HttpExchange ex, final String token) throws IOException { + final JSONObject target = verify(token); + final String base = target.getString("u"); + final Map headers = target.optJSONObject("h") == null ? null + : target.getJSONObject("h").toMap().entrySet().stream().collect( + java.util.stream.Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); + final String text; + try (Response r = client.newCall(request(target).build()).execute()) { + if (!r.isSuccessful()) { + throw new Http.HttpError(502, "upstream " + r.code()); + } + text = r.body().string(); + } + final URI baseUri = URI.create(base); + final StringBuilder sb = new StringBuilder(text.length() * 2); + for (final String line : text.split("\r?\n")) { + if (line.isBlank()) { + sb.append('\n'); + } else if (line.startsWith("#")) { + final Matcher m = URI_ATTR.matcher(line); + final StringBuilder rewritten = new StringBuilder(); + while (m.find()) { + m.appendReplacement(rewritten, Matcher.quoteReplacement( + "URI=\"" + rewrite(baseUri, m.group(1), headers) + "\"")); + } + m.appendTail(rewritten); + sb.append(rewritten).append('\n'); + } else { + sb.append(rewrite(baseUri, line.trim(), headers)).append('\n'); + } + } + ex.getResponseHeaders().set("Access-Control-Allow-Origin", "*"); + Http.send(ex, 200, "application/vnd.apple.mpegurl", sb.toString().getBytes(StandardCharsets.UTF_8)); + } + + private String rewrite(final URI base, final String ref, final Map headers) { + final String abs = base.resolve(ref).toString(); + final String path = URI.create(abs).getPath(); + final boolean playlist = path.endsWith(".m3u8") || abs.contains("/hls_playlist/") + || abs.contains("/hls_variant/") || abs.contains("playlist/index.m3u8"); + return playlist ? hls(abs, headers) : media(abs, headers); + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/Mpd.java b/desktop/src/main/java/dev/pipepipe/desktop/Mpd.java new file mode 100644 index 000000000..1c98f9e83 --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/Mpd.java @@ -0,0 +1,144 @@ +package dev.pipepipe.desktop; + +import org.schabi.newpipe.extractor.stream.AudioStream; +import org.schabi.newpipe.extractor.stream.Stream; +import org.schabi.newpipe.extractor.stream.StreamInfo; +import org.schabi.newpipe.extractor.stream.VideoStream; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Builds a static DASH manifest out of the progressive (byte-range indexed) streams the + * extractor returns, so the browser can do adaptive playback up to 4K via MSE. + */ +final class Mpd { + private Mpd() { } + + static boolean indexed(final Stream s) { + if (!s.isUrl() || s.getDeliveryMethod() != org.schabi.newpipe.extractor.stream.DeliveryMethod.PROGRESSIVE_HTTP) { + return false; + } + if (s instanceof VideoStream v) { + return v.getIndexEnd() > 0 && v.getInitEnd() > 0; + } + if (s instanceof AudioStream a) { + return a.getIndexEnd() > 0 && a.getInitEnd() > 0; + } + return false; + } + + static boolean canBuild(final StreamInfo info) { + return info.getVideoOnlyStreams().stream().anyMatch(Mpd::indexed) + && info.getAudioStreams().stream().anyMatch(Mpd::indexed); + } + + private static String esc(final String s) { + return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } + + static String build(final StreamInfo info, final MediaProxy proxy, + final java.util.function.Function> headers) { + long durationMs = info.getDuration() * 1000L; + for (final VideoStream v : info.getVideoOnlyStreams()) { + if (v.getItagItem() != null && v.getItagItem().getApproxDurationMs() > 0) { + durationMs = v.getItagItem().getApproxDurationMs(); + break; + } + } + if (durationMs <= 0) { + durationMs = 1000L * 60 * 60 * 3; + } + final StringBuilder sb = new StringBuilder(8192); + sb.append("\n") + .append("\n\n"); + + // video: group by container + codec family + final Map> videoSets = new LinkedHashMap<>(); + for (final VideoStream v : info.getVideoOnlyStreams()) { + if (!indexed(v) || v.getFormat() == null) { + continue; + } + final String codec = v.getCodec() == null ? "" : v.getCodec(); + final String family = codec.contains(".") ? codec.substring(0, codec.indexOf('.')) : codec; + videoSets.computeIfAbsent(v.getFormat().getMimeType() + "|" + family, k -> new ArrayList<>()).add(v); + } + int setId = 0; + for (final Map.Entry> e : videoSets.entrySet()) { + final String mime = e.getKey().split("\\|")[0]; + sb.append("\n"); + for (final VideoStream v : e.getValue()) { + sb.append(" 0 ? v.getBitrate() : 1000000)).append('"'); + if (v.getWidth() > 0) { + sb.append(" width=\"").append(v.getWidth()).append("\" height=\"").append(v.getHeight()).append('"'); + } + if (v.getFps() > 0) { + sb.append(" frameRate=\"").append(v.getFps()).append('"'); + } + sb.append(">\n").append(esc(proxy.media(v.getContent(), headers.apply(v)))) + .append("\n\n\n"); + } + sb.append("\n"); + } + + // audio: group by track (language / dubbing) + container + final Map> audioSets = new LinkedHashMap<>(); + for (final AudioStream a : info.getAudioStreams()) { + if (!indexed(a) || a.getFormat() == null) { + continue; + } + final String track = a.getAudioTrackId() == null ? "" : a.getAudioTrackId(); + audioSets.computeIfAbsent(track + "|" + a.getFormat().getMimeType(), k -> new ArrayList<>()).add(a); + } + for (final Map.Entry> e : audioSets.entrySet()) { + final AudioStream first = e.getValue().get(0); + final String mime = e.getKey().substring(e.getKey().indexOf('|') + 1); + sb.append("\n"); + final String name = first.getAudioTrackName() == null ? "" : first.getAudioTrackName().toLowerCase(Locale.ROOT); + if (audioSets.size() > 2 && (name.contains("original") || name.contains("원본"))) { + sb.append("\n"); + } + for (final AudioStream a : e.getValue()) { + final var it = a.getItagItem(); + sb.append(" 0 ? a.getBitrate() : a.getAverageBitrate() * 1000)).append('"'); + if (it != null && it.getSampleRate() > 0) { + sb.append(" audioSamplingRate=\"").append(it.getSampleRate()).append('"'); + } + sb.append(">\n"); + final int ch = it == null || it.getAudioChannels() <= 0 ? 2 : it.getAudioChannels(); + sb.append("\n"); + sb.append("").append(esc(proxy.media(a.getContent(), headers.apply(a)))) + .append("\n\n\n"); + } + sb.append("\n"); + } + sb.append("\n\n"); + return sb.toString(); + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/Server.java b/desktop/src/main/java/dev/pipepipe/desktop/Server.java new file mode 100644 index 000000000..b858f9767 --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/Server.java @@ -0,0 +1,184 @@ +package dev.pipepipe.desktop; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.json.JSONArray; +import org.json.JSONObject; +import org.schabi.newpipe.extractor.NewPipe; +import org.schabi.newpipe.extractor.exceptions.ContentNotAvailableException; +import org.schabi.newpipe.extractor.exceptions.ReCaptchaException; +import org.schabi.newpipe.extractor.localization.ContentCountry; +import org.schabi.newpipe.extractor.localization.Localization; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.Executors; + +/** HTTP server: JSON API, media proxy and the static web UI. */ +final class Server { + private static final Map TYPES = Map.of( + "html", "text/html; charset=utf-8", "js", "text/javascript; charset=utf-8", + "css", "text/css; charset=utf-8", "svg", "image/svg+xml", "png", "image/png", + "ico", "image/x-icon", "json", "application/json", "woff2", "font/woff2"); + + private final HttpServer http; + private final Api api; + private final MediaProxy proxy; + private final Store store; + private final Path webDir; + + Server(final String host, final int port, final DesktopDownloader downloader, final Store store, + final Path webDir) throws IOException { + this.proxy = new MediaProxy(downloader.client()); + this.api = new Api(proxy); + this.store = store; + this.webDir = webDir; + this.http = HttpServer.create(new InetSocketAddress(host, port), 256); + http.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); + http.createContext("/", this::handle); + applySettings(); + } + + int port() { + return http.getAddress().getPort(); + } + + void start() { + http.start(); + } + + void stop() { + http.stop(0); + } + + private void applySettings() { + try { + final String raw = store.read("settings"); + if (raw == null || "null".equals(raw.trim())) { + return; + } + final JSONObject s = new JSONObject(raw); + final String lang = s.optString("language", ""); + final String country = s.optString("country", ""); + if (!lang.isEmpty() || !country.isEmpty()) { + final String l = lang.isEmpty() ? "en" : lang; + final String c = country.isEmpty() ? "US" : country; + NewPipe.setupLocalization(new Localization(l, c), new ContentCountry(c)); + } + } catch (final Exception e) { + System.err.println("settings: " + e); + } + } + + private void handle(final HttpExchange ex) { + final String path = ex.getRequestURI().getPath(); + try { + if (path.startsWith("/px/")) { + proxy.handleMedia(ex, path.substring(4)); + } else if (path.startsWith("/hx/")) { + final String rest = path.substring(4); + proxy.handleHls(ex, rest.contains("/") ? rest.substring(0, rest.indexOf('/')) : rest); + } else if (path.startsWith("/api/")) { + api(ex, path.substring(5)); + } else { + serveStatic(ex, path); + } + } catch (final Http.HttpError e) { + error(ex, e.status, e.getMessage()); + } catch (final ReCaptchaException e) { + error(ex, 429, "The service is rate limiting this IP (captcha). Try again later."); + } catch (final ContentNotAvailableException e) { + error(ex, 404, e.getMessage() == null ? "Content not available" : e.getMessage()); + } catch (final Throwable e) { + e.printStackTrace(); + error(ex, 500, e.getClass().getSimpleName() + ": " + e.getMessage()); + } + } + + private static void error(final HttpExchange ex, final int status, final String message) { + try { + Http.json(ex, status, new JSONObject().put("error", message == null ? "error" : message)); + } catch (final IOException ignored) { + ex.close(); + } + } + + private void api(final HttpExchange ex, final String route) throws Exception { + final Map q = Http.query(ex); + switch (route) { + case "ping" -> Http.json(ex, 200, new JSONObject().put("app", "pipepipe-desktop")); + case "services" -> Http.json(ex, 200, api.services()); + case "kiosk" -> Http.json(ex, 200, api.kiosk(q)); + case "search" -> Http.json(ex, 200, api.search(q)); + case "suggest" -> Http.json(ex, 200, api.suggest(q)); + case "more" -> Http.json(ex, 200, api.more(q)); + case "stream" -> Http.json(ex, 200, api.stream(q)); + case "comments" -> Http.json(ex, 200, api.commentsFor(q)); + case "channel" -> Http.json(ex, 200, api.channel(q)); + case "playlist" -> Http.json(ex, 200, api.playlist(q)); + case "mpd" -> Http.send(ex, 200, "application/dash+xml", + api.mpd(q).getBytes(StandardCharsets.UTF_8)); + case "hls" -> { + ex.getResponseHeaders().set("Access-Control-Allow-Origin", "*"); + Http.send(ex, 200, "application/vnd.apple.mpegurl", api.hlsMaster(q).getBytes(StandardCharsets.UTF_8)); + } + case "feed" -> { + final String raw = store.read("subscriptions"); + final JSONArray subs = raw == null || "null".equals(raw.trim()) ? new JSONArray() : new JSONArray(raw); + Http.json(ex, 200, api.feed(subs, "1".equals(q.get("refresh")))); + } + default -> { + if (route.startsWith("store/")) { + final String name = route.substring(6); + if ("PUT".equals(ex.getRequestMethod()) || "POST".equals(ex.getRequestMethod())) { + final String body = new String(Http.body(ex), StandardCharsets.UTF_8); + // validate before persisting + if (body.trim().startsWith("[")) { + new JSONArray(body); + } else { + new JSONObject(body); + } + store.write(name, body); + if ("settings".equals(name)) { + applySettings(); + } + Http.json(ex, 200, new JSONObject().put("ok", true)); + } else { + Http.send(ex, 200, "application/json; charset=utf-8", + store.read(name).getBytes(StandardCharsets.UTF_8)); + } + } else { + throw new Http.HttpError(404, "no such endpoint"); + } + } + } + } + + private void serveStatic(final HttpExchange ex, final String rawPath) throws IOException { + String path = rawPath.equals("/") || !rawPath.contains(".") ? "/index.html" : rawPath; + if (path.contains("..")) { + throw new Http.HttpError(400, "bad path"); + } + final byte[] data; + if (webDir != null) { + final Path f = webDir.resolve(path.substring(1)); + data = Files.exists(f) ? Files.readAllBytes(f) : null; + } else { + try (InputStream in = Server.class.getResourceAsStream("/web" + path)) { + data = in == null ? null : in.readAllBytes(); + } + } + if (data == null) { + throw new Http.HttpError(404, "not found"); + } + final String ext = path.substring(path.lastIndexOf('.') + 1); + ex.getResponseHeaders().set("Cache-Control", webDir != null || path.endsWith(".html") + ? "no-cache" : "public, max-age=86400"); + Http.send(ex, 200, TYPES.getOrDefault(ext, "application/octet-stream"), data); + } +} diff --git a/desktop/src/main/java/dev/pipepipe/desktop/Store.java b/desktop/src/main/java/dev/pipepipe/desktop/Store.java new file mode 100644 index 000000000..b135e80e7 --- /dev/null +++ b/desktop/src/main/java/dev/pipepipe/desktop/Store.java @@ -0,0 +1,38 @@ +package dev.pipepipe.desktop; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Set; + +/** Local JSON documents (subscriptions, history, playlists, settings) in the data directory. */ +final class Store { + static final Set NAMES = Set.of("subscriptions", "history", "playlists", "settings"); + private final Path dir; + + Store(final Path dataDir) throws IOException { + this.dir = dataDir.resolve("store"); + Files.createDirectories(dir); + } + + private Path file(final String name) { + if (!NAMES.contains(name)) { + throw new Http.HttpError(404, "unknown store " + name); + } + return dir.resolve(name + ".json"); + } + + synchronized String read(final String name) throws IOException { + final Path f = file(name); + return Files.exists(f) ? Files.readString(f, StandardCharsets.UTF_8) : "null"; + } + + synchronized void write(final String name, final String json) throws IOException { + final Path f = file(name); + final Path tmp = f.resolveSibling(name + ".json.tmp"); + Files.writeString(tmp, json, StandardCharsets.UTF_8); + Files.move(tmp, f, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } +} diff --git a/desktop/src/main/resources/web/app.css b/desktop/src/main/resources/web/app.css new file mode 100644 index 000000000..e24e35aa8 --- /dev/null +++ b/desktop/src/main/resources/web/app.css @@ -0,0 +1,537 @@ +/* PipePipe Desktop — "Graphite" design + dense desktop layout, graphite neutrals, one coral accent, system fonts (no web-font wait). */ + +:root { + --bg: #0e0f11; + --bg-elev: #15171a; + --bg-hover: #1c1f23; + --bg-active: #23272c; + --surface: #181a1e; + --line: #24272c; + --line-strong: #30343a; + --text: #ecedef; + --text-2: #a4a8b0; + --text-3: #6e737c; + --accent: #ff5f57; + --accent-2: #ff8a5c; + --accent-ink: #fff; + --accent-soft: rgba(255, 95, 87, .14); + --shadow: 0 10px 30px -10px rgba(0, 0, 0, .6), 0 0 0 1px var(--line); + --scrim: rgba(8, 9, 10, .72); + --radius: 10px; + --radius-sm: 7px; + --topbar: 56px; + --sidebar: 228px; + --sidebar-rail: 68px; + --ease: cubic-bezier(.2, .7, .2, 1); + --font: "Pretendard Variable", Pretendard, Inter, "Segoe UI Variable Text", "Segoe UI", system-ui, + -apple-system, "Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans KR", sans-serif; + --mono: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, monospace; + color-scheme: dark; +} + +:root[data-theme="light"] { + --bg: #f7f7f8; + --bg-elev: #ffffff; + --bg-hover: #eeeef0; + --bg-active: #e5e6e9; + --surface: #ffffff; + --line: #e4e5e8; + --line-strong: #d4d6da; + --text: #121316; + --text-2: #50545b; + --text-3: #858a93; + --accent: #e8413b; + --accent-2: #f46d43; + --accent-soft: rgba(232, 65, 59, .1); + --shadow: 0 12px 32px -12px rgba(20, 22, 26, .25), 0 0 0 1px var(--line); + --scrim: rgba(255, 255, 255, .8); + color-scheme: light; +} + +* { box-sizing: border-box; } +html, body { margin: 0; height: 100%; } +body { + background: var(--bg); + color: var(--text); + font: 14px/1.45 var(--font); + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; + overflow: hidden; +} +a { color: inherit; text-decoration: none; } +button, input, select, textarea { font: inherit; color: inherit; } +button { cursor: pointer; background: none; border: 0; padding: 0; } +img { display: block; } +svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; flex: none; } +svg .fill { fill: currentColor; stroke: none; } +::selection { background: var(--accent-soft); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 6px; } + +/* scrollbars */ +* { scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; } +::-webkit-scrollbar { width: 10px; height: 10px; } +::-webkit-scrollbar-thumb { background: var(--line-strong); border-radius: 10px; border: 3px solid var(--bg); } +::-webkit-scrollbar-track { background: transparent; } + +/* ---------------------------------------------------------------- shell */ +.app { + display: grid; + grid-template-columns: var(--sidebar) 1fr; + grid-template-rows: var(--topbar) 1fr; + grid-template-areas: "top top" "side main"; + height: 100vh; + transition: grid-template-columns .22s var(--ease); +} +.app.collapsed { grid-template-columns: var(--sidebar-rail) 1fr; } + +.topbar { + grid-area: top; + display: flex; align-items: center; gap: 16px; + padding: 0 16px 0 12px; + border-bottom: 1px solid var(--line); + background: var(--bg); + z-index: 30; + -webkit-app-region: drag; +} +.topbar > * { -webkit-app-region: no-drag; } +.topbar-left { display: flex; align-items: center; gap: 8px; width: calc(var(--sidebar) - 24px); flex: none; } +.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; font-size: 16px; letter-spacing: -.01em; } +.brand img { border-radius: 7px; } +.topbar-right { display: flex; gap: 4px; margin-left: auto; } + +.icon-btn { + display: inline-grid; place-items: center; + width: 36px; height: 36px; border-radius: 9px; + color: var(--text-2); + transition: background .12s, color .12s; +} +.icon-btn:hover { background: var(--bg-hover); color: var(--text); } +.icon-btn.sm { width: 30px; height: 30px; border-radius: 8px; } +.icon-btn.sm svg { width: 17px; height: 17px; } + +/* search */ +.search { flex: 1; max-width: 720px; display: flex; gap: 8px; margin: 0 auto; } +.search-field { position: relative; flex: 1; } +.search-field input { + width: 100%; height: 38px; + padding: 0 40px 0 38px; + background: var(--bg-elev); + border: 1px solid var(--line); + border-radius: 10px; + outline: none; + transition: border-color .12s, background .12s, box-shadow .12s; +} +.search-field input:focus { border-color: var(--line-strong); background: var(--surface); box-shadow: 0 0 0 4px var(--accent-soft); } +.search-field input::-webkit-search-cancel-button { display: none; } +.search-ico { position: absolute; left: 12px; top: 10px; width: 18px; height: 18px; color: var(--text-3); pointer-events: none; } +.kbd { + position: absolute; right: 10px; top: 9px; + font: 11px/18px var(--mono); padding: 0 6px; + color: var(--text-3); border: 1px solid var(--line-strong); border-radius: 5px; +} +.search-field input:focus ~ .kbd { display: none; } +.suggest { + position: absolute; left: 0; right: 0; top: 44px; + margin: 0; padding: 6px; list-style: none; + background: var(--surface); border-radius: 12px; box-shadow: var(--shadow); + z-index: 50; +} +.suggest li { display: flex; align-items: center; gap: 10px; padding: 7px 10px; border-radius: 8px; cursor: pointer; color: var(--text-2); } +.suggest li svg { width: 16px; height: 16px; color: var(--text-3); } +.suggest li b { color: var(--text); font-weight: 600; } +.suggest li.active, .suggest li:hover { background: var(--bg-hover); color: var(--text); } + +.service-pick { position: relative; } +.service-btn { + height: 38px; display: flex; align-items: center; gap: 6px; + padding: 0 10px 0 12px; border-radius: 10px; + background: var(--bg-elev); border: 1px solid var(--line); + color: var(--text-2); font-weight: 600; font-size: 13px; + white-space: nowrap; +} +.service-btn:hover { color: var(--text); border-color: var(--line-strong); } +.service-btn svg { width: 15px; height: 15px; } + +.menu { + position: absolute; top: 44px; left: 0; min-width: 180px; + padding: 6px; background: var(--surface); border-radius: 12px; box-shadow: var(--shadow); + z-index: 60; +} +.menu button, .menu a { + display: flex; align-items: center; gap: 10px; width: 100%; + padding: 8px 10px; border-radius: 8px; text-align: left; color: var(--text-2); +} +.menu button:hover, .menu a:hover { background: var(--bg-hover); color: var(--text); } +.menu button.on { color: var(--text); } +.menu button.on::after { content: ""; margin-left: auto; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); } + +/* sidebar */ +.sidebar { + grid-area: side; + overflow-y: auto; overflow-x: hidden; + padding: 10px 10px 24px; + border-right: 1px solid var(--line); +} +.nav-item { + display: flex; align-items: center; gap: 14px; + height: 40px; padding: 0 12px; margin-bottom: 2px; + border-radius: 9px; color: var(--text-2); font-weight: 500; + white-space: nowrap; + transition: background .12s, color .12s; +} +.nav-item:hover { background: var(--bg-hover); color: var(--text); } +.nav-item.active { background: var(--bg-active); color: var(--text); } +.nav-item.active svg { color: var(--accent); } +.nav-sep { height: 1px; background: var(--line); margin: 12px 4px; } +.nav-title { display: flex; justify-content: space-between; align-items: center; padding: 4px 12px 8px; font-size: 12px; font-weight: 600; color: var(--text-3); text-transform: uppercase; letter-spacing: .04em; } +.nav-title a { text-transform: none; letter-spacing: 0; font-weight: 500; } +.nav-title a:hover { color: var(--text); } +.nav-sub { display: flex; align-items: center; gap: 12px; height: 36px; padding: 0 10px; border-radius: 9px; color: var(--text-2); white-space: nowrap; overflow: hidden; } +.nav-sub:hover { background: var(--bg-hover); color: var(--text); } +.nav-sub img, .nav-sub .ph { width: 24px; height: 24px; border-radius: 50%; flex: none; background: var(--bg-active); object-fit: cover; } +.nav-sub span { overflow: hidden; text-overflow: ellipsis; } +.nav-empty { padding: 4px 12px; color: var(--text-3); font-size: 13px; } + +.app.collapsed .sidebar { padding: 10px 8px; } +.app.collapsed .nav-item { flex-direction: column; justify-content: center; gap: 4px; height: 62px; padding: 0; font-size: 10px; } +.app.collapsed .nav-title, .app.collapsed .nav-sub span, .app.collapsed .nav-empty { display: none; } +.app.collapsed .nav-sub { justify-content: center; padding: 0; } +.app.collapsed .topbar-left { width: auto; } + +.main { grid-area: main; overflow-y: auto; outline: none; position: relative; scroll-behavior: auto; } +.page { padding: 24px 28px 64px; max-width: 2200px; margin: 0 auto; animation: fade .18s var(--ease); } +@keyframes fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } } + +.page-head { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; min-height: 36px; } +.page-head h1 { margin: 0; font-size: 22px; font-weight: 700; letter-spacing: -.02em; } +.page-head .sub { color: var(--text-3); font-size: 13px; } +.page-head .spacer { flex: 1; } + +.chips { display: flex; gap: 8px; flex-wrap: wrap; } +.chip { + height: 32px; padding: 0 14px; border-radius: 9px; + background: var(--bg-elev); border: 1px solid var(--line); color: var(--text-2); + font-weight: 500; font-size: 13px; white-space: nowrap; +} +.chip:hover { color: var(--text); border-color: var(--line-strong); } +.chip.on { background: var(--text); color: var(--bg); border-color: var(--text); } + +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: 8px; + height: 36px; padding: 0 16px; border-radius: 10px; + background: var(--bg-elev); border: 1px solid var(--line); color: var(--text); + font-weight: 600; font-size: 13px; white-space: nowrap; + transition: background .12s, border-color .12s, transform .06s; +} +.btn:hover { background: var(--bg-hover); border-color: var(--line-strong); } +.btn:active { transform: scale(.98); } +.btn svg { width: 17px; height: 17px; } +.btn.primary { background: var(--accent); border-color: transparent; color: var(--accent-ink); } +.btn.primary:hover { background: color-mix(in srgb, var(--accent) 88%, white); } +.btn.subscribed { background: var(--bg-active); color: var(--text-2); } +.btn.ghost { background: transparent; border-color: transparent; color: var(--text-2); } +.btn.ghost:hover { background: var(--bg-hover); color: var(--text); } + +/* ---------------------------------------------------------------- video grid */ +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(272px, 1fr)); + gap: 28px 18px; +} +.card { display: flex; flex-direction: column; gap: 10px; min-width: 0; cursor: pointer; } +.thumb { + position: relative; aspect-ratio: 16 / 9; + border-radius: var(--radius); overflow: hidden; + background: var(--bg-elev); +} +.thumb img { width: 100%; height: 100%; object-fit: cover; transition: transform .35s var(--ease), opacity .25s; opacity: 0; } +.thumb img.loaded { opacity: 1; } +.card:hover .thumb img { transform: scale(1.035); } +.badge { + position: absolute; right: 7px; bottom: 7px; + padding: 1px 6px; border-radius: 5px; + background: rgba(0, 0, 0, .78); color: #fff; + font: 600 12px/18px var(--font); font-variant-numeric: tabular-nums; + backdrop-filter: blur(4px); +} +.badge.live { background: var(--accent); } +.progress-line { position: absolute; left: 0; right: 0; bottom: 0; height: 3px; background: rgba(255, 255, 255, .25); } +.progress-line i { display: block; height: 100%; background: var(--accent); } +.thumb .hover-actions { position: absolute; top: 7px; right: 7px; display: flex; flex-direction: column; gap: 6px; opacity: 0; transition: opacity .15s; } +.card:hover .hover-actions { opacity: 1; } +.hover-actions button { width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; background: rgba(0, 0, 0, .72); color: #fff; backdrop-filter: blur(4px); } +.hover-actions button:hover { background: rgba(0, 0, 0, .9); } +.hover-actions svg { width: 16px; height: 16px; } + +.meta { display: flex; gap: 12px; min-width: 0; } +.avatar { width: 36px; height: 36px; border-radius: 50%; flex: none; background: var(--bg-active); object-fit: cover; } +.meta-text { min-width: 0; flex: 1; } +.title { + margin: 0 0 4px; font-size: 15px; font-weight: 600; line-height: 1.38; letter-spacing: -.005em; + display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; +} +.byline { color: var(--text-2); font-size: 13px; line-height: 1.5; } +.byline a:hover { color: var(--text); } +.dot::before { content: "·"; margin: 0 6px; } +.verified { width: 13px; height: 13px; vertical-align: -2px; margin-left: 3px; color: var(--text-3); } + +.card.channel { align-items: center; text-align: center; padding: 12px; } +.card.channel .avatar-lg { width: 120px; height: 120px; border-radius: 50%; object-fit: cover; background: var(--bg-elev); } +.card.channel .title { -webkit-line-clamp: 1; } + +/* list rows (related, history, search) */ +.rows { display: flex; flex-direction: column; gap: 14px; } +.row { display: flex; gap: 14px; cursor: pointer; min-width: 0; position: relative; } +.row .thumb { width: 360px; flex: none; } +.row.compact .thumb { width: 168px; border-radius: 8px; } +.row.compact .title { font-size: 14px; } +.row.compact .byline { font-size: 12px; } +.row .desc { color: var(--text-3); font-size: 12.5px; margin-top: 8px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.row .remove { position: absolute; right: 0; top: 0; opacity: 0; } +.row:hover .remove { opacity: 1; } +.row.channel-row .thumb { width: 360px; aspect-ratio: auto; height: 136px; background: none; display: grid; place-items: center; } +.row.channel-row .thumb img { width: 136px; height: 136px; border-radius: 50%; } + +/* skeletons */ +.sk { background: linear-gradient(90deg, var(--bg-elev) 0%, var(--bg-hover) 50%, var(--bg-elev) 100%); background-size: 200% 100%; animation: shimmer 1.2s infinite linear; border-radius: 6px; } +@keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } +.sk-line { height: 13px; margin-top: 8px; } + +.empty { display: grid; place-items: center; gap: 10px; padding: 80px 20px; color: var(--text-3); text-align: center; } +.empty svg { width: 44px; height: 44px; stroke-width: 1.3; } +.empty h3 { margin: 0; color: var(--text); font-size: 16px; } +.error-box { padding: 16px 18px; border-radius: var(--radius); background: var(--accent-soft); color: var(--text); display: flex; gap: 12px; align-items: center; } +.sentinel { height: 1px; } +.spinner { width: 28px; height: 28px; border: 3px solid var(--line-strong); border-top-color: var(--accent); border-radius: 50%; animation: spin .7s linear infinite; margin: 32px auto; } +@keyframes spin { to { transform: rotate(360deg); } } + +/* ---------------------------------------------------------------- watch page */ +.watch { + display: grid; grid-template-columns: minmax(0, 1fr) 400px; grid-template-rows: auto 1fr; + column-gap: 24px; padding: 20px 28px 64px; max-width: 1920px; margin: 0 auto; +} +.watch > .player-slot { grid-column: 1; grid-row: 1; } +.watch > .watch-main { grid-column: 1; grid-row: 2; } +.watch > .watch-side { grid-column: 2; grid-row: 1 / span 2; } +.watch.theater { padding-top: 0; max-width: none; } +.watch.theater > .player-slot { + grid-column: 1 / -1; margin: 0 -28px 4px; border-radius: 0; aspect-ratio: auto; + height: min(56.25vw, calc(100vh - var(--topbar) - 110px)); min-height: 360px; +} +.watch.theater > .watch-side { grid-column: 2; grid-row: 2; padding-top: 16px; } +.watch.theater > .watch-main { max-width: 1280px; } +.watch-main { min-width: 0; } +.player-slot { aspect-ratio: 16 / 9; background: #000; border-radius: 12px; overflow: hidden; position: relative; } +.watch-side { min-width: 0; } +.watch h1.vtitle { font-size: 20px; line-height: 1.35; font-weight: 700; letter-spacing: -.015em; margin: 16px 0 12px; } +.owner { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.owner .avatar { width: 42px; height: 42px; } +.owner-name { font-weight: 600; font-size: 15px; display: flex; align-items: center; } +.owner-subs { color: var(--text-3); font-size: 12.5px; } +.owner .spacer { flex: 1; } +.actions { display: flex; gap: 8px; flex-wrap: wrap; } +.pill-stat { display: inline-flex; align-items: center; gap: 7px; height: 36px; padding: 0 14px; border-radius: 10px; background: var(--bg-elev); border: 1px solid var(--line); color: var(--text-2); font-weight: 600; font-size: 13px; } +.pill-stat svg { width: 17px; height: 17px; } + +.desc-box { margin-top: 16px; padding: 14px 16px; border-radius: 12px; background: var(--bg-elev); border: 1px solid var(--line); } +.desc-stats { font-weight: 600; margin-bottom: 6px; font-size: 13.5px; } +.desc-body { white-space: pre-wrap; word-break: break-word; color: var(--text); font-size: 13.5px; line-height: 1.6; max-height: 4.8em; overflow: hidden; position: relative; } +.desc-box.open .desc-body { max-height: none; } +.desc-body a { color: var(--accent-2); } +.desc-body a:hover { text-decoration: underline; } +.desc-toggle { margin-top: 8px; font-weight: 600; color: var(--text-2); font-size: 13px; } +.desc-toggle:hover { color: var(--text); } +.tags { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 10px; } +.tags a { color: var(--accent-2); font-size: 12.5px; } + +.chapters { margin-top: 16px; display: flex; gap: 10px; overflow-x: auto; padding-bottom: 6px; } +.chapter { flex: none; width: 168px; padding: 8px; border-radius: 10px; background: var(--bg-elev); border: 1px solid var(--line); text-align: left; } +.chapter:hover { border-color: var(--line-strong); } +.chapter.now { border-color: var(--accent); } +.chapter img { width: 100%; aspect-ratio: 16/9; object-fit: cover; border-radius: 6px; margin-bottom: 6px; background: var(--bg-hover); } +.chapter .t { font: 600 12px var(--mono); color: var(--accent-2); } +.chapter .n { font-size: 12.5px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } + +.section-title { font-size: 16px; font-weight: 700; margin: 28px 0 16px; display: flex; align-items: center; gap: 10px; } +.section-title .count { color: var(--text-3); font-weight: 500; font-size: 14px; } +.comment { display: flex; gap: 14px; margin-bottom: 20px; } +.comment .avatar { width: 38px; height: 38px; } +.comment-head { font-size: 13px; margin-bottom: 3px; } +.comment-head b { font-weight: 600; margin-right: 6px; } +.comment-head span { color: var(--text-3); } +.comment-text { white-space: pre-wrap; word-break: break-word; font-size: 14px; line-height: 1.55; } +.comment-text a { color: var(--accent-2); } +.comment-foot { margin-top: 6px; color: var(--text-3); font-size: 12.5px; display: flex; gap: 14px; align-items: center; } +.comment-foot svg { width: 14px; height: 14px; } + +.autoplay-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; color: var(--text-2); font-weight: 600; font-size: 13px; } + +/* switch */ +.switch { position: relative; width: 36px; height: 20px; flex: none; } +.switch input { opacity: 0; width: 0; height: 0; position: absolute; } +.switch span { position: absolute; inset: 0; border-radius: 20px; background: var(--line-strong); transition: background .15s; cursor: pointer; } +.switch span::after { content: ""; position: absolute; left: 3px; top: 3px; width: 14px; height: 14px; border-radius: 50%; background: #fff; transition: transform .15s var(--ease); } +.switch input:checked + span { background: var(--accent); } +.switch input:checked + span::after { transform: translateX(16px); } + +/* ---------------------------------------------------------------- player */ +.player { + position: absolute; inset: 0; background: #000; color: #fff; + user-select: none; overflow: hidden; + --ctl: rgba(255, 255, 255, .92); +} +.player video { width: 100%; height: 100%; display: block; background: #000; } +.player.hide-cursor { cursor: none; } +.player .shade { + position: absolute; left: 0; right: 0; bottom: 0; height: 160px; pointer-events: none; + background: linear-gradient(to top, rgba(0,0,0,.78), rgba(0,0,0,.35) 55%, transparent); + opacity: 1; transition: opacity .2s; +} +.player .top-shade { position: absolute; left: 0; right: 0; top: 0; height: 90px; pointer-events: none; background: linear-gradient(to bottom, rgba(0,0,0,.55), transparent); transition: opacity .2s; } +.player .ptitle { position: absolute; left: 18px; top: 14px; right: 18px; font-weight: 600; font-size: 15px; text-shadow: 0 1px 3px rgba(0,0,0,.5); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .2s; opacity: 0; } +.player.fs .ptitle { opacity: 1; } +.player.idle .shade, .player.idle .top-shade, .player.idle .controls, .player.idle .ptitle { opacity: 0; } +.player.idle .controls { pointer-events: none; } + +.controls { position: absolute; left: 0; right: 0; bottom: 0; padding: 0 12px 8px; transition: opacity .2s; } +.bar { position: relative; height: 18px; display: flex; align-items: center; cursor: pointer; margin: 0 4px; } +.bar-track { position: relative; width: 100%; height: 4px; border-radius: 4px; background: rgba(255,255,255,.22); transition: height .12s; } +.bar:hover .bar-track { height: 6px; } +.bar-buf, .bar-fill, .bar-hover { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 4px; } +.bar-buf { background: rgba(255,255,255,.35); } +.bar-hover { background: rgba(255,255,255,.25); opacity: 0; } +.bar:hover .bar-hover { opacity: 1; } +.bar-fill { background: var(--accent); } +.bar-knob { position: absolute; top: 50%; width: 14px; height: 14px; margin: -7px 0 0 -7px; border-radius: 50%; background: var(--accent); transform: scale(0); transition: transform .12s; box-shadow: 0 0 0 4px rgba(255, 95, 87, .25); } +.bar:hover .bar-knob, .bar.drag .bar-knob { transform: scale(1); } +.bar-marks i { position: absolute; top: 0; bottom: 0; width: 3px; background: rgba(0,0,0,.65); } +.bar-tip { position: absolute; bottom: 24px; transform: translateX(-50%); padding: 4px 8px; border-radius: 6px; background: rgba(20,20,22,.92); font: 600 12px var(--font); white-space: nowrap; pointer-events: none; opacity: 0; transition: opacity .1s; font-variant-numeric: tabular-nums; } +.bar-tip small { display: block; font-weight: 500; opacity: .8; max-width: 240px; overflow: hidden; text-overflow: ellipsis; } +.bar:hover .bar-tip { opacity: 1; } + +.ctl-row { display: flex; align-items: center; gap: 2px; height: 44px; } +.ctl-row .grow { flex: 1; } +.pbtn { width: 40px; height: 40px; display: grid; place-items: center; border-radius: 8px; color: var(--ctl); } +.pbtn:hover { color: #fff; background: rgba(255,255,255,.08); } +.pbtn svg { width: 22px; height: 22px; } +.pbtn.on { color: #fff; } +.pbtn.on::after { content: ""; position: absolute; } +.pbtn.cc-on svg { color: var(--accent); } +.time { font: 500 13px var(--font); font-variant-numeric: tabular-nums; padding: 0 10px; color: var(--ctl); white-space: nowrap; } +.chapter-name { color: rgba(255,255,255,.75); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 260px; } +.vol { display: flex; align-items: center; } +.vol-slider { width: 0; overflow: hidden; transition: width .18s var(--ease); display: flex; align-items: center; } +.vol:hover .vol-slider, .vol:focus-within .vol-slider { width: 76px; } +.vol-slider input { width: 64px; margin-left: 4px; accent-color: #fff; height: 4px; } + +.pmenu { + position: absolute; right: 14px; bottom: 64px; min-width: 240px; max-height: calc(100% - 80px); overflow-y: auto; + padding: 6px; border-radius: 12px; background: rgba(22, 23, 26, .94); backdrop-filter: blur(12px); + box-shadow: 0 10px 30px rgba(0,0,0,.5); font-size: 13.5px; +} +.pmenu .mi { display: flex; align-items: center; gap: 10px; width: 100%; padding: 9px 12px; border-radius: 8px; text-align: left; color: #fff; } +.pmenu .mi:hover { background: rgba(255,255,255,.08); } +.pmenu .mi .v { margin-left: auto; color: rgba(255,255,255,.6); } +.pmenu .mi.on { font-weight: 600; } +.pmenu .mi.on::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); margin-left: -2px; } +.pmenu .mh { display: flex; align-items: center; gap: 6px; padding: 8px 8px 10px; border-bottom: 1px solid rgba(255,255,255,.1); margin-bottom: 4px; font-weight: 600; } + +.center-flash { position: absolute; left: 50%; top: 50%; width: 68px; height: 68px; margin: -34px; border-radius: 50%; background: rgba(0,0,0,.55); display: grid; place-items: center; opacity: 0; pointer-events: none; } +.center-flash svg { width: 30px; height: 30px; } +.center-flash.go { animation: flash .5s var(--ease); } +@keyframes flash { 0% { opacity: 1; transform: scale(.8); } 100% { opacity: 0; transform: scale(1.3); } } +.p-osd { position: absolute; top: 16%; left: 50%; transform: translateX(-50%); padding: 6px 14px; border-radius: 8px; background: rgba(0,0,0,.65); font-weight: 600; font-variant-numeric: tabular-nums; opacity: 0; transition: opacity .2s; pointer-events: none; } +.p-osd.show { opacity: 1; } +.p-spin { position: absolute; left: 50%; top: 50%; margin: -22px; width: 44px; height: 44px; border: 3px solid rgba(255,255,255,.2); border-top-color: #fff; border-radius: 50%; animation: spin .8s linear infinite; display: none; pointer-events: none; } +.player.buffering .p-spin { display: block; } +.p-error { position: absolute; inset: 0; display: none; place-items: center; text-align: center; padding: 24px; background: rgba(0,0,0,.8); } +.player.errored .p-error { display: grid; } +.p-poster { position: absolute; inset: 0; background: #000 center/cover no-repeat; transition: opacity .3s; pointer-events: none; } +.player.started .p-poster { opacity: 0; } +.p-next { position: absolute; right: 16px; bottom: 80px; width: 300px; padding: 12px; border-radius: 12px; background: rgba(18,18,20,.92); display: none; gap: 12px; } +.p-next.show { display: flex; } +.p-next img { width: 110px; aspect-ratio: 16/9; object-fit: cover; border-radius: 6px; } +.p-next .n { font-size: 13px; font-weight: 600; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.p-next .s { font-size: 12px; opacity: .7; margin-bottom: 4px; } +.p-next .acts { display: flex; gap: 6px; margin-top: 8px; } +.p-next button { font-size: 12px; padding: 4px 10px; border-radius: 6px; background: rgba(255,255,255,.12); } +.p-next button.go { background: #fff; color: #000; font-weight: 600; } +video::cue { background: rgba(8,8,8,.75); color: #fff; font-family: var(--font); font-size: 1.05em; } + +/* mini dock */ +.mini-dock { + position: fixed; right: 20px; bottom: 20px; width: 400px; z-index: 40; + border-radius: 12px; overflow: hidden; background: var(--surface); box-shadow: var(--shadow); + animation: pop .2s var(--ease); +} +@keyframes pop { from { opacity: 0; transform: translateY(12px) scale(.98); } to { opacity: 1; transform: none; } } +.mini-dock .mini-slot { aspect-ratio: 16/9; position: relative; background: #000; } +.mini-dock .player .ctl-row .hide-mini, .mini-dock .player .chapter-name, .mini-dock .player .vol-slider { display: none; } +.mini-info { display: flex; align-items: center; gap: 8px; padding: 8px 8px 8px 14px; } +.mini-title { flex: 1; font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; } +.mini-actions { display: flex; gap: 2px; } + +/* ---------------------------------------------------------------- channel */ +.ch-banner { height: clamp(100px, 16vw, 220px); border-radius: 14px; background: var(--bg-elev) center/cover no-repeat; margin-bottom: 20px; } +.ch-head { display: flex; align-items: center; gap: 22px; margin-bottom: 28px; } +.ch-head .avatar { width: 112px; height: 112px; } +.ch-head h1 { margin: 0 0 4px; font-size: 28px; letter-spacing: -.02em; } +.ch-head .sub { color: var(--text-2); } +.ch-desc { color: var(--text-3); font-size: 13px; margin-top: 6px; max-width: 760px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } + +/* playlist page */ +.pl-layout { display: grid; grid-template-columns: 360px minmax(0, 1fr); gap: 28px; align-items: start; } +.pl-hero { position: sticky; top: 0; padding: 20px; border-radius: 16px; background: linear-gradient(160deg, var(--bg-active), var(--bg-elev)); border: 1px solid var(--line); } +.pl-hero .thumb { margin-bottom: 16px; } +.pl-hero h1 { margin: 0 0 8px; font-size: 22px; letter-spacing: -.015em; } +.pl-hero .sub { color: var(--text-2); margin-bottom: 16px; } +.pl-index { width: 26px; flex: none; text-align: center; color: var(--text-3); font-size: 13px; align-self: center; } + +/* settings */ +.settings { max-width: 760px; } +.set-group { border: 1px solid var(--line); border-radius: 14px; background: var(--bg-elev); margin-bottom: 20px; overflow: hidden; } +.set-group h2 { font-size: 13px; margin: 0; padding: 14px 18px 10px; color: var(--text-3); text-transform: uppercase; letter-spacing: .05em; } +.set-row { display: flex; align-items: center; gap: 16px; padding: 14px 18px; border-top: 1px solid var(--line); } +.set-row:first-of-type { border-top: 0; } +.set-row .lbl { flex: 1; } +.set-row .lbl small { display: block; color: var(--text-3); font-size: 12.5px; margin-top: 2px; } +select, .input { + height: 34px; padding: 0 10px; border-radius: 8px; + background: var(--surface); border: 1px solid var(--line-strong); outline: none; +} +select:focus, .input:focus { border-color: var(--accent); } +.kbd-list { display: grid; grid-template-columns: auto 1fr; gap: 8px 18px; padding: 14px 18px; font-size: 13px; color: var(--text-2); } +.kbd-list kbd { font: 12px var(--mono); padding: 2px 7px; border-radius: 5px; border: 1px solid var(--line-strong); color: var(--text); background: var(--surface); justify-self: start; } + +/* toasts */ +.toast-host { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; z-index: 100; pointer-events: none; } +.toast { padding: 10px 16px; border-radius: 10px; background: var(--text); color: var(--bg); font-weight: 600; font-size: 13px; box-shadow: var(--shadow); animation: pop .2s var(--ease); } + +/* responsive */ +@media (max-width: 1280px) { + .watch { grid-template-columns: minmax(0, 1fr) 340px; } + .row .thumb { width: 280px; } +} +@media (max-width: 1000px) { + .watch, .watch.theater { grid-template-columns: 1fr; } + .watch > .watch-side, .watch.theater > .watch-side { grid-column: 1; grid-row: 3; padding-top: 24px; } + .pl-layout { grid-template-columns: 1fr; } + .pl-hero { position: static; } + .app { grid-template-columns: var(--sidebar-rail) 1fr; } + .app .sidebar { padding: 10px 8px; } + .app .nav-item { flex-direction: column; justify-content: center; gap: 4px; height: 62px; padding: 0; font-size: 10px; } + .app .nav-title, .app .nav-sub span, .app .nav-empty { display: none; } + .app .nav-sub { justify-content: center; padding: 0; } + .topbar-left { width: auto; } + .brand span { display: none; } + .row .thumb { width: 200px; } +} +@media (max-width: 640px) { + .page, .watch { padding: 16px; } + .service-pick { display: none; } + .app { grid-template-columns: 0 1fr; } + .sidebar { display: none; } + .row .thumb { width: 150px; } + .mini-dock { width: calc(100vw - 32px); right: 16px; } +} diff --git a/desktop/src/main/resources/web/app.js b/desktop/src/main/resources/web/app.js new file mode 100644 index 000000000..26fc3af1f --- /dev/null +++ b/desktop/src/main/resources/web/app.js @@ -0,0 +1,948 @@ +// PipePipe Desktop — web UI (no build step, plain ES modules) +import { Player, fmtTime, escapeHtml as esc } from './player.js'; + +const $ = (s, r = document) => r.querySelector(s); +const $$ = (s, r = document) => [...r.querySelectorAll(s)]; +const icon = (id, cls = '') => ``; +const main = $('#main'); + +// ------------------------------------------------------------------ local store (server persisted) +const navLang = (navigator.language || 'ko-KR').split('-'); +const DEFAULT_SETTINGS = { + service: 0, language: navLang[0] || 'ko', country: (navLang[1] || (navLang[0] === 'ko' ? 'KR' : 'US')).toUpperCase(), quality: '1080', codec: 'auto', autoplay: true, + subtitles: 'off', theme: 'dark', volume: 1, muted: false, theater: false, sidebar: true, audioOnly: false, +}; +const docs = { subscriptions: [], history: [], playlists: { watchLater: [], lists: [] }, settings: { ...DEFAULT_SETTINGS } }; +const saveTimers = {}; +function save(name, delay = 400) { + clearTimeout(saveTimers[name]); + saveTimers[name] = setTimeout(() => { + fetch('/api/store/' + name, { method: 'PUT', body: JSON.stringify(docs[name]), headers: { 'Content-Type': 'application/json' } }) + .catch(() => toast('저장 실패')); + }, delay); +} +async function loadDocs() { + await Promise.all(Object.keys(docs).map(async (k) => { + try { + const v = await (await fetch('/api/store/' + k)).json(); + if (v !== null) docs[k] = k === 'settings' ? { ...DEFAULT_SETTINGS, ...v } : k === 'playlists' ? { watchLater: [], lists: [], ...v } : v; + else if (k === 'settings') save('settings', 0); // first run: let the server pick up language / region + } catch (e) { /* first run */ } + })); +} +const S = () => docs.settings; + +// ------------------------------------------------------------------ api +const cache = new Map(); +async function api(path, params = {}, { signal, ttl = 0 } = {}) { + const qs = new URLSearchParams(params).toString(); + const key = path + '?' + qs; + if (ttl) { + const c = cache.get(key); + if (c && Date.now() - c.at < ttl) return c.data; + } + const r = await fetch('/api/' + path + (qs ? '?' + qs : ''), { signal }); + const data = await r.json().catch(() => ({ error: 'HTTP ' + r.status })); + if (!r.ok) throw new Error(data.error || 'HTTP ' + r.status); + if (ttl) cache.set(key, { data, at: Date.now() }); + return data; +} + +// ------------------------------------------------------------------ formatting +const loc = () => (S().language || 'ko'); +function fmtCount(n, unit = '') { + if (n == null || n < 0) return ''; + return new Intl.NumberFormat(loc(), { notation: 'compact', maximumFractionDigits: 1 }).format(n) + unit; +} +function fmtViews(n) { + if (n == null || n < 0) return ''; + return loc() === 'ko' ? '조회수 ' + fmtCount(n) + '회' : fmtCount(n) + ' views'; +} +function fmtAgo(ms, fallback) { + if (!ms) return fallback || ''; + const rtf = new Intl.RelativeTimeFormat(loc(), { numeric: 'auto' }); + const s = (ms - Date.now()) / 1000; + const units = [['year', 31536000], ['month', 2592000], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60]]; + for (const [u, sec] of units) if (Math.abs(s) >= sec) return rtf.format(Math.round(s / sec), u); + return rtf.format(0, 'minute'); +} +const route = (name, params) => '#/' + name + (params ? '?' + new URLSearchParams(params) : ''); + +// ------------------------------------------------------------------ toasts +function toast(msg) { + const t = document.createElement('div'); + t.className = 'toast'; + t.textContent = msg; + $('#toasts').appendChild(t); + setTimeout(() => t.remove(), 2400); +} + +// ------------------------------------------------------------------ items +const thumbImg = (src, alt = '') => src ? `${esc(alt)}` : ''; +function historyFor(url) { return docs.history.find((h) => h.url === url); } + +function progressLine(it) { + const h = historyFor(it.url); + if (!h || !h.pos || !it.duration) return ''; + return `
`; +} +function badge(it) { + if (it.live) return 'LIVE'; + if (it.duration > 0) return `${fmtTime(it.duration)}`; + return ''; +} +function byline(it) { + const parts = []; + if (it.views >= 0 && it.views != null) parts.push(fmtViews(it.views)); + const ago = fmtAgo(it.date, it.dateText); + if (ago) parts.push(ago); + return parts.map((p, i) => `${esc(p)}`).join(''); +} +function encodeItem(it) { return esc(JSON.stringify(it)); } + +function card(it, ctx = {}) { + if (it.type === 'channel') { + return ` + ${it.thumb ? `` : '
'} +

${esc(it.name)}

`; + } + if (it.type === 'playlist') { + return ` +
${thumbImg(it.thumb)}${it.streams > 0 ? it.streams + '개 동영상' : '재생목록'}
+

${esc(it.name)}

`; + } + const href = route('watch', ctx.queue ? { url: it.url, q: ctx.queue, i: ctx.index } : { url: it.url }); + return ` +
${thumbImg(it.thumb, it.name)}${badge(it)}${progressLine(it)} +
+ + +
+
+ ${ctx.noAvatar || !it.uploaderAvatar ? '' : ``} +
+

${esc(it.name)}

+ +
+
`; +} + +function row(it, { compact = false, index, queue, remove } = {}) { + if (it.type === 'channel') { + return ` +
${it.thumb ? `` : ''}
+

${esc(it.name)}

+ + ${it.description ? `
${esc(it.description)}
` : ''}
`; + } + if (it.type === 'playlist') { + return ` +
${thumbImg(it.thumb)}${it.streams > 0 ? it.streams + '개' : '재생목록'}
+

${esc(it.name)}

`; + } + const href = route('watch', queue ? { url: it.url, q: queue, i: index } : { url: it.url }); + return ` + ${index != null && !compact ? `
${index + 1}
` : ''} +
${thumbImg(it.thumb, it.name)}${badge(it)}${progressLine(it)} + ${compact ? '' : `
`}
+
+

${esc(it.name)}

+ +
+ ${remove ? `` : ''} +
`; +} + +function skeletonGrid(n = 12) { + return '
' + Array.from({ length: n }, () => `
`).join('') + '
'; +} +function errorBox(e) { + return `
${icon('x')}
불러오지 못했습니다
${esc(e.message || e)}
`; +} +function emptyState(ic, title, text = '') { + return `
${icon(ic)}

${esc(title)}

${text}
`; +} + +// infinite scroll for any list returned by the server +function paginate(host, next, render, signal) { + if (!next) return; + const sentinel = document.createElement('div'); + sentinel.className = 'sentinel'; + host.after(sentinel); + let loading = false; + const io = new IntersectionObserver(async (entries) => { + if (!entries[0].isIntersecting || loading || !next) return; + loading = true; + const spin = document.createElement('div'); + spin.className = 'spinner'; + sentinel.after(spin); + try { + const r = await api('more', { next }, { signal }); + host.insertAdjacentHTML('beforeend', r.items.map(render).join('')); + next = r.next; + if (!next) io.disconnect(); + } catch (e) { + if (e.name !== 'AbortError') { io.disconnect(); sentinel.insertAdjacentHTML('afterend', errorBox(e)); } + } finally { spin.remove(); loading = false; } + }, { root: main, rootMargin: '1200px' }); + io.observe(sentinel); + signal.addEventListener('abort', () => io.disconnect()); +} + +// ------------------------------------------------------------------ player + queue +let player; +const nowPlaying = { url: null, data: null, queue: null, index: -1 }; +const sessionWatched = new Set(); + +function queueItems(q) { + if (!q) return null; + if (q === 'later') return docs.playlists.watchLater; + if (q.startsWith('local:')) return (docs.playlists.lists.find((l) => l.id === q.slice(6)) || {}).items || null; + if (q.startsWith('remote:')) return remoteQueues.get(q) || null; + return null; +} +const remoteQueues = new Map(); + +function peekNext() { + const items = queueItems(nowPlaying.queue); + if (items && nowPlaying.index + 1 < items.length) return { ...items[nowPlaying.index + 1], _qi: nowPlaying.index + 1 }; + const rel = (nowPlaying.data && nowPlaying.data.related || []).filter((r) => r.type === 'stream' && !r.live); + return rel.find((r) => !sessionWatched.has(r.url)) || rel[0] || null; +} +function playNext() { + const n = peekNext(); + if (!n) return; + const params = { url: n.url }; + if (n._qi != null) { params.q = nowPlaying.queue; params.i = n._qi; } + location.hash = route('watch', params); +} + +function recordHistory(d) { + const prev = historyFor(d.url); + const entry = { url: d.url, name: d.name, thumb: d.thumb, uploader: d.uploader && d.uploader.name, uploaderUrl: d.uploader && d.uploader.url, + duration: d.duration, service: d.service, pos: prev ? prev.pos : 0, at: Date.now(), type: 'stream' }; + docs.history = [entry, ...docs.history.filter((h) => h.url !== d.url)].slice(0, 1000); + save('history'); +} +let lastPosSave = 0; +function onPlayerTime(t, dur) { + const h = nowPlaying.url && historyFor(nowPlaying.url); + if (!h || !dur || nowPlaying.data?.live) return; + h.pos = dur - t < 15 ? 0 : Math.floor(t); // finished -> start over next time + if (Date.now() - lastPosSave > 5000) { lastPosSave = Date.now(); save('history', 1500); } +} + +function initPlayer() { + player = new Player(S()); + player.on('next', () => playNext()); + player.on('peekNext', peekNext); + player.handlers.peekNext = peekNext; + player.on('time', onPlayerTime); + player.on('settings', () => save('settings', 800)); + player.on('theater', () => { S().theater = !S().theater; save('settings'); $('.watch')?.classList.toggle('theater', S().theater); }); + player.on('chapter', (c) => { + $$('.chapter').forEach((el) => el.classList.toggle('now', c && +el.dataset.t === c.t)); + }); +} + +function dockToMini() { + if (!nowPlaying.url || !player || player.video.paused && player.video.currentTime < 1) { closeMini(); return; } + const dock = $('#mini-dock'); + let slot = $('.mini-slot', dock); + if (!slot) { slot = document.createElement('div'); slot.className = 'mini-slot'; dock.prepend(slot); } + player.closeMenu(); + slot.appendChild(player.el); + $('#mini-title').textContent = nowPlaying.data ? nowPlaying.data.name : ''; + dock.hidden = false; +} +function closeMini() { + $('#mini-dock').hidden = true; + if (player) player.stop(); + nowPlaying.url = null; nowPlaying.data = null; +} + +// ------------------------------------------------------------------ description sanitising / linkify +function linkifyText(text) { + return esc(text) + .replace(/(https?:\/\/[^\s<]+)/g, (m) => `${m}`) + .replace(/(^|\s)((?:\d{1,2}:)?\d{1,2}:\d{2})(?=\s|$)/gm, (m, pre, ts) => `${pre}${ts}`); +} +function toSec(ts) { return ts.split(':').reduce((a, b) => a * 60 + +b, 0); } +function sanitizeHtml(html) { + const doc = new DOMParser().parseFromString(`
${html}
`, 'text/html'); + const out = document.createElement('div'); + const walk = (node, into) => { + for (const n of node.childNodes) { + if (n.nodeType === 3) { into.appendChild(document.createTextNode(n.textContent)); continue; } + if (n.nodeType !== 1) continue; + const tag = n.tagName.toLowerCase(); + if (tag === 'br') { into.appendChild(document.createElement('br')); continue; } + if (tag === 'a') { + const a = document.createElement('a'); + const href = n.getAttribute('href') || ''; + const t = href.match(/[?&#]t=(\d+)/); + if (t && /watch|youtu\.be/.test(href) && nowPlaying.url && href.includes(nowPlaying.data?.id || '__')) { a.href = '#'; a.dataset.seek = t[1]; } + else { a.href = href; a.dataset.ext = ''; } + walk(n, a); into.appendChild(a); continue; + } + if (['b', 'strong', 'i', 'em', 'p', 'span', 'div', 'ul', 'ol', 'li'].includes(tag)) { + const e = document.createElement(['p', 'div'].includes(tag) ? 'span' : tag); + walk(n, e); into.appendChild(e); if (tag === 'p' || tag === 'div') into.appendChild(document.createElement('br')); + continue; + } + walk(n, into); + } + }; + walk(doc.body.firstChild, out); + return out.innerHTML; +} +function richText(text, isHtml) { + if (!text) return ''; + return isHtml ? sanitizeHtml(text) : linkifyText(text); +} + +/** turn a pasted URL into an internal route */ +function routeForUrl(u) { + if (!/^https?:\/\//i.test(u)) return null; + if (/youtube\.com\/(watch|shorts|live)|youtu\.be\/|bilibili\.com\/video|b23\.tv|nicovideo\.jp\/watch|nico\.ms/.test(u)) return route('watch', { url: u }); + if (/[?&]list=/.test(u)) return route('playlist', { url: u }); + if (/youtube\.com\/(channel|c|user|@)|youtube\.com\/@|space\.bilibili\.com|nicovideo\.jp\/user/.test(u)) return route('channel', { url: u }); + return route('watch', { url: u }); +} + +// ------------------------------------------------------------------ subscriptions helpers +function isSubscribed(url) { return docs.subscriptions.some((s) => s.url === url); } +function toggleSub(ch) { + if (isSubscribed(ch.url)) { + docs.subscriptions = docs.subscriptions.filter((s) => s.url !== ch.url); + toast('구독 취소됨'); + } else { + docs.subscriptions.push({ url: ch.url, name: ch.name, avatar: ch.avatar, service: ch.service ?? 0 }); + toast(ch.name + ' 구독'); + } + save('subscriptions'); + renderNavSubs(); + return isSubscribed(ch.url); +} +function subButton(ch) { + const on = isSubscribed(ch.url); + return ``; +} +function renderNavSubs() { + const host = $('#nav-subs'); + if (!docs.subscriptions.length) { host.innerHTML = ''; return; } + host.innerHTML = [...docs.subscriptions].sort((a, b) => a.name.localeCompare(b.name)).map((s) => + `${s.avatar ? `` : '
'}${esc(s.name)}
`).join(''); +} + +// ------------------------------------------------------------------ playlists helpers +function addToWatchLater(it) { + if (docs.playlists.watchLater.some((x) => x.url === it.url)) { toast('이미 추가됨'); return; } + docs.playlists.watchLater.unshift(slim(it)); + save('playlists'); + toast('나중에 볼 동영상에 추가됨'); +} +function slim(it) { + return { type: 'stream', url: it.url, name: it.name, thumb: it.thumb, uploader: it.uploader, uploaderUrl: it.uploaderUrl, duration: it.duration, service: it.service, views: it.views, date: it.date, dateText: it.dateText }; +} +function addToPlaylistMenu(it, anchor) { + $$('.menu.floating').forEach((m) => m.remove()); + const m = document.createElement('div'); + m.className = 'menu floating'; + m.style.position = 'fixed'; + const r = anchor.getBoundingClientRect(); + m.style.left = Math.min(window.innerWidth - 230, r.left) + 'px'; + m.style.top = Math.min(window.innerHeight - 300, r.bottom + 6) + 'px'; + m.style.width = '220px'; + m.innerHTML = docs.playlists.lists.map((l) => ``).join('') + + ``; + document.body.appendChild(m); + const close = (e) => { if (!m.contains(e.target)) { m.remove(); document.removeEventListener('mousedown', close, true); } }; + setTimeout(() => document.addEventListener('mousedown', close, true)); + m.addEventListener('click', (e) => { + const b = e.target.closest('button'); + if (!b) return; + let list; + if (b.dataset.new != null) { + const name = prompt('새 재생목록 이름'); + if (!name) return; + list = { id: Math.random().toString(36).slice(2, 10), name, items: [] }; + docs.playlists.lists.push(list); + } else list = docs.playlists.lists.find((l) => l.id === b.dataset.pl); + if (!list.items.some((x) => x.url === it.url)) list.items.push(slim(it)); + save('playlists'); + toast(list.name + '에 추가됨'); + m.remove(); + }); +} + +// ------------------------------------------------------------------ views +let services = []; +const views = {}; + +views.home = async (p, signal) => { + const svc = services.find((s) => s.id === +S().service) || services[0]; + const kiosk = p.get('kiosk') || (svc && svc.defaultKiosk) || ''; + main.innerHTML = `

${esc(svc ? svc.name : '')}

${skeletonGrid()}
`; + if (svc) $('#kiosks').innerHTML = svc.kiosks.map((k) => `${esc(kioskName(k))}`).join(''); + try { + const r = await api('kiosk', { service: S().service, id: kiosk }, { signal, ttl: 10 * 60e3 }); + $('#list').innerHTML = r.items.length ? `
${r.items.map((i) => card(i)).join('')}
` : emptyState('flame', '표시할 동영상이 없습니다'); + if (r.items.length) paginate($('#list .grid'), r.next, (i) => card(i), signal); + } catch (e) { if (e.name !== 'AbortError') $('#list').innerHTML = errorBox(e); } +}; +const KIOSK_NAMES = { Trending: '인기 급상승', 'Recommended Lives': '추천 라이브', Live: '라이브', Music: '음악', Gaming: '게임', Movies: '영화', Recommended: '추천', 'Top 50': 'Top 50', 'New & hot': '최신 인기' }; +const kioskName = (k) => KIOSK_NAMES[k] || k; + +const FILTER_NAMES = { all: '전체', videos: '동영상', channels: '채널', playlists: '재생목록', movies: '영화', music_songs: '노래', music_videos: '뮤직비디오', + music_albums: '앨범', music_playlists: '음악 재생목록', music_artists: '아티스트', lives: '라이브', animes: '애니메이션', movies_and_tv: '영화·TV' }; +views.search = async (p, signal) => { + const q = p.get('q') || ''; + const filter = p.get('filter'); + $('#search-input').value = q; + main.innerHTML = `

“${esc(q)}”

+
`; + try { + const params = { q, service: S().service }; + if (filter) params.filter = filter; + const r = await api('search', params, { signal, ttl: 5 * 60e3 }); + $('#filters').innerHTML = (r.filters || []).map((f) => `${esc(FILTER_NAMES[f.name] || f.name)}`).join(''); + if (r.suggestion) $('#sugg').innerHTML = `${r.corrected ? '다음 검색결과 표시 중:' : '이것을 찾으셨나요?'} ${esc(r.suggestion)}`; + $('#list').innerHTML = r.items.length ? `
${r.items.map((i) => row(i)).join('')}
` : emptyState('search', '검색 결과가 없습니다'); + if (r.items.length) paginate($('#list .rows'), r.next, (i) => row(i), signal); + } catch (e) { if (e.name !== 'AbortError') $('#list').innerHTML = errorBox(e); } +}; + +views.feed = async (p, signal) => { + main.innerHTML = `

구독

${docs.subscriptions.length}개 채널
+
${docs.subscriptions.length ? skeletonGrid() : ''}
`; + if (!docs.subscriptions.length) { + $('#list').innerHTML = emptyState('rss', '구독한 채널이 없습니다', '채널 페이지에서 구독하거나, NewPipe/PipePipe 구독 목록을 가져오세요.'); + return; + } + const load = async (refresh) => { + try { + const r = await api('feed', refresh ? { refresh: 1 } : {}, { signal }); + $('#list').innerHTML = (r.failed ? `
${r.failed}개 채널을 불러오지 못했습니다
` : '') + + (r.items.length ? `
${r.items.map((i) => card(i, { noAvatar: true })).join('')}
` : emptyState('rss', '새 동영상이 없습니다')); + } catch (e) { if (e.name !== 'AbortError') $('#list').innerHTML = errorBox(e); } + }; + $('#refresh').onclick = () => { $('#list').innerHTML = skeletonGrid(); load(true); }; + load(false); +}; + +views.history = async () => { + const items = docs.history; + main.innerHTML = `

시청 기록

${items.length}개
+ ${items.length ? `` : ''}
+
${items.length ? groupByDay(items).map(([day, list]) => `
${esc(day)}
` + list.map((i) => row(i, { remove: 'rmhist' })).join('')).join('') : emptyState('history', '시청 기록이 없습니다')}
`; + const c = $('#clear'); + if (c) c.onclick = () => { if (confirm('시청 기록을 모두 삭제할까요?')) { docs.history = []; save('history', 0); views.history(); } }; +}; +function groupByDay(items) { + const groups = new Map(); + const fmt = new Intl.DateTimeFormat(loc(), { month: 'long', day: 'numeric', weekday: 'short' }); + const today = new Date().toDateString(), yest = new Date(Date.now() - 864e5).toDateString(); + for (const it of items) { + const d = new Date(it.at || 0); + const key = d.toDateString() === today ? '오늘' : d.toDateString() === yest ? '어제' : fmt.format(d); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(it); + } + return [...groups]; +} + +views.library = async () => { + const wl = docs.playlists.watchLater; + const lists = docs.playlists.lists; + main.innerHTML = ``; + $('#newpl').onclick = () => { + const name = prompt('새 재생목록 이름'); + if (!name) return; + docs.playlists.lists.push({ id: Math.random().toString(36).slice(2, 10), name, items: [] }); + save('playlists'); + views.library(); + }; +}; + +views.local = async (p) => { + const id = p.get('id'); + const isLater = id === 'later'; + const list = isLater ? { name: '나중에 볼 동영상', items: docs.playlists.watchLater } : docs.playlists.lists.find((l) => l.id === id); + if (!list) { main.innerHTML = `
${emptyState('library', '재생목록을 찾을 수 없습니다')}
`; return; } + const q = isLater ? 'later' : 'local:' + id; + const total = list.items.reduce((a, b) => a + (b.duration > 0 ? b.duration : 0), 0); + main.innerHTML = `
+
${thumbImg(list.items[0] && list.items[0].thumb)}

${esc(list.name)}

+
동영상 ${list.items.length}개 · ${fmtTime(total)}
+
${list.items.length ? `${icon('play')}모두 재생` : ''} + ${isLater ? '' : ``}
+
${list.items.length ? list.items.map((it, i) => row(it, { index: i, queue: q, remove: 'rmlocal' })).join('') : emptyState('library', '비어 있습니다', '동영상 카드에 마우스를 올리고 + 버튼으로 추가하세요.')}
`; + const del = $('#delpl'); + if (del) del.onclick = () => { if (confirm(`'${list.name}' 재생목록을 삭제할까요?`)) { docs.playlists.lists = docs.playlists.lists.filter((l) => l !== list); save('playlists'); location.hash = '#/library'; } }; + $('#list').dataset.local = id; +}; + +views.subs = async () => { + main.innerHTML = `

구독 관리

${docs.subscriptions.length}개 채널
+ +
+
${docs.subscriptions.length ? [...docs.subscriptions].sort((a, b) => a.name.localeCompare(b.name)).map((s) => ` + `).join('') : emptyState('rss', '구독한 채널이 없습니다', 'NewPipe 또는 PipePipe에서 내보낸 구독 JSON 파일을 가져올 수 있습니다.')}
`; + $('#import').onchange = async (e) => { + const f = e.target.files[0]; + if (!f) return; + try { + const j = JSON.parse(await f.text()); + const list = j.subscriptions || j; + let added = 0; + for (const s of list) { + const url = s.url; + if (!url || isSubscribed(url)) continue; + docs.subscriptions.push({ url, name: s.name || url, avatar: s.avatar || null, service: s.service_id ?? s.service ?? 0 }); + added++; + } + save('subscriptions', 0); + renderNavSubs(); + toast(added + '개 채널을 가져왔습니다'); + views.subs(); + } catch (err) { toast('가져오기 실패: ' + err.message); } + }; + $('#export').onclick = () => { + const out = { app_version: 'pipepipe-desktop', app_version_int: 1, subscriptions: docs.subscriptions.map((s) => ({ service_id: s.service, url: s.url, name: s.name })) }; + const a = document.createElement('a'); + a.href = URL.createObjectURL(new Blob([JSON.stringify(out, null, 2)], { type: 'application/json' })); + a.download = 'pipepipe_subscriptions.json'; + a.click(); + }; + $('.rows', main).addEventListener('click', (e) => { + const b = e.target.closest('[data-unsub]'); + if (!b) return; + const s = docs.subscriptions.find((x) => x.url === b.dataset.unsub); + if (s) { toggleSub(s); views.subs(); } + }); +}; + +views.channel = async (p, signal) => { + const url = p.get('url'); + main.innerHTML = `
${skeletonGrid(8)}
`; + try { + const c = await api('channel', { url }, { signal, ttl: 10 * 60e3 }); + const ch = { url: c.url, name: c.name, avatar: c.avatar, service: c.service }; + main.innerHTML = `
+ ${c.banner ? `
` : ''} +
${c.avatar ? `` : '
'} +

${esc(c.name)}

${c.subs > 0 ? '구독자 ' + fmtCount(c.subs) + '명' : ''}
+ ${c.description ? `
${esc(c.description)}
` : ''}
+
${subButton(ch)}
+
동영상
+
${c.items.length ? `
${c.items.map((i) => card(i, { noAvatar: true })).join('')}
` : emptyState('rss', '동영상이 없습니다')}
`; + $('#subbtn').onclick = () => { toggleSub(ch); $('#subbtn').innerHTML = subButton(ch); }; + // keep the stored name/avatar fresh + const s = docs.subscriptions.find((x) => x.url === c.url); + if (s && (s.avatar !== c.avatar || s.name !== c.name)) { s.avatar = c.avatar; s.name = c.name; save('subscriptions'); renderNavSubs(); } + if (c.items.length) paginate($('#list .grid'), c.next, (i) => card(i, { noAvatar: true }), signal); + } catch (e) { if (e.name !== 'AbortError') main.innerHTML = `
${errorBox(e)}
`; } +}; + +views.playlist = async (p, signal) => { + const url = p.get('url'); + main.innerHTML = `
`; + try { + const pl = await api('playlist', { url }, { signal, ttl: 10 * 60e3 }); + const q = 'remote:' + pl.url; + remoteQueues.set(q, pl.items.filter((i) => i.type === 'stream')); + main.innerHTML = `
+
${thumbImg(pl.thumb || (pl.items[0] && pl.items[0].thumb))}

${esc(pl.name)}

+
${pl.uploaderUrl ? `${esc(pl.uploader || '')}` : esc(pl.uploader || '')}${pl.count > 0 ? ` · 동영상 ${pl.count}개` : ''}
+
${pl.items.length ? `${icon('play')}모두 재생` : ''}
+
${pl.items.map((it, i) => row(it, { index: i, queue: q })).join('')}
`; + let n = pl.items.length; + paginate($('#list'), pl.next, (it) => { remoteQueues.get(q).push(it); return row(it, { index: n++, queue: q }); }, signal); + } catch (e) { if (e.name !== 'AbortError') main.innerHTML = `
${errorBox(e)}
`; } +}; + +views.settings = async () => { + const s = S(); + const opt = (v, cur, label) => ``; + main.innerHTML = `

설정

+

콘텐츠

+
기본 서비스홈 화면과 검색에 사용됩니다
+
콘텐츠 언어
+
콘텐츠 국가인기 동영상 지역
+
+

재생

+
최대 화질자동 화질이 이 해상도를 넘지 않습니다
+
선호 코덱AVC는 CPU 사용량이 낮고, VP9/AV1은 화질이 좋습니다
+
자동 재생끝나면 다음 동영상 재생
+
오디오 전용 모드영상 없이 소리만 (데이터·CPU 절약)
+
기본 자막
+
+

모양

+
테마
+
+

데이터

+
구독 가져오기/내보내기NewPipe · PipePipe JSON 형식 호환
구독 관리
+
시청 기록 삭제
+
+

단축키

+ /검색K재생 / 일시정지 (Space)J10초 뒤로 · L 10초 앞으로 · ←/→ 5초 + ↑ ↓볼륨M음소거F전체화면T영화관 모드IPIP + C자막Shift + N다음 동영상Shift + < >재생 속도0-9구간 이동 (10% 단위)Ctrl + B사이드바 +
+
PipePipe Desktop · PipePipeExtractor 기반 · 모든 데이터는 이 컴퓨터에만 저장됩니다.
`; + $$('[data-k]', main).forEach((el) => el.addEventListener('change', () => { + const k = el.dataset.k; + s[k] = el.type === 'checkbox' ? el.checked : (k === 'service' ? +el.value : el.value); + if (k === 'theme') applyTheme(); + if (k === 'service') paintService(); + if (k === 'language' || k === 'country') cache.clear(); + save('settings', 0); + toast('저장됨'); + })); + $('#clearhist').onclick = () => { if (confirm('시청 기록을 모두 삭제할까요?')) { docs.history = []; save('history', 0); toast('삭제됨'); } }; +}; + +// ------------------------------------------------------------------ watch +views.watch = async (p, signal) => { + const url = p.get('url'); + const q = p.get('q'); + const qi = p.get('i') != null ? +p.get('i') : -1; + const t = p.get('t'); + main.innerHTML = `
+
+
+
+
`; + $('#slot').appendChild(player.el); + $('#mini-dock').hidden = true; + const same = nowPlaying.url === url && nowPlaying.data; + nowPlaying.queue = q; nowPlaying.index = qi; + let d; + try { + d = same ? nowPlaying.data : await api('stream', { url }, { signal }); + } catch (e) { + if (e.name === 'AbortError') return; + $('#info').innerHTML = `
${errorBox(e)}
`; + $('#side').innerHTML = ''; + player.stop(); player.fail(e.message); + return; + } + if (signal.aborted) return; + if (!same) { + nowPlaying.url = url; nowPlaying.data = d; + sessionWatched.add(url); sessionWatched.add(d.url); + const h = historyFor(d.url); + const startAt = t ? +t : (h && h.pos > 10 && (!d.duration || h.pos < d.duration - 15) ? h.pos : 0); + recordHistory(d); + player.load(d, { startAt, autoplay: true }); + } + document.title = d.name + ' · PipePipe'; + renderWatchInfo(d, signal); + renderSide(d, q, qi); + player.el.focus({ preventScroll: true }); +}; + +function renderWatchInfo(d, signal) { + const ch = { url: d.uploader.url, name: d.uploader.name, avatar: d.uploader.avatar, service: d.service }; + const date = d.date ? new Intl.DateTimeFormat(loc(), { dateStyle: 'medium' }).format(new Date(d.date)) : (d.dateText || ''); + $('#info').innerHTML = ` +

${esc(d.name)}

+
+ ${ch.avatar ? `` : '
'}
+
${esc(ch.name)}${d.uploader.verified ? icon('verified', 'verified') : ''} +
${d.uploader.subs > 0 ? '구독자 ' + fmtCount(d.uploader.subs) + '명' : ''}
+ ${ch.url ? subButton(ch) : ''} +
+
+ ${d.likes > 0 ? `${icon('thumb')}${fmtCount(d.likes)}` : ''} + + + +
+
+ ${d.chapters.length ? `
${d.chapters.map((c) => ``).join('')}
` : ''} +
+
${d.live ? '실시간 스트리밍' : fmtViews(d.views)}${esc(date)}${d.category ? `${esc(d.category)}` : ''}
+
${richText(d.description.text, d.description.html)}
+ ${d.tags.length ? `
${d.tags.slice(0, 12).map((tg) => `#${esc(tg)}`).join('')}
` : ''} + +
+
댓글
`; + const desc = $('#desc'); + const body = $('.desc-body', desc); + if (body.scrollHeight <= body.clientHeight + 4 && !d.tags.length) $('#desc-toggle').remove(); + else $('#desc-toggle').onclick = () => { desc.classList.toggle('open'); $('#desc-toggle').textContent = desc.classList.contains('open') ? '간략히' : '더보기'; }; + $('#subbtn').onclick = () => { if (ch.url) { toggleSub(ch); $('#subbtn').innerHTML = subButton(ch); } }; + $('#later').onclick = () => addToWatchLater({ ...d, uploader: d.uploader.name, uploaderUrl: d.uploader.url }); + $('#addpl').onclick = (e) => addToPlaylistMenu({ ...d, uploader: d.uploader.name, uploaderUrl: d.uploader.url }, e.currentTarget); + $('#share').onclick = () => { navigator.clipboard.writeText(d.url).then(() => toast('링크를 복사했습니다')); }; + $$('.chapter').forEach((b) => b.onclick = () => { player.seek(+b.dataset.t); player.play(); }); + + // comments load lazily when scrolled near + const host = $('#comments'); + const io = new IntersectionObserver(async (en) => { + if (!en[0].isIntersecting) return; + io.disconnect(); + try { + const c = await api('comments', { url: d.url }, { signal, ttl: 5 * 60e3 }); + if (c.disabled) { host.innerHTML = '
댓글
댓글이 사용 중지되었습니다.
'; return; } + host.innerHTML = `
댓글
${c.items.map(comment).join('') || '
댓글이 없습니다
'}
`; + paginate($('#clist'), c.next, comment, signal); + } catch (e) { if (e.name !== 'AbortError') host.innerHTML = '
댓글
댓글을 불러오지 못했습니다
'; } + }, { root: main, rootMargin: '600px' }); + io.observe(host); + signal.addEventListener('abort', () => io.disconnect()); +} + +function comment(c) { + return `
${c.avatar ? `` : '
'} +
${esc(c.author)}${esc(fmtAgo(c.at, c.date))}
+
${richText(c.text, c.html)}
+
${c.likes > 0 || c.likesText ? `${icon('thumb')}${esc(c.likesText || fmtCount(c.likes))}` : ''}${c.replies > 0 ? `답글 ${c.replies}개` : ''}
`; +} + +function renderSide(d, q, qi) { + const items = queueItems(q); + let html = ''; + if (items && items.length) { + const title = q === 'later' ? '나중에 볼 동영상' : q.startsWith('local:') ? (docs.playlists.lists.find((l) => l.id === q.slice(6)) || {}).name : '재생목록'; + html += `
${esc(title || '')} ${qi + 1} / ${items.length}
+
${items.map((it, i) => row(it, { compact: true, queue: q, index: i })).join('')}
`; + } + html += `
다음 동영상
+
${d.related.map((it) => row(it, { compact: true })).join('') || '
관련 동영상이 없습니다
'}
`; + $('#side').innerHTML = html; + $('#autoplay').onchange = (e) => { S().autoplay = e.target.checked; save('settings'); }; + const cur = $$('#side .desc-box .row')[qi]; + if (cur) { cur.style.background = 'var(--bg-active)'; cur.style.borderRadius = '10px'; cur.scrollIntoView({ block: 'nearest' }); } +} + +// ------------------------------------------------------------------ router +let currentNav = new AbortController(); +const scrollPos = new Map(); +async function router() { + const hash = location.hash || '#/'; + const [path, qs] = hash.slice(2).split('?'); + const name = path || 'home'; + const p = new URLSearchParams(qs || ''); + scrollPos.set(router.last, main.scrollTop); + currentNav.abort(); + currentNav = new AbortController(); + $$('.menu.floating').forEach((m) => m.remove()); + $$('.nav-item').forEach((a) => a.classList.toggle('active', a.dataset.route === name)); + if (name !== 'watch') { + document.title = 'PipePipe'; + if (player && player.el.isConnected && !$('#mini-dock').contains(player.el)) dockToMini(); + } + const view = views[name] || views.home; + main.scrollTop = 0; + await view(p, currentNav.signal); + const back = router.popped && scrollPos.get(hash); + if (back) requestAnimationFrame(() => (main.scrollTop = back)); + router.last = hash; + router.popped = false; +} +window.addEventListener('popstate', () => (router.popped = true)); +window.addEventListener('hashchange', router); + +// ------------------------------------------------------------------ search box + suggestions +function setupSearch() { + const form = $('#search-form'), input = $('#search-input'), box = $('#suggest'); + let items = [], active = -1, timer, seq = 0; + const hide = () => { box.hidden = true; active = -1; }; + const paint = () => { + box.innerHTML = items.map((s, i) => `
  • ${icon('search')}${highlight(s, input.value)}
  • `).join(''); + box.hidden = !items.length; + }; + const go = (q) => { + q = q.trim(); + if (!q) return; + hide(); + input.blur(); + location.hash = routeForUrl(q) || route('search', { q }); + }; + input.addEventListener('input', () => { + clearTimeout(timer); + const q = input.value.trim(); + if (!q || /^https?:/.test(q)) { items = []; paint(); return; } + timer = setTimeout(async () => { + const my = ++seq; + try { + const r = await api('suggest', { q, service: S().service }, { ttl: 60e3 }); + if (my !== seq) return; + items = r.slice(0, 10); active = -1; paint(); + } catch (e) { /* ignore */ } + }, 120); + }); + input.addEventListener('keydown', (e) => { + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + if (!items.length) return; + e.preventDefault(); + // cycle through -1 (typed text) .. items.length-1 + const n = items.length + 1; + active = ((active + 1 + (e.key === 'ArrowDown' ? 1 : -1)) % n + n) % n - 1; + paint(); + if (active >= 0) input.value = items[active]; + } else if (e.key === 'Enter') { + e.preventDefault(); + go(active >= 0 ? items[active] : input.value); + } else if (e.key === 'Escape') { hide(); input.blur(); } + }); + input.addEventListener('blur', () => setTimeout(hide, 150)); + input.addEventListener('focus', () => { if (items.length) paint(); }); + box.addEventListener('mousedown', (e) => { const li = e.target.closest('li'); if (li) { e.preventDefault(); go(items[+li.dataset.i]); } }); + form.addEventListener('submit', (e) => { e.preventDefault(); go(input.value); }); +} +function highlight(s, q) { + const i = s.toLowerCase().indexOf(q.toLowerCase().trim()); + if (i < 0 || !q.trim()) return esc(s); + const n = q.trim().length; + return esc(s.slice(0, i)) + esc(s.slice(i, i + n)) + '' + esc(s.slice(i + n)) + ''; +} + +// ------------------------------------------------------------------ service switcher +function paintService() { + const svc = services.find((s) => s.id === +S().service) || services[0]; + $('#service-name').textContent = svc ? svc.name : ''; + $('#service-menu').innerHTML = services.map((s) => ``).join(''); +} +function setupServiceMenu() { + const btn = $('#service-btn'), menu = $('#service-menu'); + btn.onclick = (e) => { e.stopPropagation(); menu.hidden = !menu.hidden; }; + document.addEventListener('click', () => (menu.hidden = true)); + menu.addEventListener('click', (e) => { + const b = e.target.closest('[data-svc]'); + if (!b) return; + S().service = +b.dataset.svc; + save('settings', 0); + paintService(); + menu.hidden = true; + if (!location.hash || location.hash.startsWith('#/?') || location.hash === '#/') router(); else location.hash = '#/'; + }); +} + +// ------------------------------------------------------------------ theme / sidebar +function applyTheme() { + document.documentElement.dataset.theme = S().theme; + try { localStorage.setItem('pp.theme', S().theme); } catch (e) { /* private */ } + $('#theme-toggle').innerHTML = icon(S().theme === 'dark' ? 'moon' : 'sun'); +} +function applySidebar() { $('#app').classList.toggle('collapsed', !S().sidebar); } + +// ------------------------------------------------------------------ global interactions +function setupGlobal() { + // thumbnails fade in once decoded + document.addEventListener('load', (e) => { if (e.target.tagName === 'IMG') e.target.classList.add('loaded'); }, true); + document.addEventListener('error', (e) => { if (e.target.tagName === 'IMG') e.target.style.visibility = 'hidden'; }, true); + + document.addEventListener('click', (e) => { + const act = e.target.closest('[data-act]'); + if (act) { + e.preventDefault(); e.stopPropagation(); + const host = act.closest('[data-item]'); + const it = host ? JSON.parse(host.dataset.item) : null; + const a = act.dataset.act; + if (a === 'later' && it) addToWatchLater(it); + if (a === 'addpl' && it) addToPlaylistMenu(it, act); + if (a === 'rmhist' && it) { docs.history = docs.history.filter((h) => h.url !== it.url); save('history'); host.remove(); } + if (a === 'rmlocal' && it) { + const id = $('#list').dataset.local; + const list = id === 'later' ? docs.playlists.watchLater : docs.playlists.lists.find((l) => l.id === id).items; + const i = list.findIndex((x) => x.url === it.url); + if (i >= 0) list.splice(i, 1); + save('playlists'); host.remove(); + } + return; + } + const inner = e.target.closest('[data-href]'); + if (inner) { e.preventDefault(); e.stopPropagation(); location.hash = inner.dataset.href; return; } + const seek = e.target.closest('[data-seek]'); + if (seek) { e.preventDefault(); player.seek(+seek.dataset.seek); player.play(); $('#main').scrollTo({ top: 0, behavior: 'smooth' }); return; } + const ext = e.target.closest('a[data-ext]'); + if (ext) { + e.preventDefault(); + const r = routeForUrl(ext.href); + if (r && /youtube\.com|youtu\.be|bilibili|nicovideo/.test(ext.href)) location.hash = r; + else window.open(ext.href, '_blank', 'noopener'); + } + }); + + // hover prefetch: warms the server-side stream cache so opening a video is near instant + let pfTimer, inflight = 0; + const prefetched = new Set(); + document.addEventListener('mouseover', (e) => { + const el = e.target.closest('[data-prefetch]'); + clearTimeout(pfTimer); + if (!el) return; + const url = el.dataset.prefetch; + if (prefetched.has(url)) return; + pfTimer = setTimeout(() => { + if (inflight >= 2) return; + prefetched.add(url); inflight++; + fetch('/api/stream?url=' + encodeURIComponent(url)).catch(() => {}).finally(() => inflight--); + }, 180); + }); + + $('#sidebar-toggle').onclick = () => { S().sidebar = !S().sidebar; applySidebar(); save('settings'); }; + $('#theme-toggle').onclick = () => { S().theme = S().theme === 'dark' ? 'light' : 'dark'; applyTheme(); save('settings'); }; + $('#mini-expand').onclick = () => { if (nowPlaying.url) location.hash = route('watch', nowPlaying.queue ? { url: nowPlaying.url, q: nowPlaying.queue, i: nowPlaying.index } : { url: nowPlaying.url }); }; + $('#mini-title').onclick = () => $('#mini-expand').click(); + $('#mini-close').onclick = closeMini; + + document.addEventListener('keydown', (e) => { + const tag = (e.target.tagName || '').toLowerCase(); + if (tag === 'input' || tag === 'textarea' || tag === 'select' || e.target.isContentEditable) return; + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'b') { e.preventDefault(); $('#sidebar-toggle').click(); return; } + if (e.ctrlKey || e.metaKey || e.altKey) return; + if (e.key === '/') { e.preventDefault(); $('#search-input').focus(); $('#search-input').select(); return; } + const active = player && nowPlaying.url && player.el.isConnected; + if (!active) return; + const k = e.key; + const handled = () => { e.preventDefault(); player.wake && player.wake(); }; + if (k === ' ' || k === 'k' || k === 'K') { handled(); player.toggle(); } + else if (k === 'j' || k === 'J') { handled(); player.seekBy(-10); } + else if (k === 'l' || k === 'L') { handled(); player.seekBy(10); } + else if (k === 'ArrowLeft') { handled(); player.seekBy(-5); } + else if (k === 'ArrowRight') { handled(); player.seekBy(5); } + else if (k === 'ArrowUp' && document.activeElement === player.el || k === 'ArrowUp' && document.fullscreenElement) { handled(); player.volumeBy(0.05); } + else if (k === 'ArrowDown' && document.activeElement === player.el || k === 'ArrowDown' && document.fullscreenElement) { handled(); player.volumeBy(-0.05); } + else if (k === 'f' || k === 'F') { handled(); player.fullscreen(); } + else if (k === 'm' || k === 'M') { handled(); player.setMuted(!player.isMuted()); player.osd(player.isMuted() ? '음소거' : '음소거 해제'); } + else if (k === 't' || k === 'T') { handled(); player.emit('theater'); } + else if (k === 'i' || k === 'I') { handled(); player.pip(); } + else if (k === 'c' || k === 'C') { handled(); player.toggleCC(); } + else if (k === 'N' && e.shiftKey) { handled(); playNext(); } + else if (k === '>' ) { handled(); player.rateBy(1); } + else if (k === '<') { handled(); player.rateBy(-1); } + else if (/^[0-9]$/.test(k)) { handled(); player.seek(player.duration() * (+k / 10)); } + else if (k === 'Escape') { player.closeMenu(); } + }); +} + +// ------------------------------------------------------------------ boot +(async function boot() { + await loadDocs(); + applyTheme(); + applySidebar(); + try { services = await api('services'); } catch (e) { services = [{ id: 0, name: 'YouTube', kiosks: [], defaultKiosk: null }]; } + paintService(); + renderNavSubs(); + setupSearch(); + setupServiceMenu(); + setupGlobal(); + const waitShaka = () => new Promise((r) => { if (window.shaka) r(); else window.addEventListener('load', r, { once: true }); }); + await waitShaka(); + if (window.shaka) shaka.polyfill.installAll(); + initPlayer(); + router(); +})(); diff --git a/desktop/src/main/resources/web/icon.png b/desktop/src/main/resources/web/icon.png new file mode 100644 index 000000000..3653ec59e Binary files /dev/null and b/desktop/src/main/resources/web/icon.png differ diff --git a/desktop/src/main/resources/web/icon.svg b/desktop/src/main/resources/web/icon.svg new file mode 100644 index 000000000..6bcdce259 --- /dev/null +++ b/desktop/src/main/resources/web/icon.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/desktop/src/main/resources/web/index.html b/desktop/src/main/resources/web/index.html new file mode 100644 index 000000000..0f1e1b23a --- /dev/null +++ b/desktop/src/main/resources/web/index.html @@ -0,0 +1,113 @@ + + + + + +PipePipe + + + + + + +
    +
    + + +
    + + +
    +
    + + + +
    + + + +
    +
    + + + + + + + diff --git a/desktop/src/main/resources/web/player.js b/desktop/src/main/resources/web/player.js new file mode 100644 index 000000000..24d20c1f9 --- /dev/null +++ b/desktop/src/main/resources/web/player.js @@ -0,0 +1,665 @@ +// PipePipe Desktop player: shaka (DASH/HLS via local proxy) + progressive / split-stream fallback. +// One persistent instance; the root element moves between the watch page and the mini dock. + +const $ = (s, r = document) => r.querySelector(s); +const icon = (id) => ``; +const SPEEDS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3]; + +export function fmtTime(sec) { + if (!isFinite(sec) || sec < 0) sec = 0; + sec = Math.floor(sec); + const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60; + return (h ? h + ':' + String(m).padStart(2, '0') : m) + ':' + String(s).padStart(2, '0'); +} + +export class Player { + constructor(settings) { + this.settings = settings; + this.data = null; + this.shaka = null; + this.audio = null; // companion