Skip to content

Commit a3cb5b6

Browse files
committed
Add external media sources to the V2 uploader
Stock Photos, Tenor GIFs, and Image Playground as picker sheets that wrap the existing UIKit pickers, adapt their output to the module's external media model, and feed the M4 uploader. Wires the picker options into routing and adds the adapter and routing tests.
1 parent 50a28a1 commit a3cb5b6

7 files changed

Lines changed: 369 additions & 1 deletion

File tree

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import Testing
2+
import UniformTypeIdentifiers
3+
import WordPressData
4+
import WordPressMediaLibrary
5+
@testable import WordPress
6+
7+
@MainActor
8+
struct ExternalRemoteMediaAdapterTests {
9+
10+
@Test func stockPhotos_prefersAssetNameOverURLStem() {
11+
let asset = StubExternalMediaAsset(
12+
id: "1",
13+
name: "Sunset over the harbor",
14+
caption: "by Foo",
15+
largeURL: URL(string: "https://images.pexels.com/photos/1234/pexels-photo.jpg")!,
16+
thumbnailURL: URL(string: "https://example.com/thumb.jpg")!
17+
)
18+
let media = ExternalRemoteMedia(stockPhotosAsset: asset)
19+
#expect(media.suggestedName == "Sunset over the harbor")
20+
#expect(media.contentType == .jpeg)
21+
#expect(media.caption == "by Foo")
22+
}
23+
24+
@Test func stockPhotos_fallsBackToDefault_whenNameAndURLStemAreEmpty() {
25+
let asset = StubExternalMediaAsset(
26+
id: "p2",
27+
name: "",
28+
caption: "",
29+
largeURL: URL(string: "https://images.pexels.com/")!,
30+
thumbnailURL: URL(string: "https://example.com/")!
31+
)
32+
let media = ExternalRemoteMedia(stockPhotosAsset: asset)
33+
#expect(media.suggestedName == "External Media")
34+
}
35+
}
36+
37+
/// Simple test stub for `ExternalMediaAsset` (a V1 app-target protocol
38+
/// inheriting from `AnyObject` + `ExportableAsset` which is
39+
/// `NSObjectProtocol`). Lives in this test file only.
40+
private final class StubExternalMediaAsset: NSObject, ExternalMediaAsset {
41+
let id: String
42+
let name: String
43+
let caption: String
44+
let largeURL: URL
45+
let thumbnailURL: URL
46+
var assetMediaType: MediaType { .image }
47+
init(id: String, name: String, caption: String, largeURL: URL, thumbnailURL: URL) {
48+
self.id = id
49+
self.name = name
50+
self.caption = caption
51+
self.largeURL = largeURL
52+
self.thumbnailURL = thumbnailURL
53+
super.init()
54+
}
55+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import Testing
2+
import WordPressData
3+
import WordPressMediaLibrary
4+
@testable import WordPress
5+
6+
@MainActor
7+
struct MediaLibraryRoutingExternalSourcesTests {
8+
9+
@Test func dotComBlog_jetpackEnabled_offersStockPhotos() {
10+
let context = ContextManager.forTesting().mainContext
11+
let blog = ModelTestHelper.insertDotComBlog(context: context)
12+
// `blog.wordPressComRestApi` is non-nil only when the account has a
13+
// non-empty authToken (WPAccount+RestApi.swift:13-24). The default
14+
// fixture leaves authToken empty, so set one before asserting.
15+
blog.account?.authToken = "test-token"
16+
try? context.save()
17+
#expect(blog.wordPressComRestApi != nil)
18+
19+
// Stabilize the Jetpack-features gate. MediaPickerSource.freePhotos
20+
// resolves to `blog.supports(.stockPhotos) && jetpackFeaturesEnabled()`.
21+
// If `JetpackFeaturesRemovalCoordinator.currentAppUIType` is nil, the
22+
// removal-phase fallback can disable Jetpack features and silently
23+
// hide Stock Photos in this test. Save/restore the override
24+
// around the test so other suites aren't affected.
25+
let savedAppUIType = JetpackFeaturesRemovalCoordinator.currentAppUIType
26+
JetpackFeaturesRemovalCoordinator.currentAppUIType = .normal
27+
defer { JetpackFeaturesRemovalCoordinator.currentAppUIType = savedAppUIType }
28+
29+
let options = MediaLibraryRouting.externalPickerOptions(for: blog)
30+
let ids = options.map(\.id)
31+
#expect(ids.contains("stockPhotos"))
32+
}
33+
34+
@Test func selfHostedBlog_hidesStockPhotos() {
35+
let blog = ModelTestHelper.insertSelfHostedBlog(context: ContextManager.forTesting().mainContext)
36+
let options = MediaLibraryRouting.externalPickerOptions(for: blog)
37+
let ids = options.map(\.id)
38+
#expect(!ids.contains("stockPhotos")) // V1 parity: gated on .freePhotos
39+
}
40+
}

‎WordPress/Classes/ViewRelated/Media/MediaLibraryRouting.swift‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import SwiftUI
12
import UIKit
23
import WordPressCore
34
import WordPressData
@@ -40,7 +41,57 @@ enum MediaLibraryRouting {
4041
return MediaLibraryHostingController.make(
4142
client: client,
4243
tracker: tracker,
43-
uploader: uploader
44+
uploader: uploader,
45+
externalPickerOptions: externalPickerOptions(for: blog)
4446
)
4547
}
48+
49+
/// Internal helper so tests can assert the option array without UI introspection.
50+
/// Mirrors V1's effective gates from MediaPickerMenu+External.swift.
51+
static func externalPickerOptions(for blog: Blog) -> [ExternalMediaPickerOption] {
52+
var options: [ExternalMediaPickerOption] = []
53+
54+
if MediaPickerSource.freePhotos(blog: blog).isEnabled,
55+
let api = blog.wordPressComRestApi
56+
{
57+
options.append(
58+
.init(
59+
id: "stockPhotos",
60+
label: Strings.stockPhotos,
61+
systemImage: "photo.on.rectangle",
62+
sheetContent: { delegate in
63+
AnyView(StockPhotosPickerSheet(api: api, delegate: delegate))
64+
}
65+
)
66+
)
67+
}
68+
if MediaPickerSource.playground.isEnabled {
69+
if #available(iOS 18.1, *) {
70+
options.append(
71+
.init(
72+
id: "imagePlayground",
73+
label: Strings.imagePlayground,
74+
systemImage: "apple.image.playground",
75+
sheetContent: { delegate in
76+
AnyView(ImagePlaygroundPickerSheet(delegate: delegate))
77+
}
78+
)
79+
)
80+
}
81+
}
82+
return options
83+
}
84+
}
85+
86+
private enum Strings {
87+
static let stockPhotos = NSLocalizedString(
88+
"mediaLibrary.v2.addMenu.stockPhotos",
89+
value: "Free Photo Library",
90+
comment: "Add-menu item that opens the Stock Photos picker"
91+
)
92+
static let imagePlayground = NSLocalizedString(
93+
"mediaLibrary.v2.addMenu.imagePlayground",
94+
value: "Image Playground",
95+
comment: "Add-menu item that opens Apple's Image Playground"
96+
)
4697
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import SwiftUI
2+
import UIKit
3+
import WordPressMediaLibrary
4+
5+
/// SwiftUI wrapper around the V1 `ExternalMediaPickerViewController`, shared by
6+
/// every external source that vends `ExternalMediaAsset`s (Stock Photos).
7+
/// Per-source differences (data source, welcome view, title, asset mapping) are
8+
/// injected; the picker-to-delegate bridging is common to all of them.
9+
struct ExternalMediaPickerSheet: View {
10+
let title: String
11+
let source: MediaSource
12+
let makeDataSource: () -> ExternalMediaDataSource
13+
let makeWelcomeView: () -> UIView
14+
let mapAsset: (ExternalMediaAsset) -> ExternalRemoteMedia
15+
let delegate: any ExternalMediaPickerDelegate
16+
@Environment(\.dismiss) private var dismiss
17+
18+
var body: some View {
19+
ExternalMediaPickerVCRepresentable(
20+
title: title,
21+
mediaSource: source,
22+
makeDataSource: makeDataSource,
23+
makeWelcomeView: makeWelcomeView
24+
) { selection in
25+
// V1 picker uses a single didFinishWithSelection callback;
26+
// empty array = cancel, non-empty = done.
27+
if selection.isEmpty {
28+
delegate.didCancel()
29+
} else {
30+
delegate.didPick(remoteMedia: selection.map(mapAsset))
31+
}
32+
dismiss()
33+
}
34+
.ignoresSafeArea()
35+
}
36+
}
37+
38+
private struct ExternalMediaPickerVCRepresentable: UIViewControllerRepresentable {
39+
let title: String
40+
let mediaSource: MediaSource
41+
let makeDataSource: () -> ExternalMediaDataSource
42+
let makeWelcomeView: () -> UIView
43+
let onFinished: ([ExternalMediaAsset]) -> Void
44+
45+
func makeUIViewController(context: Context) -> UINavigationController {
46+
let picker = ExternalMediaPickerViewController(
47+
dataSource: makeDataSource(),
48+
source: mediaSource,
49+
allowsMultipleSelection: true
50+
)
51+
picker.title = title
52+
picker.welcomeView = makeWelcomeView()
53+
picker.delegate = context.coordinator
54+
return UINavigationController(rootViewController: picker)
55+
}
56+
57+
func updateUIViewController(_: UINavigationController, context: Context) {}
58+
59+
func makeCoordinator() -> Coordinator { Coordinator(onFinished: onFinished) }
60+
61+
final class Coordinator: NSObject, ExternalMediaPickerViewDelegate {
62+
let onFinished: ([ExternalMediaAsset]) -> Void
63+
init(onFinished: @escaping ([ExternalMediaAsset]) -> Void) {
64+
self.onFinished = onFinished
65+
}
66+
func externalMediaPickerViewController(
67+
_ viewController: ExternalMediaPickerViewController,
68+
didFinishWithSelection selection: [ExternalMediaAsset]
69+
) {
70+
// V1 callback runs on the main thread (it's a UIKit dismiss path).
71+
// assumeIsolated bridges into the @MainActor closure without an
72+
// async hop. Same pattern as MediaPickerController.swift:78-82.
73+
MainActor.assumeIsolated {
74+
onFinished(selection)
75+
}
76+
}
77+
}
78+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import Foundation
2+
import UniformTypeIdentifiers
3+
import WordPressMediaLibrary
4+
5+
extension ExternalRemoteMedia {
6+
/// Stock Photos: prefer the asset's title (Pexels names are descriptive
7+
/// and V1 preserves them via `MediaImageExporter(filename:)`). Falls back
8+
/// to URL basename, then to the localized "External Media" default.
9+
init(stockPhotosAsset asset: ExternalMediaAsset) {
10+
self.init(
11+
url: asset.largeURL,
12+
suggestedName: Self.normalizeStem(preferred: asset.name, fallback: asset.largeURL),
13+
contentType: .jpeg,
14+
caption: asset.caption.isEmpty ? nil : asset.caption
15+
)
16+
}
17+
18+
private static func normalizeStem(preferred: String, fallback: URL) -> String {
19+
let stem = sanitize(preferred)
20+
if !stem.isEmpty { return stem }
21+
let urlStem = sanitize(fallback.deletingPathExtension().lastPathComponent)
22+
if !urlStem.isEmpty { return urlStem }
23+
return Strings.defaultExternalMediaStem
24+
}
25+
26+
private static func sanitize(_ raw: String) -> String {
27+
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
28+
let stripped = (trimmed as NSString).deletingPathExtension
29+
// Treat input composed entirely of path separators as empty so the
30+
// caller falls through to the URL-basename / localized-default chain.
31+
let withoutSeparators = stripped.replacingOccurrences(of: "/", with: "")
32+
if withoutSeparators.isEmpty { return "" }
33+
return
34+
stripped
35+
.replacingOccurrences(of: "/", with: "_")
36+
.replacingOccurrences(of: "\0", with: "")
37+
}
38+
}
39+
40+
private enum Strings {
41+
static let defaultExternalMediaStem = NSLocalizedString(
42+
"mediaLibrary.v2.externalMedia.defaultStem",
43+
value: "External Media",
44+
comment: "Fallback filename stem when an external picker provides no usable name"
45+
)
46+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import SwiftUI
2+
import UIKit
3+
import WordPressMediaLibrary
4+
5+
#if canImport(ImagePlayground)
6+
import ImagePlayground
7+
8+
@available(iOS 18.1, *)
9+
struct ImagePlaygroundPickerSheet: View {
10+
let delegate: any ExternalMediaPickerDelegate
11+
@Environment(\.dismiss) private var dismiss
12+
13+
var body: some View {
14+
ImagePlaygroundVCRepresentable(
15+
onCreated: { url in
16+
let stem = url.deletingPathExtension().lastPathComponent
17+
delegate.didPick(imagePlaygroundFile: url, suggestedName: stem)
18+
dismiss()
19+
},
20+
onCancelled: {
21+
delegate.didCancel()
22+
dismiss()
23+
}
24+
)
25+
.ignoresSafeArea()
26+
}
27+
}
28+
29+
@available(iOS 18.1, *)
30+
private struct ImagePlaygroundVCRepresentable: UIViewControllerRepresentable {
31+
let onCreated: (URL) -> Void
32+
let onCancelled: () -> Void
33+
34+
func makeUIViewController(context: Context) -> UIViewController {
35+
let controller = ImagePlaygroundViewController()
36+
// SwiftUI retains the Coordinator via context.coordinator for the lifetime
37+
// of the representable, so the weak `delegate` on ImagePlaygroundViewController
38+
// stays alive without V1's objc_setAssociatedObject workaround.
39+
controller.delegate = context.coordinator
40+
return controller
41+
}
42+
43+
func updateUIViewController(_: UIViewController, context: Context) {}
44+
45+
func makeCoordinator() -> Coordinator {
46+
Coordinator(onCreated: onCreated, onCancelled: onCancelled)
47+
}
48+
49+
@available(iOS 18.1, *)
50+
final class Coordinator: NSObject, ImagePlaygroundViewController.Delegate {
51+
let onCreated: (URL) -> Void
52+
let onCancelled: () -> Void
53+
54+
init(onCreated: @escaping (URL) -> Void, onCancelled: @escaping () -> Void) {
55+
self.onCreated = onCreated
56+
self.onCancelled = onCancelled
57+
}
58+
59+
func imagePlaygroundViewController(
60+
_ viewController: ImagePlaygroundViewController,
61+
didCreateImageAt url: URL
62+
) {
63+
MainActor.assumeIsolated { onCreated(url) }
64+
}
65+
66+
func imagePlaygroundViewControllerDidCancel(_ viewController: ImagePlaygroundViewController) {
67+
MainActor.assumeIsolated { onCancelled() }
68+
}
69+
}
70+
}
71+
#endif
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import SwiftUI
2+
import WordPressKit // WordPressComRestApi lives here (see DefaultStockPhotosService.swift:1-20)
3+
import WordPressMediaLibrary
4+
5+
struct StockPhotosPickerSheet: View {
6+
let api: WordPressComRestApi
7+
let delegate: any ExternalMediaPickerDelegate
8+
9+
var body: some View {
10+
ExternalMediaPickerSheet(
11+
title: Strings.pickFromStockPhotos,
12+
source: .stockPhotos,
13+
makeDataSource: { StockPhotosDataSource(service: DefaultStockPhotosService(api: api)) },
14+
makeWelcomeView: { StockPhotosWelcomeView() },
15+
mapAsset: ExternalRemoteMedia.init(stockPhotosAsset:),
16+
delegate: delegate
17+
)
18+
}
19+
}
20+
21+
private enum Strings {
22+
static let pickFromStockPhotos = NSLocalizedString(
23+
"mediaLibrary.v2.stockPhotos.title",
24+
value: "Free Photo Library",
25+
comment: "Title of the Stock Photos picker (matches V1 MediaPickerMenu+External.swift)"
26+
)
27+
}

0 commit comments

Comments
 (0)