Skip to content

Open-source music player for YouTube Music's catalog, with genres, full albums and playlists. Windows, macOS, Linux, Android, iPhone and Docker. No account needed.

TypeScript

iOS app: Capacitor platform, native resolving, native audio and lock screen

Vahid Etemovic19ca989079ff
diff --git a/mobile/capacitor.config.ts b/mobile/capacitor.config.ts
index 1cd363c..02f5c13 100644
--- a/mobile/capacitor.config.ts
+++ b/mobile/capacitor.config.ts
@@ -1,5 +1,9 @@
import type { CapacitorConfig } from "@capacitor/cli";
+// Built against a Musike server (MUSIKE_SERVER_URL=https://musike.example.com): the app then loads that instance.
+// Without it, the backend runs inside the app (see web/src/native).
+const serverUrl = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.MUSIKE_SERVER_URL;
+
const config: CapacitorConfig = {
appId: "app.musike.android",
appName: "Musike",
@@ -10,7 +14,19 @@ const config: CapacitorConfig = {
// Music keeps loading while the screen is off or another app is in front.
allowMixedContent: false,
},
+ ios: {
+ // The status bar area is padded by the app itself, like on Android.
+ contentInset: "never",
+ scrollEnabled: true,
+ backgroundColor: "#0B0C0F",
+ },
+ ...(serverUrl ? { server: { url: serverUrl, cleartext: false } } : {}),
plugins: {
+ Keyboard: {
+ // The web view shrinks with the keyboard, so the search box and its results stay in view.
+ resize: "native",
+ resizeOnFullScreen: true,
+ },
SystemBars: {
// The app already pads itself with env(safe-area-inset-*), like on an iPhone.
insetsHandling: "native",
diff --git a/mobile/ios/.gitignore b/mobile/ios/.gitignore
new file mode 100644
index 0000000..5a2e913
--- /dev/null
+++ b/mobile/ios/.gitignore
@@ -0,0 +1,16 @@
+App/build
+App/Pods
+App/output
+App/App/public
+DerivedData
+xcuserdata
+
+# Cordova plugins for Capacitor
+capacitor-cordova-ios-plugins
+
+# Generated Config files
+App/App/capacitor.config.json
+App/App/config.xml
+
+# Build output of mobile/scripts/build-ipa.mjs
+build/
diff --git a/mobile/ios/App/App.xcodeproj/project.pbxproj b/mobile/ios/App/App.xcodeproj/project.pbxproj
new file mode 100644
index 0000000..1f816b4
--- /dev/null
+++ b/mobile/ios/App/App.xcodeproj/project.pbxproj
@@ -0,0 +1,396 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 60;
+ objects = {
+
+/* Begin PBXBuildFile section */
+ 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; };
+ 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; };
+ 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; };
+ 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; };
+ 504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; };
+ 504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };
+ 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
+ 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
+ 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; };
+ AA0000000000000000000001 /* MusikePlayback.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0000000000000000000002 /* MusikePlayback.swift */; };
+ AA0000000000000000000003 /* MusikeWebViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0000000000000000000004 /* MusikeWebViewController.swift */; };
+ AA0000000000000000000006 /* MusikeYouTube.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0000000000000000000005 /* MusikeYouTube.swift */; };
+ AA0000000000000000000008 /* MusikeAudio.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0000000000000000000007 /* MusikeAudio.swift */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+ 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = "<group>"; };
+ 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = "<group>"; };
+ 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ 504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
+ 504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
+ 504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
+ 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+ 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
+ 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
+ AA0000000000000000000002 /* MusikePlayback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusikePlayback.swift; sourceTree = "<group>"; };
+ AA0000000000000000000004 /* MusikeWebViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusikeWebViewController.swift; sourceTree = "<group>"; };
+ AA0000000000000000000005 /* MusikeYouTube.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusikeYouTube.swift; sourceTree = "<group>"; };
+ AA0000000000000000000007 /* MusikeAudio.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusikeAudio.swift; sourceTree = "<group>"; };
+ 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 504EC3011FED79650016851F /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 504EC2FB1FED79650016851F = {
+ isa = PBXGroup;
+ children = (
+ 958DCC722DB07C7200EA8C5F /* debug.xcconfig */,
+ 504EC3061FED79650016851F /* App */,
+ 504EC3051FED79650016851F /* Products */,
+ );
+ sourceTree = "<group>";
+ };
+ 504EC3051FED79650016851F /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 504EC3041FED79650016851F /* App.app */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ 504EC3061FED79650016851F /* App */ = {
+ isa = PBXGroup;
+ children = (
+ 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */,
+ AA0000000000000000000002 /* MusikePlayback.swift */,
+ AA0000000000000000000004 /* MusikeWebViewController.swift */,
+ AA0000000000000000000005 /* MusikeYouTube.swift */,
+ AA0000000000000000000007 /* MusikeAudio.swift */,
+ 50379B222058CBB4000EE86E /* capacitor.config.json */,
+ 504EC3071FED79650016851F /* AppDelegate.swift */,
+ 504EC30B1FED79650016851F /* Main.storyboard */,
+ 504EC30E1FED79650016851F /* Assets.xcassets */,
+ 504EC3101FED79650016851F /* LaunchScreen.storyboard */,
+ 504EC3131FED79650016851F /* Info.plist */,
+ 2FAD9762203C412B000D30F8 /* config.xml */,
+ 50B271D01FEDC1A000F3C39B /* public */,
+ );
+ path = App;
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 504EC3031FED79650016851F /* App */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */;
+ buildPhases = (
+ 504EC3001FED79650016851F /* Sources */,
+ 504EC3011FED79650016851F /* Frameworks */,
+ 504EC3021FED79650016851F /* Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = App;
+ packageProductDependencies = (
+ 4D22ABE82AF431CB00220026 /* CapApp-SPM */,
+ );
+ productName = App;
+ productReference = 504EC3041FED79650016851F /* App.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 504EC2FC1FED79650016851F /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ LastSwiftUpdateCheck = 0920;
+ LastUpgradeCheck = 0920;
+ TargetAttributes = {
+ 504EC3031FED79650016851F = {
+ CreatedOnToolsVersion = 9.2;
+ LastSwiftMigration = 1100;
+ ProvisioningStyle = Automatic;
+ };
+ };
+ };
+ buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */;
+ compatibilityVersion = "Xcode 8.0";
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ Base,
+ );
+ mainGroup = 504EC2FB1FED79650016851F;
+ packageReferences = (
+ D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */,
+ );
+ productRefGroup = 504EC3051FED79650016851F /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 504EC3031FED79650016851F /* App */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ 504EC3021FED79650016851F /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */,
+ 50B271D11FEDC1A000F3C39B /* public in Resources */,
+ 504EC30F1FED79650016851F /* Assets.xcassets in Resources */,
+ 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */,
+ 504EC30D1FED79650016851F /* Main.storyboard in Resources */,
+ 2FAD9763203C412B000D30F8 /* config.xml in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 504EC3001FED79650016851F /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
+ 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */,
+ AA0000000000000000000001 /* MusikePlayback.swift in Sources */,
+ AA0000000000000000000003 /* MusikeWebViewController.swift in Sources */,
+ AA0000000000000000000006 /* MusikeYouTube.swift in Sources */,
+ AA0000000000000000000008 /* MusikeAudio.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXVariantGroup section */
+ 504EC30B1FED79650016851F /* Main.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 504EC30C1FED79650016851F /* Base */,
+ );
+ name = Main.storyboard;
+ sourceTree = "<group>";
+ };
+ 504EC3101FED79650016851F /* LaunchScreen.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 504EC3111FED79650016851F /* Base */,
+ );
+ name = LaunchScreen.storyboard;
+ sourceTree = "<group>";
+ };
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+ 504EC3141FED79650016851F /* Debug */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = dwarf;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_TESTABILITY = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ GCC_PREPROCESSOR_DEFINITIONS = (
+ "DEBUG=1",
+ "$(inherited)",
+ );
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ MTL_ENABLE_DEBUG_INFO = YES;
+ ONLY_ACTIVE_ARCH = YES;
+ SDKROOT = iphoneos;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ };
+ name = Debug;
+ };
+ 504EC3151FED79650016851F /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGN_IDENTITY = "iPhone Developer";
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ SDKROOT = iphoneos;
+ SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_OPTIMIZATION_LEVEL = "-O";
+ VALIDATE_PRODUCT = YES;
+ };
+ name = Release;
+ };
+ 504EC3171FED79650016851F /* Debug */ = {
+ isa = XCBuildConfiguration;
+ baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 10402;
+ INFOPLIST_FILE = App/Info.plist;
+ IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ MARKETING_VERSION = 1.4.2;
+ OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
+ PRODUCT_BUNDLE_IDENTIFIER = app.musike.ios;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
+ 504EC3181FED79650016851F /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 10402;
+ INFOPLIST_FILE = App/Info.plist;
+ IPHONEOS_DEPLOYMENT_TARGET = 15.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ );
+ MARKETING_VERSION = 1.4.2;
+ PRODUCT_BUNDLE_IDENTIFIER = app.musike.ios;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 504EC3141FED79650016851F /* Debug */,
+ 504EC3151FED79650016851F /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 504EC3171FED79650016851F /* Debug */,
+ 504EC3181FED79650016851F /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+
+/* Begin XCLocalSwiftPackageReference section */
+ D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */ = {
+ isa = XCLocalSwiftPackageReference;
+ relativePath = "CapApp-SPM";
+ };
+/* End XCLocalSwiftPackageReference section */
+
+/* Begin XCSwiftPackageProductDependency section */
+ 4D22ABE82AF431CB00220026 /* CapApp-SPM */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = D4C12C0A2AAA248700AAC8A2 /* XCLocalSwiftPackageReference "CapApp-SPM" */;
+ productName = "CapApp-SPM";
+ };
+/* End XCSwiftPackageProductDependency section */
+ };
+ rootObject = 504EC2FC1FED79650016851F /* Project object */;
+}
diff --git a/mobile/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mobile/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
new file mode 100644
index 0000000..18d9810
--- /dev/null
+++ b/mobile/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>IDEDidComputeMac32BitWarning</key>
+ <true/>
+</dict>
+</plist>
diff --git a/mobile/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mobile/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
new file mode 100644
index 0000000..675bfde
--- /dev/null
+++ b/mobile/ios/App/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -0,0 +1,24 @@
+{
+ "originHash" : "4981192772b7f327415ef462d2453a441e74a7bf9ccbd9026d143d9788d63a0a",
+ "pins" : [
+ {
+ "identity" : "capacitor-swift-pm",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/ionic-team/capacitor-swift-pm.git",
+ "state" : {
+ "revision" : "4c7f346d16196e21fbe23d4a7a6fc7af62af6742",
+ "version" : "8.5.3"
+ }
+ },
+ {
+ "identity" : "ion-ios-filesystem",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/ionic-team/ion-ios-filesystem.git",
+ "state" : {
+ "revision" : "549c18ad9d9bb70d05df37cc3f6f7aa7f5d0ee52",
+ "version" : "2.0.1"
+ }
+ }
+ ],
+ "version" : 3
+}
diff --git a/mobile/ios/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme b/mobile/ios/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme
new file mode 100644
index 0000000..b745155
--- /dev/null
+++ b/mobile/ios/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "2700"
+ version = "1.7">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "504EC3031FED79650016851F"
+ BuildableName = "App.app"
+ BlueprintName = "App"
+ ReferencedContainer = "container:App.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES">
+ <Testables>
+ </Testables>
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "504EC3031FED79650016851F"
+ BuildableName = "App.app"
+ BlueprintName = "App"
+ ReferencedContainer = "container:App.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "504EC3031FED79650016851F"
+ BuildableName = "App.app"
+ BlueprintName = "App"
+ ReferencedContainer = "container:App.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/mobile/ios/App/App/AppDelegate.swift b/mobile/ios/App/App/AppDelegate.swift
new file mode 100644
index 0000000..fec95ac
--- /dev/null
+++ b/mobile/ios/App/App/AppDelegate.swift
@@ -0,0 +1,44 @@
+import UIKit
+import Capacitor
+
+@UIApplicationMain
+class AppDelegate: UIResponder, UIApplicationDelegate {
+
+ var window: UIWindow?
+
+ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
+ // Override point for customization after application launch.
+ return true
+ }
+
+ func applicationWillResignActive(_ application: UIApplication) {
+ // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
+ // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
+ }
+
+ func applicationDidEnterBackground(_ application: UIApplication) {
+ // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
+ // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
+ }
+
+ func applicationWillEnterForeground(_ application: UIApplication) {
+ // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
+ }
+
+ func applicationDidBecomeActive(_ application: UIApplication) {
+ // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
+ }
+
+ func applicationWillTerminate(_ application: UIApplication) {
+ // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
+ }
+
+ func application(_ application: UIApplication,
+ configurationForConnecting connectingSceneSession: UISceneSession,
+ options: UIScene.ConnectionOptions) -> UISceneConfiguration {
+ let config = UISceneConfiguration(name: "Default Configuration",
+ sessionRole: connectingSceneSession.role)
+ config.delegateClass = SceneDelegate.self
+ return config
+ }
+}
diff --git a/mobile/ios/App/App/Assets.xcassets/AppIcon.appiconset/[email protected] b/mobile/ios/App/App/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 0000000..d47fbf8
Binary files /dev/null and b/mobile/ios/App/App/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/mobile/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/mobile/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 0000000..9b7d382
--- /dev/null
+++ b/mobile/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,14 @@
+{
+ "images" : [
+ {
+ "filename" : "[email protected]",
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/mobile/ios/App/App/Assets.xcassets/Contents.json b/mobile/ios/App/App/Assets.xcassets/Contents.json
new file mode 100644
index 0000000..da4a164
--- /dev/null
+++ b/mobile/ios/App/App/Assets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/mobile/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json
new file mode 100644
index 0000000..d7d96a6
--- /dev/null
+++ b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json
@@ -0,0 +1,23 @@
+{
+ "images" : [
+ {
+ "idiom" : "universal",
+ "filename" : "splash-2732x2732-2.png",
+ "scale" : "1x"
+ },
+ {
+ "idiom" : "universal",
+ "filename" : "splash-2732x2732-1.png",
+ "scale" : "2x"
+ },
+ {
+ "idiom" : "universal",
+ "filename" : "splash-2732x2732.png",
+ "scale" : "3x"
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png
new file mode 100644
index 0000000..5ef305b
Binary files /dev/null and b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png differ
diff --git a/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png
new file mode 100644
index 0000000..5ef305b
Binary files /dev/null and b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png differ
diff --git a/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png
new file mode 100644
index 0000000..5ef305b
Binary files /dev/null and b/mobile/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png differ
diff --git a/mobile/ios/App/App/Base.lproj/LaunchScreen.storyboard b/mobile/ios/App/App/Base.lproj/LaunchScreen.storyboard
new file mode 100644
index 0000000..e7ae5d7
--- /dev/null
+++ b/mobile/ios/App/App/Base.lproj/LaunchScreen.storyboard
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17132" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
+ <device id="retina4_7" orientation="portrait" appearance="light"/>
+ <dependencies>
+ <deployment identifier="iOS"/>
+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17105"/>
+ <capability name="System colors in document resources" minToolsVersion="11.0"/>
+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
+ </dependencies>
+ <scenes>
+ <!--View Controller-->
+ <scene sceneID="EHf-IW-A2E">
+ <objects>
+ <viewController id="01J-lp-oVM" sceneMemberID="viewController">
+ <imageView key="view" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="Splash" id="snD-IY-ifK">
+ <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
+ <autoresizingMask key="autoresizingMask"/>
+ <color key="backgroundColor" systemColor="systemBackgroundColor"/>
+ </imageView>
+ </viewController>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
+ </objects>
+ <point key="canvasLocation" x="53" y="375"/>
+ </scene>
+ </scenes>
+ <resources>
+ <image name="Splash" width="1366" height="1366"/>
+ <systemColor name="systemBackgroundColor">
+ <color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
+ </systemColor>
+ </resources>
+</document>
diff --git a/mobile/ios/App/App/Base.lproj/Main.storyboard b/mobile/ios/App/App/Base.lproj/Main.storyboard
new file mode 100644
index 0000000..b44df7b
--- /dev/null
+++ b/mobile/ios/App/App/Base.lproj/Main.storyboard
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14111" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
+ <device id="retina4_7" orientation="portrait">
+ <adaptation id="fullscreen"/>
+ </device>
+ <dependencies>
+ <deployment identifier="iOS"/>
+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
+ </dependencies>
+ <scenes>
+ <!--Bridge View Controller-->
+ <scene sceneID="tne-QT-ifu">
+ <objects>
+ <viewController id="BYZ-38-t0r" customClass="CAPBridgeViewController" customModule="Capacitor" sceneMemberID="viewController"/>
+ <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
+ </objects>
+ </scene>
+ </scenes>
+</document>
diff --git a/mobile/ios/App/App/Info.plist b/mobile/ios/App/App/Info.plist
new file mode 100644
index 0000000..9b235c1
--- /dev/null
+++ b/mobile/ios/App/App/Info.plist
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CAPACITOR_DEBUG</key>
+ <string>$(CAPACITOR_DEBUG)</string>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>Musike</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>LSRequiresIPhoneOS</key>
+ <true/>
+ <key>UIBackgroundModes</key>
+ <array>
+ <string>audio</string>
+ </array>
+ <key>UIApplicationSceneManifest</key>
+ <dict>
+ <key>UIApplicationSupportsMultipleScenes</key>
+ <false/>
+ <key>UISceneConfigurations</key>
+ <dict>
+ <key>UIWindowSceneSessionRoleApplication</key>
+ <array>
+ <dict>
+ <key>UISceneConfigurationName</key>
+ <string>Default Configuration</string>
+ <key>UISceneDelegateClassName</key>
+ <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
+ <key>UISceneStoryboardFile</key>
+ <string>Main</string>
+ </dict>
+ </array>
+ </dict>
+ </dict>
+ <key>UILaunchStoryboardName</key>
+ <string>LaunchScreen</string>
+ <key>UIMainStoryboardFile</key>
+ <string>Main</string>
+ <key>UIRequiredDeviceCapabilities</key>
+ <array>
+ <string>armv7</string>
+ </array>
+ <key>UISupportedInterfaceOrientations</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+ <key>UISupportedInterfaceOrientations~ipad</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+ <key>UIViewControllerBasedStatusBarAppearance</key>
+ <true/>
+</dict>
+</plist>
diff --git a/mobile/ios/App/App/MusikeAudio.swift b/mobile/ios/App/App/MusikeAudio.swift
new file mode 100644
index 0000000..54dab7c
--- /dev/null
+++ b/mobile/ios/App/App/MusikeAudio.swift
@@ -0,0 +1,137 @@
+import AVFoundation
+import Capacitor
+import WebKit
+
+/// Plays audio natively, so the music doesn't go through the web view's media stack.
+///
+/// WKWebView hands media to a separate process that YouTube cuts off after a few hundred kilobytes: the element
+/// just pauses, with no error, about fifteen seconds in. AVPlayer uses the app's own network stack instead, which
+/// reads the same URL from beginning to end. The web app drives it through the `musikeAudio` handler and gets
+/// `window.__musikeAudioEvent(...)` back, so the player code doesn't have to know the difference.
+final class MusikeAudio: NSObject, WKScriptMessageHandler {
+ private weak var webView: WKWebView?
+ private var player: AVPlayer?
+ private var item: AVPlayerItem?
+ private var ticker: Any?
+ private var statusObservation: NSKeyValueObservation?
+ private var endObserver: NSObjectProtocol?
+
+ func attach(_ webView: WKWebView?) {
+ self.webView = webView
+ }
+
+ // MARK: - What the web app sends
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard message.name == "musikeAudio",
+ let body = message.body as? [String: Any],
+ let command = body["cmd"] as? String
+ else { return }
+
+ switch command {
+ case "load":
+ load(body["url"] as? String ?? "", startAt: body["startAt"] as? Double ?? 0)
+ case "play":
+ play()
+ case "pause":
+ player?.pause()
+ case "seek":
+ seek(body["to"] as? Double ?? 0)
+ case "volume":
+ player?.volume = Float(body["value"] as? Double ?? 1)
+ case "muted":
+ player?.isMuted = body["value"] as? Bool ?? false
+ default:
+ break
+ }
+ }
+
+ // MARK: - Playback
+
+ private func load(_ link: String, startAt: Double) {
+ tearDown()
+ guard let url = URL(string: link), !link.isEmpty else {
+ emit("error", ["message": "No stream"])
+ return
+ }
+ let asset = AVURLAsset(url: url, options: [
+ "AVURLAssetHTTPHeaderFieldsKey": [
+ "User-Agent": "com.google.ios.youtube/20.10.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)",
+ ],
+ ])
+ let newItem = AVPlayerItem(asset: asset)
+ let newPlayer = AVPlayer(playerItem: newItem)
+ newPlayer.automaticallyWaitsToMinimizeStalling = true
+ newPlayer.volume = player?.volume ?? 1
+ player = newPlayer
+ item = newItem
+
+ statusObservation = newItem.observe(\.status, options: [.initial, .new]) { [weak self] item, _ in
+ guard let self else { return }
+ switch item.status {
+ case .readyToPlay:
+ let seconds = CMTimeGetSeconds(item.duration)
+ self.emit("ready", ["duration": seconds.isFinite ? seconds : 0])
+ if startAt > 0 { self.seek(startAt) }
+ case .failed:
+ self.emit("error", ["message": item.error?.localizedDescription ?? "Playback failed"])
+ default:
+ break
+ }
+ }
+ endObserver = NotificationCenter.default.addObserver(
+ forName: .AVPlayerItemDidPlayToEndTime, object: newItem, queue: .main
+ ) { [weak self] _ in
+ self?.emit("ended")
+ }
+ ticker = newPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.5, preferredTimescale: 600), queue: .main) { [weak self] time in
+ guard let self, let item = self.item else { return }
+ let duration = CMTimeGetSeconds(item.duration)
+ self.emit("time", [
+ "position": CMTimeGetSeconds(time),
+ "duration": duration.isFinite ? duration : 0,
+ "buffered": self.bufferedEnd(),
+ ])
+ }
+ }
+
+ private func play() {
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playback, mode: .default)
+ try? session.setActive(true)
+ player?.play()
+ emit("playing")
+ }
+
+ private func seek(_ to: Double) {
+ player?.seek(to: CMTime(seconds: max(0, to), preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero)
+ }
+
+ private func bufferedEnd() -> Double {
+ guard let range = item?.loadedTimeRanges.last?.timeRangeValue else { return 0 }
+ return CMTimeGetSeconds(CMTimeAdd(range.start, range.duration))
+ }
+
+ private func tearDown() {
+ if let ticker { player?.removeTimeObserver(ticker) }
+ ticker = nil
+ statusObservation = nil
+ if let endObserver { NotificationCenter.default.removeObserver(endObserver) }
+ endObserver = nil
+ player?.pause()
+ player = nil
+ item = nil
+ }
+
+ private func emit(_ event: String, _ payload: [String: Any] = [:]) {
+ guard let data = try? JSONSerialization.data(withJSONObject: payload),
+ let json = String(data: data, encoding: .utf8)
+ else { return }
+ let js = "window.__musikeAudioEvent && window.__musikeAudioEvent('\(event)', \(json))"
+ if Thread.isMainThread {
+ webView?.evaluateJavaScript(js)
+ } else {
+ DispatchQueue.main.async { [weak self] in self?.webView?.evaluateJavaScript(js) }
+ }
+ }
+}
diff --git a/mobile/ios/App/App/MusikePlayback.swift b/mobile/ios/App/App/MusikePlayback.swift
new file mode 100644
index 0000000..2b99b57
--- /dev/null
+++ b/mobile/ios/App/App/MusikePlayback.swift
@@ -0,0 +1,139 @@
+import AVFoundation
+import Capacitor
+import MediaPlayer
+import UIKit
+import WebKit
+
+/// The iOS side of the player: the lock screen, Control Center and the headphone buttons.
+///
+/// The web app talks to it over the `musikeMedia` message handler (web/src/native/media.ts) and it talks back with
+/// `window.__musikeMediaAction(...)` — the same actions Android's MusikePlaybackPlugin sends, so the player code on
+/// both platforms is the one already written for Android.
+final class MusikePlayback: NSObject, WKScriptMessageHandler {
+ private weak var webView: WKWebView?
+ private var nowPlaying: [String: Any] = [:]
+ private var artworks: [String: MPMediaItemArtwork] = [:]
+ private var artworkURL = ""
+ private var artworkTask: URLSessionDataTask?
+
+ override init() {
+ super.init()
+ let session = AVAudioSession.sharedInstance()
+ // Playback: the music keeps going with the screen off. Activating it happens when something plays, so the
+ // app doesn't take the audio away from whatever the user was listening to before opening Musike.
+ try? session.setCategory(.playback, mode: .default)
+ configureCommands()
+ }
+
+ /** Called once the web view exists, so the lock screen's buttons have somewhere to go. */
+ func attach(_ webView: WKWebView?) {
+ self.webView = webView
+ }
+
+ // MARK: - The lock screen's buttons
+
+ private func configureCommands() {
+ let center = MPRemoteCommandCenter.shared()
+ center.playCommand.addTarget { [weak self] _ in
+ self?.send("play")
+ return .success
+ }
+ center.pauseCommand.addTarget { [weak self] _ in
+ self?.send("pause")
+ return .success
+ }
+ center.togglePlayPauseCommand.addTarget { [weak self] _ in
+ self?.send("toggle")
+ return .success
+ }
+ center.nextTrackCommand.addTarget { [weak self] _ in
+ self?.send("next")
+ return .success
+ }
+ center.previousTrackCommand.addTarget { [weak self] _ in
+ self?.send("previous")
+ return .success
+ }
+ center.changePlaybackPositionCommand.addTarget { [weak self] event in
+ guard let seek = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed }
+ self?.send("seek", position: seek.positionTime)
+ return .success
+ }
+ }
+
+ private func send(_ action: String, position: Double? = nil) {
+ var js = "window.__musikeMediaAction && window.__musikeMediaAction('\(action)')"
+ if let position { js = "window.__musikeMediaAction && window.__musikeMediaAction('\(action)', \(position))" }
+ DispatchQueue.main.async { [weak self] in
+ self?.webView?.evaluateJavaScript(js)
+ }
+ }
+
+ // MARK: - What the web app sends
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard message.name == "musikeMedia",
+ let body = message.body as? [String: Any],
+ let type = body["type"] as? String
+ else { return }
+ switch type {
+ case "track": setTrack(body)
+ case "state": setState(body)
+ default: break
+ }
+ }
+
+ private func setTrack(_ body: [String: Any]) {
+ nowPlaying[MPMediaItemPropertyTitle] = body["title"] as? String ?? ""
+ nowPlaying[MPMediaItemPropertyArtist] = body["artist"] as? String ?? ""
+ nowPlaying[MPMediaItemPropertyAlbumTitle] = body["album"] as? String ?? ""
+ nowPlaying[MPNowPlayingInfoPropertyElapsedPlaybackTime] = number(body["position"])
+ if number(body["duration"]) > 0 { nowPlaying[MPMediaItemPropertyPlaybackDuration] = number(body["duration"]) }
+ publish()
+ if let link = body["artwork"] as? String { loadArtwork(link) }
+ }
+
+ private func setState(_ body: [String: Any]) {
+ let playing = body["playing"] as? Bool ?? false
+ nowPlaying[MPNowPlayingInfoPropertyElapsedPlaybackTime] = number(body["position"])
+ nowPlaying[MPNowPlayingInfoPropertyPlaybackRate] = playing ? 1.0 : 0.0
+ if number(body["duration"]) > 0 { nowPlaying[MPMediaItemPropertyPlaybackDuration] = number(body["duration"]) }
+ if playing { try? AVAudioSession.sharedInstance().setActive(true) }
+ publish(state: playing ? .playing : .paused)
+ }
+
+ private func publish(state: MPNowPlayingPlaybackState? = nil) {
+ MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlaying
+ if let state { MPNowPlayingInfoCenter.default().playbackState = state }
+ }
+
+ private func number(_ value: Any?) -> Double {
+ if let d = value as? Double { return d }
+ if let n = value as? NSNumber { return n.doubleValue }
+ return 0
+ }
+
+ // MARK: - Artwork
+
+ private func loadArtwork(_ link: String) {
+ guard link != artworkURL, let url = URL(string: link), url.scheme == "https" else { return }
+ artworkURL = link
+ if let cached = artworks[link] {
+ nowPlaying[MPMediaItemPropertyArtwork] = cached
+ publish()
+ return
+ }
+ artworkTask?.cancel()
+ artworkTask = URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
+ guard let self, let data, let image = UIImage(data: data), link == self.artworkURL else { return }
+ let artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
+ DispatchQueue.main.async {
+ if self.artworks.count > 8 { self.artworks.removeAll() }
+ self.artworks[link] = artwork
+ self.nowPlaying[MPMediaItemPropertyArtwork] = artwork
+ self.publish()
+ }
+ }
+ artworkTask?.resume()
+ }
+}
diff --git a/mobile/ios/App/App/MusikeWebViewController.swift b/mobile/ios/App/App/MusikeWebViewController.swift
new file mode 100644
index 0000000..a8f12b2
--- /dev/null
+++ b/mobile/ios/App/App/MusikeWebViewController.swift
@@ -0,0 +1,25 @@
+import Capacitor
+import UIKit
+import WebKit
+
+/// The app's web view: Capacitor's own, plus the two bridges iOS needs that Android has in its Java code —
+/// the lock screen (MusikePlayback) and resolving a stream URL (MusikeYouTube).
+final class MusikeWebViewController: CAPBridgeViewController {
+ private let playback = MusikePlayback()
+ private let youtube = MusikeYouTube()
+ private let audio = MusikeAudio()
+
+ override func capacitorDidLoad() {
+ super.capacitorDidLoad()
+ // Capacitor replaces the web view's userContentController after the configuration is built, so the handlers
+ // are added here, once the web view exists.
+ webView?.configuration.userContentController.add(playback, name: "musikeMedia")
+ webView?.configuration.userContentController.add(youtube, name: "musikeResolve")
+ webView?.configuration.userContentController.add(audio, name: "musikeAudio")
+ playback.attach(webView)
+ youtube.attach(webView)
+ audio.attach(webView)
+ // Swipe from the left edge goes back, like the Android back button: dialogs close, then pages.
+ webView?.allowsBackForwardNavigationGestures = true
+ }
+}
diff --git a/mobile/ios/App/App/MusikeYouTube.swift b/mobile/ios/App/App/MusikeYouTube.swift
new file mode 100644
index 0000000..ae80f12
--- /dev/null
+++ b/mobile/ios/App/App/MusikeYouTube.swift
@@ -0,0 +1,169 @@
+import Foundation
+import WebKit
+
+/// Gets a playable stream URL for a video, the job yt-dlp does on a computer.
+///
+/// Two things make this native rather than JavaScript. First, YouTube bot-checks requests that arrive through the
+/// web view's HTTP stack, while the same request from URLSession gets a plain answer. Second, the `ios` client stops
+/// serving a stream after the first couple of megabytes (it wants a proof-of-origin token); `VISIONOS` still hands
+/// out URLs the phone can read from beginning to end, and it only answers a session that already has a visitor id.
+final class MusikeYouTube: NSObject, WKScriptMessageHandler {
+ private weak var webView: WKWebView?
+
+ private static let playerURL = URL(string: "https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json")!
+ private static let visitorURL = URL(string: "https://www.youtube.com/youtubei/v1/visitor_id?prettyPrint=false")!
+ private static let userAgent =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15"
+ /// Clients to try, in order: VISIONOS hands out URLs that need no proof-of-origin token, the others are the
+ /// fallbacks YouTube leaves open on some networks.
+ private static let clients: [(name: String, version: String, id: String)] = [
+ ("VISIONOS", "1.02", "101"),
+ ("ANDROID_VR", "1.60.19", "28"),
+ ("IOS", "20.10.4", "5"),
+ ]
+ private static let visitorKey = "musike:visitorData"
+ private static let visitorAgeKey = "musike:visitorDataAt"
+ private static let visitorTTL: TimeInterval = 24 * 3600
+
+ func attach(_ webView: WKWebView?) {
+ self.webView = webView
+ }
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard message.name == "musikeResolve",
+ let body = message.body as? [String: Any],
+ let request = body["req"] as? Int,
+ let id = body["id"] as? String
+ else { return }
+ resolve(
+ videoId: id,
+ lang: body["lang"] as? String ?? "en",
+ region: body["region"] as? String ?? "US"
+ ) { payload in
+ DispatchQueue.main.async { [weak self] in
+ guard let json = try? JSONSerialization.data(withJSONObject: payload),
+ let text = String(data: json, encoding: .utf8)
+ else { return }
+ self?.webView?.evaluateJavaScript("window.__musikeResolve && window.__musikeResolve(\(request), \(text))")
+ }
+ }
+ }
+
+ // MARK: - The two requests
+
+ /// The player, with a visitor id YouTube accepts.
+ private func resolve(videoId: String, lang: String, region: String, done: @escaping ([String: Any]) -> Void) {
+ visitor(lang: lang, region: region) { [weak self] visitorData in
+ guard let self else { return }
+ self.tryClient(videoId: videoId, visitorData: visitorData, lang: lang, region: region, at: 0, done: done)
+ }
+ }
+
+ private func tryClient(
+ videoId: String, visitorData: String, lang: String, region: String, at index: Int,
+ done: @escaping ([String: Any]) -> Void
+ ) {
+ guard index < Self.clients.count else {
+ NSLog("Musike: every YouTube client was refused for %@", videoId)
+ done(["error": "YouTube asked for an anti-bot check.", "code": "bot_check"])
+ return
+ }
+ let client = Self.clients[index]
+ let body = playerBody(videoId: videoId, visitorData: visitorData, lang: lang, region: region, client: client)
+ post(Self.playerURL, body, client: client) { [weak self] result in
+ guard let self else { return }
+ let status = (result?["playabilityStatus"] as? [String: Any])?["status"] as? String ?? "no answer"
+ guard status == "OK" else {
+ self.tryClient(videoId: videoId, visitorData: visitorData, lang: lang, region: region, at: index + 1, done: done)
+ return
+ }
+ let details = result?["videoDetails"] as? [String: Any] ?? [:]
+ let formats = ((result?["streamingData"] as? [String: Any])?["adaptiveFormats"] as? [[String: Any]] ?? [])
+ .filter { ($0["mimeType"] as? String)?.hasPrefix("audio/mp4") == true && $0["url"] != nil }
+ .sorted { Self.int($0["bitrate"]) > Self.int($1["bitrate"]) }
+ guard let best = formats.first, let url = best["url"] as? String else {
+ done(["error": "No audio format available for this video.", "code": "no_audio"])
+ return
+ }
+ done([
+ "url": url,
+ "mime": best["mimeType"] as? String ?? "audio/mp4",
+ "title": details["title"] as? String ?? "",
+ "duration": Self.int(details["lengthSeconds"]),
+ ])
+ }
+ }
+
+ private func playerBody(
+ videoId: String, visitorData: String, lang: String, region: String,
+ client chosen: (name: String, version: String, id: String)
+ ) -> [String: Any] {
+ var client = client(lang: lang, region: region, chosen: chosen)
+ client["visitorData"] = visitorData
+ client["originalUrl"] = "https://www.youtube.com/watch?v=\(videoId)"
+ return [
+ "videoId": videoId,
+ "racyCheckOk": true,
+ "contentCheckOk": true,
+ "context": ["client": client],
+ "playbackContext": ["contentPlaybackContext": ["html5Preference": "HTML5_PREF_WANTS"]],
+ ]
+ }
+
+ private func client(lang: String, region: String, chosen: (name: String, version: String, id: String)? = nil) -> [String: Any] {
+ let picked = chosen ?? Self.clients[0]
+ return [
+ "clientName": picked.name,
+ "clientVersion": picked.version,
+ "hl": lang,
+ "gl": region,
+ "userAgent": "\(Self.userAgent),gzip(gfe)",
+ "platform": "DESKTOP",
+ ]
+ }
+
+ /// The visitor id YouTube handed this install, kept for a day; a request without one is bot-checked.
+ private func visitor(lang: String, region: String, done: @escaping (String) -> Void) {
+ let defaults = UserDefaults.standard
+ let age = Date().timeIntervalSince1970 - defaults.double(forKey: Self.visitorAgeKey)
+ if let cached = defaults.string(forKey: Self.visitorKey), !cached.isEmpty, age < Self.visitorTTL {
+ done(cached)
+ return
+ }
+ post(Self.visitorURL, ["context": ["client": client(lang: lang, region: region)]], client: Self.clients[0]) { [weak self] json in
+ let fresh = ((json?["responseContext"] as? [String: Any])?["visitorData"] as? String) ?? ""
+ if !fresh.isEmpty {
+ defaults.set(fresh, forKey: Self.visitorKey)
+ defaults.set(Date().timeIntervalSince1970, forKey: Self.visitorAgeKey)
+ }
+ done(fresh.isEmpty ? (defaults.string(forKey: Self.visitorKey) ?? "") : fresh)
+ _ = self
+ }
+ }
+
+ private func post(_ url: URL, _ body: [String: Any], client: (name: String, version: String, id: String), done: @escaping ([String: Any]?) -> Void) {
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.httpBody = try? JSONSerialization.data(withJSONObject: body)
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ request.setValue(client.id, forHTTPHeaderField: "X-YouTube-Client-Name")
+ request.setValue(client.version, forHTTPHeaderField: "X-YouTube-Client-Version")
+ request.setValue("2", forHTTPHeaderField: "X-Goog-Api-Format-Version")
+ request.setValue("https://www.youtube.com", forHTTPHeaderField: "Origin")
+ request.setValue(Self.userAgent, forHTTPHeaderField: "User-Agent")
+ URLSession(configuration: .ephemeral).downloadTask(with: request) { fileURL, _, error in
+ guard error == nil, let fileURL, let data = try? Data(contentsOf: fileURL) else {
+ done(nil)
+ return
+ }
+ done(try? JSONSerialization.jsonObject(with: data) as? [String: Any])
+ }.resume()
+ }
+
+ private static func int(_ value: Any?) -> Int {
+ if let n = value as? Int { return n }
+ if let s = value as? String { return Int(s) ?? 0 }
+ if let n = value as? NSNumber { return n.intValue }
+ return 0
+ }
+}
diff --git a/mobile/ios/App/App/SceneDelegate.swift b/mobile/ios/App/App/SceneDelegate.swift
new file mode 100644
index 0000000..2fc6624
--- /dev/null
+++ b/mobile/ios/App/App/SceneDelegate.swift
@@ -0,0 +1,24 @@
+import UIKit
+import Capacitor
+
+class SceneDelegate: UIResponder, UIWindowSceneDelegate {
+ var window: UIWindow?
+
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
+ guard let windowScene = scene as? UIWindowScene else { return }
+
+ window = UIWindow(windowScene: windowScene)
+ window?.rootViewController = MusikeWebViewController()
+ window?.makeKeyAndVisible()
+
+ SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
+ }
+
+ func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
+ SceneDelegateProxy.shared.scene(scene, openURLContexts: URLContexts)
+ }
+
+ func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
+ SceneDelegateProxy.shared.scene(scene, continue: userActivity)
+ }
+}
diff --git a/mobile/ios/App/CapApp-SPM/.gitignore b/mobile/ios/App/CapApp-SPM/.gitignore
new file mode 100644
index 0000000..3b29812
--- /dev/null
+++ b/mobile/ios/App/CapApp-SPM/.gitignore
@@ -0,0 +1,9 @@
+.DS_Store
+/.build
+/Packages
+/*.xcodeproj
+xcuserdata/
+DerivedData/
+.swiftpm/config/registries.json
+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
+.netrc
diff --git a/mobile/ios/App/CapApp-SPM/Package.swift b/mobile/ios/App/CapApp-SPM/Package.swift
new file mode 100644
index 0000000..e530bdc
--- /dev/null
+++ b/mobile/ios/App/CapApp-SPM/Package.swift
@@ -0,0 +1,33 @@
+// swift-tools-version: 5.9
+import PackageDescription
+
+// DO NOT MODIFY THIS FILE - managed by Capacitor CLI commands
+let package = Package(
+ name: "CapApp-SPM",
+ platforms: [.iOS(.v15)],
+ products: [
+ .library(
+ name: "CapApp-SPM",
+ targets: ["CapApp-SPM"])
+ ],
+ dependencies: [
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.5.3"),
+ .package(name: "CapacitorApp", path: "../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/app"),
+ .package(name: "CapacitorFilesystem", path: "../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/filesystem"),
+ .package(name: "CapacitorKeyboard", path: "../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/keyboard"),
+ .package(name: "CapacitorShare", path: "../../../../node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@capacitor/share")
+ ],
+ targets: [
+ .target(
+ name: "CapApp-SPM",
+ dependencies: [
+ .product(name: "Capacitor", package: "capacitor-swift-pm"),
+ .product(name: "Cordova", package: "capacitor-swift-pm"),
+ .product(name: "CapacitorApp", package: "CapacitorApp"),
+ .product(name: "CapacitorFilesystem", package: "CapacitorFilesystem"),
+ .product(name: "CapacitorKeyboard", package: "CapacitorKeyboard"),
+ .product(name: "CapacitorShare", package: "CapacitorShare")
+ ]
+ )
+ ]
+)
diff --git a/mobile/ios/App/CapApp-SPM/README.md b/mobile/ios/App/CapApp-SPM/README.md
new file mode 100644
index 0000000..03964db
--- /dev/null
+++ b/mobile/ios/App/CapApp-SPM/README.md
@@ -0,0 +1,5 @@
+# CapApp-SPM
+
+This package is used to host SPM dependencies for your Capacitor project
+
+Do not modify the contents of it or there may be unintended consequences.
diff --git a/mobile/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift b/mobile/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift
new file mode 100644
index 0000000..945afec
--- /dev/null
+++ b/mobile/ios/App/CapApp-SPM/Sources/CapApp-SPM/CapApp-SPM.swift
@@ -0,0 +1 @@
+public let isCapacitorApp = true
diff --git a/mobile/ios/debug.xcconfig b/mobile/ios/debug.xcconfig
new file mode 100644
index 0000000..53ce18d
--- /dev/null
+++ b/mobile/ios/debug.xcconfig
@@ -0,0 +1 @@
+CAPACITOR_DEBUG = true
diff --git a/mobile/package.json b/mobile/package.json
index 6fd4e4e..4a69e14 100644
--- a/mobile/package.json
+++ b/mobile/package.json
@@ -7,6 +7,7 @@
"scripts": {
"build": "pnpm --filter @musike/web build:native && cap sync android",
"apk": "pnpm run build && node scripts/build-apk.mjs",
+ "ipa": "node scripts/build-ipa.mjs",
"open": "cap open android"
},
"dependencies": {
@@ -14,6 +15,8 @@
"@capacitor/app": "8.1.2",
"@capacitor/core": "8.5.3",
"@capacitor/filesystem": "8.1.5",
+ "@capacitor/ios": "8.5.3",
+ "@capacitor/keyboard": "^8.0.6",
"@capacitor/share": "8.0.3"
},
"devDependencies": {
diff --git a/mobile/scripts/build-ipa.mjs b/mobile/scripts/build-ipa.mjs
new file mode 100644
index 0000000..481a33c
--- /dev/null
+++ b/mobile/scripts/build-ipa.mjs
@@ -0,0 +1,55 @@
+// Builds the iOS app as an unsigned .ipa and copies it to release/Musike-Setup-<version>-iOS-unsigned.ipa at the
+// repository root, next to the desktop and Android downloads.
+// Needs macOS with Xcode 15+ (xcodebuild). The .ipa is not signed on purpose: Sideloadly, AltStore, TrollStore and
+// friends sign it with the user's own certificate when installing.
+//
+// MUSIKE_SERVER_URL=https://musike.example.com builds the app against that Musike server instead of the backend
+// inside the app; the file is then named ...-iOS-server-unsigned.ipa.
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const { version } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
+const app = join(root, "ios", "App");
+const work = join(root, "ios", "build");
+const archive = join(work, "Musike.xcarchive");
+const staging = join(work, "ipa");
+
+const run = (cmd, args, cwd = app) => {
+ const r = spawnSync(cmd, args, { cwd, stdio: "inherit" });
+ if (r.status !== 0) process.exit(r.status ?? 1);
+};
+
+// The web app with the backend running inside the app, then the copy Capacitor makes of it for the Xcode project.
+run("pnpm", ["--filter", "@musike/web", "build:native"], join(root, ".."));
+run("pnpm", ["exec", "cap", "sync", "ios"]);
+run("xcodebuild", [
+ "-project", "App.xcodeproj",
+ "-scheme", "App",
+ "-configuration", "Release",
+ "-destination", "generic/platform=iOS",
+ "-archivePath", archive,
+ "archive",
+ "CODE_SIGNING_ALLOWED=NO",
+ "CODE_SIGNING_REQUIRED=NO",
+ "CODE_SIGN_IDENTITY=",
+]);
+
+// An .ipa is a zip with the app bundle inside Payload/.
+const bundle = join(archive, "Products", "Applications", "App.app");
+if (!existsSync(bundle)) {
+ console.error(`No app bundle at ${bundle}`);
+ process.exit(1);
+}
+rmSync(staging, { recursive: true, force: true });
+mkdirSync(join(staging, "Payload"), { recursive: true });
+run("cp", ["-R", bundle, join(staging, "Payload", "Musike.app")]);
+const kind = process.env.MUSIKE_SERVER_URL ? "server" : "app";
+const target = join(root, "..", "release", `Musike-Setup-${version}-iOS-${kind}-unsigned.ipa`);
+mkdirSync(dirname(target), { recursive: true });
+rmSync(target, { force: true });
+run("zip", ["-qry", target, "Payload"], staging);
+run("rm", ["-rf", staging]);
+console.log(`\n${target}`);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 36e5b77..9cd6676 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -40,6 +40,12 @@ importers:
'@capacitor/filesystem':
specifier: 8.1.5
version: 8.1.5(@capacitor/[email protected])
+ '@capacitor/ios':
+ specifier: 8.5.3
+ version: 8.5.3(@capacitor/[email protected])
+ '@capacitor/keyboard':
+ specifier: ^8.0.6
+ version: 8.0.6(@capacitor/[email protected])
'@capacitor/share':
specifier: 8.0.3
version: 8.0.3(@capacitor/[email protected])
@@ -681,6 +687,16 @@ packages:
peerDependencies:
'@capacitor/core': '>=8.0.0'
+ '@capacitor/[email protected]':
+ resolution: {integrity: sha512-HnnV92Jl8+3x0JUloXUMjFcUsQI8wHFVsKwkLn72DfRZXYGZW11tQbmNOWOnRTljaU18FdI1b9ipT09SzzPDNw==}
+ peerDependencies:
+ '@capacitor/core': ^8.5.0
+
+ '@capacitor/[email protected]':
+ resolution: {integrity: sha512-Bbe+9V0qaT6dzEFJEK7BUWR01l2+vZE8FM5ITF/WgKtx+G6eGZ6d5+YiSMRJBAK0VGjdO59v8yiQ10Doa5KyvQ==}
+ peerDependencies:
+ '@capacitor/core': '>=8.0.0'
+
'@capacitor/[email protected]':
resolution: {integrity: sha512-gnvZBV1NPu2B8vd1UKncR56G15ueHd0aZLqgDov++t3SmTBG9Q0VrAZ1VnHn5stxlmglVaTb4RwopMgbpLzroA==}
peerDependencies:
@@ -4453,6 +4469,14 @@ snapshots:
'@capacitor/core': 8.5.3
'@capacitor/synapse': 1.0.4
+ '@capacitor/[email protected](@capacitor/[email protected])':
+ dependencies:
+ '@capacitor/core': 8.5.3
+
+ '@capacitor/[email protected](@capacitor/[email protected])':
+ dependencies:
+ '@capacitor/core': 8.5.3
+
'@capacitor/[email protected](@capacitor/[email protected])':
dependencies:
'@capacitor/core': 8.5.3
diff --git a/web/src/components/Rail.tsx b/web/src/components/Rail.tsx
index 0d94059..21a3d35 100644
--- a/web/src/components/Rail.tsx
+++ b/web/src/components/Rail.tsx
@@ -104,7 +104,7 @@ export function Rail() {
return (
<aside className="island hidden w-[78px] shrink-0 md:flex wide:w-[256px]">
<div className="island-core flex w-full flex-col overflow-hidden">
- <div className="flex h-16 items-center justify-center wide:justify-start wide:px-4">
+ <div className="flex h-16 items-center justify-center wide:justify-start wide:px-4 [@media(max-height:540px)]:h-12">
<LogoMark className="size-8 text-accent-text wide:hidden" />
<span className="hidden wide:block">
<Logo />
@@ -120,7 +120,7 @@ export function Rail() {
title={t.nav[key]}
className={({ isActive }) =>
cn(
- "flex h-11 items-center justify-center gap-3 rounded-full transition-colors duration-200 wide:justify-start wide:px-4",
+ "flex h-11 items-center justify-center gap-3 rounded-full transition-colors duration-200 wide:justify-start wide:px-4 [@media(max-height:540px)]:h-9",
isActive ? "bg-surface-4 text-fg" : "text-fg-2 hover:bg-surface-3 hover:text-fg",
)
}
@@ -135,9 +135,9 @@ export function Rail() {
))}
</nav>
- <div className="mx-4 my-3 h-px bg-line" />
+ <div className="mx-4 my-3 h-px bg-line [@media(max-height:540px)]:my-1.5" />
- <div className="flex items-center justify-between px-4 pb-1">
+ <div className="flex items-center justify-between px-4 pb-1 [@media(max-height:540px)]:pb-0">
<span className="hidden text-xs font-medium text-fg-3 wide:block">{t.nav.yourCollection}</span>
<button
type="button"
@@ -150,7 +150,7 @@ export function Rail() {
</button>
</div>
- <div className="scroll-area flex flex-1 flex-col gap-0.5 overflow-y-auto px-2 pb-2">
+ <div className="scroll-area flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto px-2 pb-2">
<RailLink to={paths.favorites} label={t.nav.favorites} sub={t.common.tracks(favorites.length)}>
<span className="grid size-full place-items-center bg-accent-soft text-accent-text">
<HeartIcon size={20} weight="fill" />
diff --git a/web/src/lib/audio.ts b/web/src/lib/audio.ts
new file mode 100644
index 0000000..f574c92
--- /dev/null
+++ b/web/src/lib/audio.ts
@@ -0,0 +1,188 @@
+/**
+ * The audio element the player drives.
+ *
+ * On iOS it is not an `<audio>` at all: the web view's media stack gets cut off by YouTube a few hundred kilobytes
+ * into a track (the element pauses, silently, around fifteen seconds), so the app plays natively through the
+ * `musikeAudio` handler (ios/App/App/MusikeAudio.swift). This class keeps the slice of the HTMLMediaElement API the
+ * player uses — src, play, pause, currentTime, duration, volume, buffered and the events — backed by that player.
+ *
+ * Everywhere else it is the plain `<audio>` the app has always used.
+ */
+
+interface Bridge {
+ postMessage(message: unknown): void;
+}
+
+interface NativePayload {
+ position?: number;
+ duration?: number;
+ buffered?: number;
+ message?: string;
+}
+
+const nativeBridge = (globalThis as { webkit?: { messageHandlers?: { musikeAudio?: Bridge } } }).webkit?.messageHandlers
+ ?.musikeAudio;
+
+class Buffered {
+ constructor(private to: number) {}
+ get length() {
+ return this.to > 0 ? 1 : 0;
+ }
+ end(_index: number) {
+ return this.to;
+ }
+}
+
+class NativeAudio extends EventTarget {
+ // The player sets these; the native side only needs to know about them.
+ private _volume = 1;
+ private _muted = false;
+ private _src = "";
+ private _position = 0;
+ private _duration = NaN;
+ private _paused = true;
+ private _ended = false;
+ private _bufferedEnd = 0;
+
+ readyState = 0;
+ networkState = 0;
+ playbackRate = 1;
+ error: { code: number; message: string } | null = null;
+ preload = "auto";
+
+ constructor(private bridge: Bridge) {
+ super();
+ const host = globalThis as { __musikeAudioEvent?: (event: string, data: NativePayload) => void };
+ host.__musikeAudioEvent = (event, data) => this.fromNative(event, data ?? {});
+ }
+
+ get src() {
+ return this._src;
+ }
+
+ set src(value: string) {
+ this._src = value;
+ this._ended = false;
+ this.error = null;
+ this.readyState = 0;
+ this.bridge.postMessage({ cmd: "load", url: value });
+ }
+
+ get currentTime() {
+ return this._position;
+ }
+
+ set currentTime(value: number) {
+ this._position = value;
+ this.bridge.postMessage({ cmd: "seek", to: value });
+ }
+
+ get duration() {
+ return this._duration;
+ }
+
+ get paused() {
+ return this._paused;
+ }
+
+ get ended() {
+ return this._ended;
+ }
+
+ get volume() {
+ return this._volume;
+ }
+
+ set volume(value: number) {
+ this._volume = value;
+ this.bridge.postMessage({ cmd: "volume", value });
+ }
+
+ get muted() {
+ return this._muted;
+ }
+
+ set muted(value: boolean) {
+ this._muted = value;
+ this.bridge.postMessage({ cmd: "muted", value });
+ }
+
+ get buffered() {
+ return new Buffered(this._bufferedEnd);
+ }
+
+ getAttribute(name: string) {
+ return name === "src" ? this._src : null;
+ }
+
+ setAttribute(name: string, value: string) {
+ if (name === "src") this.src = value;
+ }
+
+ removeAttribute(name: string) {
+ if (name !== "src") return;
+ this._src = "";
+ this._position = 0;
+ this.bridge.postMessage({ cmd: "load", url: "" });
+ }
+
+ load() {
+ if (this._src) this.bridge.postMessage({ cmd: "load", url: this._src });
+ }
+
+ play() {
+ this._paused = false;
+ this.bridge.postMessage({ cmd: "play" });
+ return Promise.resolve();
+ }
+
+ pause() {
+ this._paused = true;
+ this.bridge.postMessage({ cmd: "pause" });
+ this.dispatchEvent(new Event("pause"));
+ }
+
+ private fromNative(event: string, data: NativePayload) {
+ switch (event) {
+ case "ready":
+ this._duration = data.duration ?? NaN;
+ this.readyState = 4;
+ this.dispatchEvent(new Event("loadedmetadata"));
+ this.dispatchEvent(new Event("durationchange"));
+ break;
+ case "time":
+ this._position = data.position ?? this._position;
+ if (data.duration && Number.isFinite(data.duration)) this._duration = data.duration;
+ this._bufferedEnd = data.buffered ?? this._bufferedEnd;
+ this.dispatchEvent(new Event("timeupdate"));
+ this.dispatchEvent(new Event("progress"));
+ break;
+ case "playing":
+ this._paused = false;
+ this.readyState = 4;
+ this.dispatchEvent(new Event("playing"));
+ break;
+ case "ended":
+ this._ended = true;
+ this._paused = true;
+ this.dispatchEvent(new Event("ended"));
+ break;
+ case "error":
+ this.error = { code: 4, message: data.message ?? "Playback failed" };
+ this.dispatchEvent(new Event("error"));
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+/** The audio element for this platform: native on iOS, a real `<audio>` everywhere else. */
+export function createAudio(): HTMLAudioElement {
+ if (!nativeBridge) {
+ const audio = new Audio();
+ audio.preload = "auto";
+ return audio;
+ }
+ return new NativeAudio(nativeBridge) as unknown as HTMLAudioElement;
+}
diff --git a/web/src/native/media.ts b/web/src/native/media.ts
index de9a8de..ffff57e 100644
--- a/web/src/native/media.ts
+++ b/web/src/native/media.ts
@@ -24,22 +24,60 @@ const Playback = registerPlugin<PlaybackPlugin>("MusikePlayback", {
web: () => ({ update: noop, addListener: async () => ({ remove: noop }) }),
});
+/**
+ * Bridge to the app's iOS side (ios/App/App/MusikePlayback.swift). iOS has no Capacitor plugin here: the web view's
+ * own message handler carries the now-playing info, and the lock screen's buttons come back as
+ * window.__musikeMediaAction(), the same actions the Android plugin sends.
+ */
+interface MessageBridge {
+ postMessage(message: unknown): void;
+}
+
+const iosBridge = (
+ globalThis as { webkit?: { messageHandlers?: { musikeMedia?: MessageBridge } } }
+).webkit?.messageHandlers?.musikeMedia;
+
// The system advances the position on its own while playing; only real changes need sending.
let last = { playing: false, position: 0, at: 0 };
-export const media: SystemMedia = {
+/** Whether this state is news to the system: a real change, not the clock moving. */
+function worthSending(playing: boolean, position: number): boolean {
+ const now = Date.now();
+ const expected = last.playing ? last.position + (now - last.at) / 1000 : last.position;
+ if (playing === last.playing && Math.abs(position - expected) < 2 && now - last.at < 15_000) return false;
+ last = { playing, position, at: now };
+ return true;
+}
+
+const androidMedia: SystemMedia = {
setTrack(track) {
last = { playing: last.playing, position: 0, at: Date.now() };
void Playback.update({ ...track, position: 0 });
},
setState({ playing, position, duration }) {
- const now = Date.now();
- const expected = last.playing ? last.position + (now - last.at) / 1000 : last.position;
- if (playing === last.playing && Math.abs(position - expected) < 2 && now - last.at < 15_000) return;
- last = { playing, position, at: now };
+ if (!worthSending(playing, position)) return;
void Playback.update({ playing, position, duration: Number.isFinite(duration) ? duration : 0 });
},
onAction(handler) {
void Playback.addListener("action", (e) => handler(e.action as Parameters<typeof handler>[0], e.position));
},
};
+
+const iosMedia: SystemMedia = {
+ setTrack(track) {
+ last = { playing: last.playing, position: 0, at: Date.now() };
+ iosBridge?.postMessage({ type: "track", ...track, position: 0 });
+ },
+ setState({ playing, position, duration }) {
+ if (!worthSending(playing, position)) return;
+ iosBridge?.postMessage({ type: "state", playing, position, duration: Number.isFinite(duration) ? duration : 0 });
+ },
+ onAction(handler) {
+ (globalThis as { __musikeMediaAction?: (action: string, position?: number) => void }).__musikeMediaAction = (
+ action,
+ position,
+ ) => handler(action as Parameters<typeof handler>[0], position);
+ },
+};
+
+export const media: SystemMedia = iosBridge ? iosMedia : androidMedia;
diff --git a/web/src/native/streams.ts b/web/src/native/streams.ts
index 99b49aa..9d4a43f 100644
--- a/web/src/native/streams.ts
+++ b/web/src/native/streams.ts
@@ -1,4 +1,8 @@
+import { Capacitor } from "@capacitor/core";
import { msg, tr } from "../../../server/src/i18n";
+import { config } from "./shims/config";
+import { nativeResolverAvailable, resolveNatively } from "./ytplayer";
+
import { text, withClient } from "../../../server/src/search";
import { getLang } from "../i18n";
import { ApiError } from "../lib/apiTypes";
@@ -12,12 +16,16 @@ import { ApiError } from "../lib/apiTypes";
* remotely (mobile/streaming.json in the repository) without shipping a new app.
*/
-const DEFAULT_CLIENTS = ["VISIONOS"];
+// iOS asks YouTube from Safari's side of the world: its "IOS" client hands out plain URLs, while VISIONOS now hits
+// "Sign in to confirm you're not a bot" there. Android keeps the client yt-dlp itself uses.
+const DEFAULT_CLIENTS = Capacitor.getPlatform() === "ios" ? ["IOS", "VISIONOS"] : ["VISIONOS"];
const REMOTE_CONFIG = "https://raw.githubusercontent.com/Ernani1234/musike/main/mobile/streaming.json";
const CLIENTS_KEY = "musike:stream-clients";
interface Resolved {
url: string;
+ mime: string;
+ size: number;
title: string;
duration: number;
expiresAt: number;
@@ -31,7 +39,9 @@ const validClients = (v: unknown): string[] | null =>
function storedClients(): string[] {
try {
- return validClients(JSON.parse(localStorage.getItem(CLIENTS_KEY) ?? "null")) ?? DEFAULT_CLIENTS;
+ const stored = validClients(JSON.parse(localStorage.getItem(CLIENTS_KEY) ?? "null")) ?? [];
+ // This platform's own clients come first: a list saved by an older build (or another platform) must not hide them.
+ return [...new Set([...DEFAULT_CLIENTS, ...stored])];
} catch {
return DEFAULT_CLIENTS;
}
@@ -45,8 +55,9 @@ async function refreshClients() {
const res = await fetch(REMOTE_CONFIG, { signal: AbortSignal.timeout(6000) });
const remote = validClients(((await res.json()) as { clients?: unknown }).clients);
if (!remote) return;
- clients = remote;
- localStorage.setItem(CLIENTS_KEY, JSON.stringify(remote));
+ const merged = [...new Set([...DEFAULT_CLIENTS, ...remote])];
+ clients = merged;
+ localStorage.setItem(CLIENTS_KEY, JSON.stringify(merged));
} catch {
// offline or no config yet: keep what we have
}
@@ -54,6 +65,27 @@ async function refreshClients() {
void refreshClients();
async function resolve(id: string): Promise<Resolved> {
+ if (nativeResolverAvailable()) {
+ try {
+ const r = await resolveNatively(id, getLang() === "pt-BR" ? "pt-BR" : "en", config.location);
+ if (!r.error && r.url) {
+ const expire = Number(new URL(r.url).searchParams.get("expire")) * 1000;
+ const resolved: Resolved = {
+ url: r.url,
+ mime: r.mime || "audio/mp4",
+ size: 0,
+ title: r.title,
+ duration: r.duration,
+ expiresAt: expire || Date.now() + 3 * 3600_000,
+ };
+ cache.set(id, resolved);
+ return resolved;
+ }
+ } catch (e) {
+ // fall through to the in-app clients below
+ }
+ }
+
let reason = "";
for (const client of clients) {
try {
@@ -74,6 +106,8 @@ async function resolve(id: string): Promise<Resolved> {
const expire = Number(new URL(best.url).searchParams.get("expire")) * 1000;
const resolved: Resolved = {
url: best.url,
+ mime: String(best.mime_type ?? "audio/mp4"),
+ size: Number(best.content_length ?? 0),
title: info.basic_info?.title ?? "",
duration: info.basic_info?.duration ?? 0,
expiresAt: expire || Date.now() + 3 * 3600_000,
diff --git a/web/src/native/ytplayer.ts b/web/src/native/ytplayer.ts
new file mode 100644
index 0000000..329a0b4
--- /dev/null
+++ b/web/src/native/ytplayer.ts
@@ -0,0 +1,57 @@
+import { Capacitor } from "@capacitor/core";
+
+/**
+ * Resolving tracks on iOS goes through the app's own network stack (ios/App/App/MusikeYouTube.swift): YouTube
+ * bot-checks the web view's requests, and only the native one gets a URL the phone can read to the end.
+ */
+interface ResolveResult {
+ url: string;
+ mime: string;
+ title: string;
+ duration: number;
+ error?: string;
+ code?: string;
+}
+
+interface MessageBridge {
+ postMessage(message: unknown): void;
+}
+
+const bridge = (
+ globalThis as { webkit?: { messageHandlers?: { musikeResolve?: MessageBridge } } }
+).webkit?.messageHandlers?.musikeResolve;
+
+export const nativeResolverAvailable = () => !!bridge && Capacitor.getPlatform() === "ios";
+
+const pending = new Map<number, (result: ResolveResult) => void>();
+let sequence = 0;
+
+(globalThis as { __musikeResolve?: (req: number, result: ResolveResult) => void }).__musikeResolve = (req, result) => {
+ const done = pending.get(req);
+ if (!done) return;
+ pending.delete(req);
+ done(result);
+};
+
+/** Asks the iOS side for a stream URL; rejects with the reason YouTube gave. */
+export function resolveNatively(videoId: string, lang: string, region: string): Promise<ResolveResult> {
+ return new Promise((resolve, reject) => {
+ if (!bridge) {
+ reject(new Error("musikeResolve bridge is missing"));
+ return;
+ }
+ const req = ++sequence;
+ // A track is downloaded before the player gets it, which on a slow connection can take a while.
+ const timer = setTimeout(() => {
+ pending.delete(req);
+ reject(new Error("YouTube took too long to answer."));
+ }, 120_000);
+ pending.set(req, (result) => {
+ clearTimeout(timer);
+ // The web view's media element can't read a file URL (the scheme handler only serves fetch/img), so the
+ // downloaded bytes become a blob and the player gets that.
+ resolve(result);
+ });
+ bridge.postMessage({ req, id: videoId, lang, region });
+ });
+}
diff --git a/web/src/player/player.ts b/web/src/player/player.ts
index a73057f..37ecbf4 100644
--- a/web/src/player/player.ts
+++ b/web/src/player/player.ts
@@ -1,6 +1,7 @@
import { create } from "zustand";
import { getT, useT } from "../i18n";
import { api, capabilities, explainStreamError, streamSource, systemMedia, type ApiError, type ErrorCode } from "../lib/api";
+import { createAudio } from "../lib/audio";
import { shuffled } from "../lib/format";
import type { Track } from "../lib/types";
import { useLibrary } from "../stores/library";
@@ -61,8 +62,8 @@ interface PlayerState {
}
// Media elements live outside React so playback survives any re-render or route change.
-const audio = new Audio();
-audio.preload = "auto";
+// On iOS this is the native player behind the same API (see lib/audio.ts).
+const audio = createAudio();
export const videoEl = document.createElement("video");
videoEl.playsInline = true;