Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10f9f29314 | ||
|
|
46e8fac3aa | ||
|
|
7442b1c423 | ||
|
|
9d393a00de | ||
|
|
df3049e171 | ||
|
|
726509188a |
No files matched your search
@@ -14,6 +14,7 @@ on:
|
||||
- NotificationServiceExtension/**
|
||||
- ShareExtension/**
|
||||
- BroadcastUploadExtension/**
|
||||
- TalkWidgets/**
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
AACE32068D5BE4716C35504B /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 2C7F47AC20289B9600081CC7 /* Localizable.strings */; };
|
||||
07F8FEC44AC7B36560C5EE1B /* TalkWidgets.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
1F0ECBF52A68274400921E90 /* CDMarkdownKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1F0ECBF42A68274400921E90 /* CDMarkdownKit */; };
|
||||
1F0ECBF72A68277000921E90 /* CDMarkdownKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1F0ECBF62A68277000921E90 /* CDMarkdownKit */; };
|
||||
1F0ECBF92A68277C00921E90 /* CDMarkdownKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1F0ECBF82A68277C00921E90 /* CDMarkdownKit */; };
|
||||
@@ -160,6 +162,13 @@
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
B38B10737B74861948D4B46A /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 2C0574751EDD9E8E00D9E7F2 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 404DF6649BF5F70D4316B064;
|
||||
remoteInfo = TalkWidgets;
|
||||
};
|
||||
1F6D8C342B2E3756004376B8 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 2C0574751EDD9E8E00D9E7F2 /* Project object */;
|
||||
@@ -273,6 +282,7 @@
|
||||
dstSubfolderSpec = 13;
|
||||
files = (
|
||||
2C62AFAE24C08845007E460A /* ShareExtension.appex in Embed App Extensions */,
|
||||
07F8FEC44AC7B36560C5EE1B /* TalkWidgets.appex in Embed App Extensions */,
|
||||
2CC0015724A1F0E900A20167 /* NotificationServiceExtension.appex in Embed App Extensions */,
|
||||
1FF2FD722AB99CCB000C9905 /* BroadcastUploadExtension.appex in Embed App Extensions */,
|
||||
);
|
||||
@@ -282,6 +292,7 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = TalkWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
1F21A0622C77863500ED8C0C /* nb-NO */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "nb-NO"; path = "nb-NO.lproj/InfoPlist.strings"; sourceTree = "<group>"; };
|
||||
1F21A0632C77863500ED8C0C /* nb-NO */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "nb-NO"; path = "nb-NO.lproj/Localizable.strings"; sourceTree = "<group>"; };
|
||||
1F21A0642C77863500ED8C0C /* nb-NO */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = "nb-NO"; path = "nb-NO.lproj/Localizable.stringsdict"; sourceTree = "<group>"; };
|
||||
@@ -461,6 +472,20 @@
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
|
||||
8B65C957AD2D5B226E3E451F /* Exceptions for "TalkWidgets" folder in "NextcloudTalk" target */ = {
|
||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
||||
membershipExceptions = (
|
||||
ConversationsWidgetData.swift,
|
||||
);
|
||||
target = 2C05747C1EDD9E8E00D9E7F2 /* NextcloudTalk */;
|
||||
};
|
||||
AF55F227961AC70B32D0CA6E /* Exceptions for "TalkWidgets" folder in "TalkWidgets" target */ = {
|
||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
||||
membershipExceptions = (
|
||||
Info.plist,
|
||||
);
|
||||
target = 404DF6649BF5F70D4316B064 /* TalkWidgets */;
|
||||
};
|
||||
1F2058712CEBE4E200AAA673 /* Exceptions for "NotificationServiceExtension" folder in "NotificationServiceExtension" target */ = {
|
||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
||||
membershipExceptions = (
|
||||
@@ -978,6 +1003,15 @@
|
||||
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
|
||||
|
||||
/* Begin PBXFileSystemSynchronizedRootGroup section */
|
||||
276FE3D714359BBDDFCFD105 /* TalkWidgets */ = {
|
||||
isa = PBXFileSystemSynchronizedRootGroup;
|
||||
exceptions = (
|
||||
8B65C957AD2D5B226E3E451F /* Exceptions for "TalkWidgets" folder in "NextcloudTalk" target */,
|
||||
AF55F227961AC70B32D0CA6E /* Exceptions for "TalkWidgets" folder in "TalkWidgets" target */,
|
||||
);
|
||||
path = TalkWidgets;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
1F20586F2CEBE4E200AAA673 /* NotificationServiceExtension */ = {
|
||||
isa = PBXFileSystemSynchronizedRootGroup;
|
||||
exceptions = (
|
||||
@@ -1175,6 +1209,13 @@
|
||||
/* End PBXFileSystemSynchronizedRootGroup section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8BF89396AF80593D0F773E3 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
1F6D8C2D2B2E3756004376B8 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -1320,6 +1361,7 @@
|
||||
1F2058A32CEBE4EA00AAA673 /* BroadcastUploadExtension */,
|
||||
1F8977F52DB0F76100E8114D /* NextcloudTalkTests */,
|
||||
1FA93D9D2D70FCC200DF6CDF /* TalkIntents */,
|
||||
276FE3D714359BBDDFCFD105 /* TalkWidgets */,
|
||||
2C05747E1EDD9E8E00D9E7F2 /* Products */,
|
||||
2C05749C1EDDA01700D9E7F2 /* ThirdParty */,
|
||||
2C05747F1EDD9E8E00D9E7F2 /* NextcloudTalk */,
|
||||
@@ -1339,6 +1381,7 @@
|
||||
1FF2FD5B2AB99CCB000C9905 /* BroadcastUploadExtension.appex */,
|
||||
1F6D8C302B2E3756004376B8 /* NextcloudTalkTests.xctest */,
|
||||
1FA93D9C2D70FCC200DF6CDF /* TalkIntents.appex */,
|
||||
A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -1516,6 +1559,28 @@
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
404DF6649BF5F70D4316B064 /* TalkWidgets */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 9ABE05A230C005038CB734E7 /* Build configuration list for PBXNativeTarget "TalkWidgets" */;
|
||||
buildPhases = (
|
||||
7B48D333E0BB9346485C467C /* Sources */,
|
||||
C8BF89396AF80593D0F773E3 /* Frameworks */,
|
||||
E8B6BD717E91928AEB804805 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
fileSystemSynchronizedGroups = (
|
||||
276FE3D714359BBDDFCFD105 /* TalkWidgets */,
|
||||
);
|
||||
name = TalkWidgets;
|
||||
packageProductDependencies = (
|
||||
);
|
||||
productName = TalkWidgets;
|
||||
productReference = A06BE6676DC8072EFA0886DF /* TalkWidgets.appex */;
|
||||
productType = "com.apple.product-type.app-extension";
|
||||
};
|
||||
1F6D8C2F2B2E3756004376B8 /* NextcloudTalkTests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 1F6D8C362B2E3756004376B8 /* Build configuration list for PBXNativeTarget "NextcloudTalkTests" */;
|
||||
@@ -1664,6 +1729,7 @@
|
||||
2C62AFAD24C08845007E460A /* PBXTargetDependency */,
|
||||
1FF2FD712AB99CCB000C9905 /* PBXTargetDependency */,
|
||||
1FA93DA42D70FCC200DF6CDF /* PBXTargetDependency */,
|
||||
F9B0708653706C7E88EE41B0 /* PBXTargetDependency */,
|
||||
);
|
||||
fileSystemSynchronizedGroups = (
|
||||
1F2058832CEBE4E700AAA673 /* ShareExtension */,
|
||||
@@ -1803,6 +1869,9 @@
|
||||
LastUpgradeCheck = 1320;
|
||||
ORGANIZATIONNAME = "";
|
||||
TargetAttributes = {
|
||||
404DF6649BF5F70D4316B064 = {
|
||||
CreatedOnToolsVersion = 27.1;
|
||||
};
|
||||
1F6D8C2F2B2E3756004376B8 = {
|
||||
CreatedOnToolsVersion = 15.1;
|
||||
LastSwiftMigration = 1520;
|
||||
@@ -1921,11 +1990,20 @@
|
||||
1FD8AD892A3A162100787C16 /* NextcloudTalkUITests */,
|
||||
1F6D8C2F2B2E3756004376B8 /* NextcloudTalkTests */,
|
||||
1FA93D9B2D70FCC200DF6CDF /* TalkIntents */,
|
||||
404DF6649BF5F70D4316B064 /* TalkWidgets */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
E8B6BD717E91928AEB804805 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
AACE32068D5BE4716C35504B /* Localizable.strings in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
1F6D8C2E2B2E3756004376B8 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -2203,6 +2281,13 @@
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
7B48D333E0BB9346485C467C /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
1F6D8C2C2B2E3756004376B8 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -2294,6 +2379,11 @@
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
F9B0708653706C7E88EE41B0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 404DF6649BF5F70D4316B064 /* TalkWidgets */;
|
||||
targetProxy = B38B10737B74861948D4B46A /* PBXContainerItemProxy */;
|
||||
};
|
||||
1F6D8C352B2E3756004376B8 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 2C05747C1EDD9E8E00D9E7F2 /* NextcloudTalk */;
|
||||
@@ -2450,6 +2540,67 @@
|
||||
/* End PBXVariantGroup section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
90C606693565B566AE1CBA39 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = TalkWidgets/TalkWidgets.entitlements;
|
||||
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = NKUJUXUJ3B;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
INFOPLIST_FILE = TalkWidgets/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 25.0.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.nextcloud.Talk.TalkWidgets;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = APP_EXTENSION;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
9F99C4F4C1B607E85292FA51 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = TalkWidgets/TalkWidgets.entitlements;
|
||||
CODE_SIGN_IDENTITY = "iPhone Distribution: Nextcloud GmbH (NKUJUXUJ3B)";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = NKUJUXUJ3B;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
INFOPLIST_FILE = TalkWidgets/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 16.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 25.0.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.nextcloud.Talk.TalkWidgets;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = APP_EXTENSION;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
1F6D8C372B2E3756004376B8 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 342600BABD1AD1FCA48B5E59 /* Pods-NextcloudTalkTests.debug.xcconfig */;
|
||||
@@ -3291,6 +3442,15 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
9ABE05A230C005038CB734E7 /* Build configuration list for PBXNativeTarget "TalkWidgets" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
90C606693565B566AE1CBA39 /* Debug */,
|
||||
9F99C4F4C1B607E85292FA51 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
1F6D8C362B2E3756004376B8 /* Build configuration list for PBXNativeTarget "NextcloudTalkTests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
|
||||
@@ -75,6 +75,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {
|
||||
// Init rooms manager to start receiving NSNotificationCenter notifications
|
||||
_ = NCRoomsManager.shared
|
||||
|
||||
// Keep the widgets and the system search up to date with the conversations
|
||||
ConversationsWidgetController.shared.start()
|
||||
ConversationsSpotlightIndexer.shared.start()
|
||||
|
||||
self.registerBackgroundFetchTask()
|
||||
self.registerBackgroundProcessingTask()
|
||||
|
||||
@@ -95,6 +99,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {
|
||||
}
|
||||
|
||||
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
|
||||
// A conversation was selected in the system search (Spotlight)
|
||||
if let conversationURL = ConversationsSpotlightIndexer.conversationURL(for: userActivity) {
|
||||
NCUserInterfaceController.sharedInstance().presentChatForURL(conversationURL)
|
||||
return true
|
||||
}
|
||||
|
||||
let intent = userActivity.interaction?.intent
|
||||
let audioCallIntent = intent is INStartAudioCallIntent
|
||||
let videoCallIntent = intent is INStartVideoCallIntent
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
// Watches the thermal state and Low Power Mode during a call. Encoding and decoding video is
|
||||
// what heats up the device the most, so while it is hot or should save power, less video is used.
|
||||
class CallPerformanceMonitor {
|
||||
|
||||
enum Reason {
|
||||
case none
|
||||
case thermalState
|
||||
case lowPowerMode
|
||||
}
|
||||
|
||||
private(set) var maxVideoQuality: SimulcastVideoQuality = .high
|
||||
private(set) var reason: Reason = .none
|
||||
|
||||
// Called on the main thread, whenever the maximum video quality changed
|
||||
var onChange: ((_ maxVideoQuality: SimulcastVideoQuality, _ reason: Reason) -> Void)?
|
||||
|
||||
private let processInfo: ProcessInfo
|
||||
|
||||
init(processInfo: ProcessInfo = .processInfo) {
|
||||
self.processInfo = processInfo
|
||||
|
||||
self.update(notify: false)
|
||||
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(stateDidChange), name: ProcessInfo.thermalStateDidChangeNotification, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(stateDidChange), name: .NSProcessInfoPowerStateDidChange, object: nil)
|
||||
}
|
||||
|
||||
static func maxVideoQuality(thermalState: ProcessInfo.ThermalState, isLowPowerModeEnabled: Bool) -> (quality: SimulcastVideoQuality, reason: Reason) {
|
||||
switch thermalState {
|
||||
case .critical:
|
||||
return (.low, .thermalState)
|
||||
case .serious:
|
||||
return (.medium, .thermalState)
|
||||
default:
|
||||
return isLowPowerModeEnabled ? (.medium, .lowPowerMode) : (.high, .none)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func stateDidChange() {
|
||||
// The notifications are posted on an arbitrary thread
|
||||
DispatchQueue.main.async {
|
||||
self.update(notify: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func update(notify: Bool) {
|
||||
let (quality, reason) = Self.maxVideoQuality(thermalState: processInfo.thermalState, isLowPowerModeEnabled: processInfo.isLowPowerModeEnabled)
|
||||
|
||||
guard quality != self.maxVideoQuality || reason != self.reason else { return }
|
||||
|
||||
NCLog.log("Call video quality limited to \(quality) (thermal state: \(processInfo.thermalState.rawValue), low power mode: \(processInfo.isLowPowerModeEnabled))")
|
||||
|
||||
self.maxVideoQuality = quality
|
||||
self.reason = reason
|
||||
|
||||
if notify {
|
||||
self.onChange?(quality, reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import AVFoundation
|
||||
import SwiftUI
|
||||
|
||||
// A short check before joining a call: a camera preview, a microphone level meter and the audio output,
|
||||
// with the option to join with camera or microphone turned off.
|
||||
|
||||
struct CallPreflightResult: Equatable {
|
||||
let cameraEnabled: Bool
|
||||
let microphoneEnabled: Bool
|
||||
}
|
||||
|
||||
// Hands the choice from the check over to the call view controller, which is created later through CallKit
|
||||
enum CallPreflightPreferences {
|
||||
|
||||
private struct PendingResult {
|
||||
let token: String
|
||||
let result: CallPreflightResult
|
||||
let date: Date
|
||||
}
|
||||
|
||||
private static var pending: PendingResult?
|
||||
|
||||
static func store(_ result: CallPreflightResult, for token: String) {
|
||||
pending = PendingResult(token: token, result: result, date: Date())
|
||||
}
|
||||
|
||||
/// Returns the stored choice for the conversation once, if it was made in the last minute
|
||||
static func take(for token: String) -> CallPreflightResult? {
|
||||
guard let pending, pending.token == token, Date().timeIntervalSince(pending.date) < 60 else { return nil }
|
||||
|
||||
self.pending = nil
|
||||
return pending.result
|
||||
}
|
||||
}
|
||||
|
||||
class CallPreflightViewController: UIHostingController<CallPreflightView> {
|
||||
|
||||
init(room: NCRoom, withVideo video: Bool, completion: @escaping (CallPreflightResult?) -> Void) {
|
||||
let model = CallPreflightModel(cameraAvailable: video && room.canPublishVideo,
|
||||
microphoneAvailable: room.permissions.contains(.canPublishAudio))
|
||||
|
||||
var dismissHandler: ((CallPreflightResult?) -> Void)?
|
||||
let view = CallPreflightView(model: model, roomName: room.displayName) { result in
|
||||
dismissHandler?(result)
|
||||
}
|
||||
|
||||
super.init(rootView: view)
|
||||
|
||||
dismissHandler = { [weak self] result in
|
||||
model.stop()
|
||||
self?.dismiss(animated: true) {
|
||||
completion(result)
|
||||
}
|
||||
}
|
||||
|
||||
self.modalPresentationStyle = .formSheet
|
||||
self.sheetPresentationController?.detents = [.large()]
|
||||
self.sheetPresentationController?.prefersGrabberVisible = true
|
||||
// Swiping the sheet away is the same as cancelling
|
||||
self.presentationController?.delegate = self
|
||||
self.cancelHandler = {
|
||||
model.stop()
|
||||
completion(nil)
|
||||
}
|
||||
}
|
||||
|
||||
private var cancelHandler: (() -> Void)?
|
||||
|
||||
@MainActor required dynamic init?(coder aDecoder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
static func isNeeded(for room: NCRoom, withVideo video: Bool) -> Bool {
|
||||
guard NCUserDefaults.showCallPreflight() else { return false }
|
||||
|
||||
return (video && room.canPublishVideo) || room.permissions.contains(.canPublishAudio)
|
||||
}
|
||||
}
|
||||
|
||||
extension CallPreflightViewController: UIAdaptivePresentationControllerDelegate {
|
||||
|
||||
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
|
||||
self.cancelHandler?()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Model
|
||||
|
||||
@MainActor
|
||||
class CallPreflightModel: ObservableObject {
|
||||
|
||||
let cameraAvailable: Bool
|
||||
let microphoneAvailable: Bool
|
||||
|
||||
@Published var cameraEnabled: Bool {
|
||||
didSet { self.updateCamera() }
|
||||
}
|
||||
|
||||
@Published var microphoneEnabled: Bool {
|
||||
didSet { self.updateMicrophone() }
|
||||
}
|
||||
|
||||
@Published var cameraState: DeviceState = .starting
|
||||
@Published var microphoneState: DeviceState = .starting
|
||||
// 0...1
|
||||
@Published var microphoneLevel: Float = 0
|
||||
@Published var audioOutputName = ""
|
||||
|
||||
enum DeviceState {
|
||||
case starting, running, denied, unavailable
|
||||
}
|
||||
|
||||
let captureSession = AVCaptureSession()
|
||||
private let captureQueue = DispatchQueue(label: "com.nextcloud.Talk.CallPreflight")
|
||||
private var cameraConfigured = false
|
||||
private var recorder: AVAudioRecorder?
|
||||
private var meterTimer: Timer?
|
||||
private var stopped = false
|
||||
|
||||
init(cameraAvailable: Bool, microphoneAvailable: Bool) {
|
||||
self.cameraAvailable = cameraAvailable
|
||||
self.microphoneAvailable = microphoneAvailable
|
||||
self.cameraEnabled = cameraAvailable
|
||||
self.microphoneEnabled = microphoneAvailable
|
||||
}
|
||||
|
||||
func start() {
|
||||
self.updateCamera()
|
||||
self.updateMicrophone()
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard !stopped else { return }
|
||||
|
||||
stopped = true
|
||||
self.stopMicrophone()
|
||||
|
||||
let session = captureSession
|
||||
captureQueue.async {
|
||||
session.stopRunning()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Camera
|
||||
|
||||
private func updateCamera() {
|
||||
guard cameraAvailable, !stopped else { return }
|
||||
|
||||
guard cameraEnabled else {
|
||||
let session = captureSession
|
||||
captureQueue.async {
|
||||
session.stopRunning()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Task {
|
||||
guard await AVCaptureDevice.requestAccess(for: .video) else {
|
||||
self.cameraState = .denied
|
||||
return
|
||||
}
|
||||
|
||||
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front),
|
||||
let input = try? AVCaptureDeviceInput(device: device)
|
||||
else {
|
||||
self.cameraState = .unavailable
|
||||
return
|
||||
}
|
||||
|
||||
let session = captureSession
|
||||
let needsConfiguration = !cameraConfigured
|
||||
cameraConfigured = true
|
||||
|
||||
captureQueue.async {
|
||||
if needsConfiguration {
|
||||
session.beginConfiguration()
|
||||
session.sessionPreset = .medium
|
||||
|
||||
if session.canAddInput(input) {
|
||||
session.addInput(input)
|
||||
}
|
||||
|
||||
session.commitConfiguration()
|
||||
}
|
||||
|
||||
session.startRunning()
|
||||
}
|
||||
|
||||
self.cameraState = .running
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Microphone
|
||||
|
||||
private func updateMicrophone() {
|
||||
guard microphoneAvailable, !stopped else { return }
|
||||
|
||||
guard microphoneEnabled else {
|
||||
self.stopMicrophone()
|
||||
return
|
||||
}
|
||||
|
||||
Task {
|
||||
guard await AVCaptureDevice.requestAccess(for: .audio) else {
|
||||
self.microphoneState = .denied
|
||||
return
|
||||
}
|
||||
|
||||
self.startMicrophone()
|
||||
}
|
||||
}
|
||||
|
||||
private func startMicrophone() {
|
||||
guard recorder == nil, !stopped, microphoneEnabled else { return }
|
||||
|
||||
let audioSession = AVAudioSession.sharedInstance()
|
||||
|
||||
do {
|
||||
try audioSession.setCategory(.playAndRecord, mode: .videoChat, options: [.allowBluetoothHFP, .defaultToSpeaker])
|
||||
try audioSession.setActive(true)
|
||||
|
||||
// The recording is only used for the level meter and deleted right away
|
||||
let url = FileManager.default.temporaryDirectory.appendingPathComponent("call-preflight.m4a")
|
||||
let recorder = try AVAudioRecorder(url: url, settings: [
|
||||
AVFormatIDKey: kAudioFormatMPEG4AAC,
|
||||
AVSampleRateKey: 12000,
|
||||
AVNumberOfChannelsKey: 1
|
||||
])
|
||||
|
||||
recorder.isMeteringEnabled = true
|
||||
recorder.record()
|
||||
self.recorder = recorder
|
||||
self.microphoneState = .running
|
||||
} catch {
|
||||
NCLog.log("Could not start microphone check: \(error.localizedDescription)")
|
||||
self.microphoneState = .unavailable
|
||||
return
|
||||
}
|
||||
|
||||
self.updateAudioOutputName()
|
||||
|
||||
meterTimer = Timer.scheduledTimer(withTimeInterval: 0.08, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in
|
||||
guard let self, let recorder = self.recorder else { return }
|
||||
|
||||
recorder.updateMeters()
|
||||
self.microphoneLevel = CallPreflightModel.normalizedLevel(fromDecibels: recorder.averagePower(forChannel: 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func stopMicrophone() {
|
||||
meterTimer?.invalidate()
|
||||
meterTimer = nil
|
||||
microphoneLevel = 0
|
||||
|
||||
guard let recorder else { return }
|
||||
|
||||
recorder.stop()
|
||||
recorder.deleteRecording()
|
||||
self.recorder = nil
|
||||
|
||||
// Let CallKit take over the audio session again
|
||||
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
|
||||
}
|
||||
|
||||
private func updateAudioOutputName() {
|
||||
let output = AVAudioSession.sharedInstance().currentRoute.outputs.first
|
||||
self.audioOutputName = output?.portName ?? ""
|
||||
}
|
||||
|
||||
/// Maps the average power in decibels (-160...0) to 0...1, where everything below -50 dB counts as silence
|
||||
nonisolated static func normalizedLevel(fromDecibels decibels: Float) -> Float {
|
||||
guard decibels.isFinite else { return 0 }
|
||||
|
||||
return min(1, max(0, (decibels + 50) / 50))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Views
|
||||
|
||||
struct CallPreflightView: View {
|
||||
|
||||
@ObservedObject var model: CallPreflightModel
|
||||
let roomName: String
|
||||
let onFinish: (CallPreflightResult?) -> Void
|
||||
|
||||
@State private var showBeforeEveryCall = NCUserDefaults.showCallPreflight()
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 20) {
|
||||
VStack(spacing: 4) {
|
||||
Text(NSLocalizedString("Ready to join?", comment: "Title of the check before joining a call"))
|
||||
.font(.title2.bold())
|
||||
Text(roomName)
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.secondary)
|
||||
.lineLimit(1)
|
||||
}
|
||||
.padding(.top, 24)
|
||||
|
||||
if model.cameraAvailable {
|
||||
CameraPreview(model: model)
|
||||
.frame(maxWidth: 360)
|
||||
.aspectRatio(3 / 4, contentMode: .fit)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
|
||||
}
|
||||
|
||||
HStack(spacing: 24) {
|
||||
if model.microphoneAvailable {
|
||||
PreflightToggleButton(isOn: $model.microphoneEnabled,
|
||||
onImage: "mic.fill", offImage: "mic.slash.fill",
|
||||
label: NSLocalizedString("Microphone", comment: ""))
|
||||
}
|
||||
|
||||
if model.cameraAvailable {
|
||||
PreflightToggleButton(isOn: $model.cameraEnabled,
|
||||
onImage: "video.fill", offImage: "video.slash.fill",
|
||||
label: NSLocalizedString("Camera", comment: ""))
|
||||
}
|
||||
}
|
||||
|
||||
if model.microphoneAvailable {
|
||||
MicrophoneCheck(model: model)
|
||||
}
|
||||
|
||||
if !model.audioOutputName.isEmpty {
|
||||
Label(model.audioOutputName, systemImage: "speaker.wave.2.fill")
|
||||
.font(.footnote)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
Toggle(NSLocalizedString("Show this check before every call", comment: ""), isOn: $showBeforeEveryCall)
|
||||
.font(.footnote)
|
||||
.padding(.horizontal)
|
||||
.onChange(of: showBeforeEveryCall) { newValue in
|
||||
NCUserDefaults.setShowCallPreflight(newValue)
|
||||
}
|
||||
|
||||
VStack(spacing: 12) {
|
||||
Button {
|
||||
HapticFeedback.light()
|
||||
onFinish(CallPreflightResult(cameraEnabled: model.cameraAvailable && model.cameraEnabled,
|
||||
microphoneEnabled: model.microphoneAvailable && model.microphoneEnabled))
|
||||
} label: {
|
||||
Text(NSLocalizedString("Join call", comment: ""))
|
||||
.bold()
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(Color(NCAppBranding.elementColor()))
|
||||
.controlSize(.large)
|
||||
|
||||
Button(NSLocalizedString("Cancel", comment: "")) {
|
||||
onFinish(nil)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal)
|
||||
}
|
||||
.padding()
|
||||
.frame(maxWidth: 500)
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.onAppear {
|
||||
model.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct PreflightToggleButton: View {
|
||||
|
||||
@Binding var isOn: Bool
|
||||
let onImage: String
|
||||
let offImage: String
|
||||
let label: String
|
||||
|
||||
var body: some View {
|
||||
Button {
|
||||
HapticFeedback.selection()
|
||||
isOn.toggle()
|
||||
} label: {
|
||||
Image(systemName: isOn ? onImage : offImage)
|
||||
.font(.title2)
|
||||
.foregroundColor(isOn ? .primary : .white)
|
||||
.frame(width: 60, height: 60)
|
||||
.background(Circle().fill(isOn ? Color(UIColor.secondarySystemFill) : Color.red))
|
||||
}
|
||||
.accessibilityLabel(label)
|
||||
.accessibilityValue(isOn ? NSLocalizedString("On", comment: "") : NSLocalizedString("Off", comment: ""))
|
||||
}
|
||||
}
|
||||
|
||||
private struct MicrophoneCheck: View {
|
||||
|
||||
@ObservedObject var model: CallPreflightModel
|
||||
|
||||
private let barCount = 16
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 8) {
|
||||
switch model.microphoneState {
|
||||
case .denied:
|
||||
Text(NSLocalizedString("Microphone access is not allowed", comment: ""))
|
||||
.font(.footnote)
|
||||
.foregroundColor(.secondary)
|
||||
case .unavailable:
|
||||
Text(NSLocalizedString("No microphone available", comment: ""))
|
||||
.font(.footnote)
|
||||
.foregroundColor(.secondary)
|
||||
default:
|
||||
HStack(spacing: 3) {
|
||||
ForEach(0..<barCount, id: \.self) { index in
|
||||
Capsule()
|
||||
.fill(isLit(index) ? Color.green : Color(UIColor.systemGray4))
|
||||
.frame(width: 6, height: 18)
|
||||
}
|
||||
}
|
||||
.animation(.easeOut(duration: 0.08), value: model.microphoneLevel)
|
||||
.accessibilityHidden(true)
|
||||
|
||||
Text(model.microphoneEnabled ?
|
||||
NSLocalizedString("Say something to test your microphone", comment: "") :
|
||||
NSLocalizedString("You will join muted", comment: "Shown before joining a call with the microphone turned off"))
|
||||
.font(.footnote)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func isLit(_ index: Int) -> Bool {
|
||||
return model.microphoneEnabled && Float(index) < model.microphoneLevel * Float(barCount)
|
||||
}
|
||||
}
|
||||
|
||||
private struct CameraPreview: View {
|
||||
|
||||
@ObservedObject var model: CallPreflightModel
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Color(UIColor.secondarySystemBackground)
|
||||
|
||||
if model.cameraEnabled, model.cameraState == .running {
|
||||
CaptureVideoPreview(session: model.captureSession)
|
||||
} else {
|
||||
VStack(spacing: 8) {
|
||||
Image(systemName: "video.slash.fill")
|
||||
.font(.largeTitle)
|
||||
Text(placeholderText)
|
||||
.font(.footnote)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.foregroundColor(.secondary)
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var placeholderText: String {
|
||||
switch model.cameraState {
|
||||
case .denied:
|
||||
return NSLocalizedString("Camera access is not allowed", comment: "")
|
||||
case .unavailable:
|
||||
return NSLocalizedString("No camera available", comment: "")
|
||||
default:
|
||||
return NSLocalizedString("You will join with the camera turned off", comment: "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct CaptureVideoPreview: UIViewRepresentable {
|
||||
|
||||
let session: AVCaptureSession
|
||||
|
||||
class PreviewView: UIView {
|
||||
override class var layerClass: AnyClass {
|
||||
return AVCaptureVideoPreviewLayer.self
|
||||
}
|
||||
|
||||
var previewLayer: AVCaptureVideoPreviewLayer {
|
||||
// swiftlint:disable:next force_cast
|
||||
return layer as! AVCaptureVideoPreviewLayer
|
||||
}
|
||||
}
|
||||
|
||||
func makeUIView(context: Context) -> PreviewView {
|
||||
let view = PreviewView()
|
||||
view.previewLayer.session = session
|
||||
view.previewLayer.videoGravity = .resizeAspectFill
|
||||
return view
|
||||
}
|
||||
|
||||
func updateUIView(_ uiView: PreviewView, context: Context) {}
|
||||
}
|
||||
@@ -157,6 +157,8 @@ class CallViewController: UIViewController,
|
||||
private var showChatAfterRoomSwitch = false
|
||||
private var connectingSoundAlreadyPlayed = false
|
||||
private var buttonFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
|
||||
private let performanceMonitor = CallPerformanceMonitor()
|
||||
private var hasShownReducedVideoQualityNotice = false
|
||||
private var localVideoDragStartingPoint: CGPoint?
|
||||
private var airplayView = AVRoutePickerView(frame: .init(x: 0, y: 0, width: 48, height: 32))
|
||||
private var pendingPeerInserts: [NCPeerConnection] = []
|
||||
@@ -206,6 +208,8 @@ class CallViewController: UIViewController,
|
||||
let callController = NCCallController(delegate: self, room: self.room, account: self.account, isAudioOnly: self.isAudioOnly, userSessionId: sessionId, voiceChatMode: self.voiceChatModeAtStart)
|
||||
self.callController = callController
|
||||
|
||||
callController.setMaxSendVideoQuality(self.performanceMonitor.maxVideoQuality)
|
||||
|
||||
callController.disableAudioAtStart = self.audioDisabledAtStart
|
||||
callController.disableVideoAtStart = self.videoDisabledAtStart
|
||||
callController.silentCall = self.silentCall
|
||||
@@ -227,6 +231,10 @@ class CallViewController: UIViewController,
|
||||
|
||||
self.setCallState(.joining)
|
||||
|
||||
self.performanceMonitor.onChange = { [weak self] maxVideoQuality, reason in
|
||||
self?.performanceLimitsDidChange(maxVideoQuality: maxVideoQuality, reason: reason)
|
||||
}
|
||||
|
||||
self.tapGestureForDetailedView = UITapGestureRecognizer(target: self, action: #selector(showDetailedViewWithTimer))
|
||||
self.tapGestureForDetailedView?.numberOfTapsRequired = 1
|
||||
|
||||
@@ -870,12 +878,38 @@ class CallViewController: UIViewController,
|
||||
return .low
|
||||
}
|
||||
|
||||
var quality: SimulcastVideoQuality
|
||||
|
||||
if callViewMode == .speaker {
|
||||
return peer.peerIdentifier == promotedPeerIdentifier ? .high : .low
|
||||
quality = peer.peerIdentifier == promotedPeerIdentifier ? .high : .low
|
||||
} else {
|
||||
// Unlike web, a single participant is shown fullscreen in the grid
|
||||
quality = peersInCall.count == 1 ? .high : .medium
|
||||
}
|
||||
|
||||
// Unlike web, a single participant is shown fullscreen in the grid
|
||||
return peersInCall.count == 1 ? .high : .medium
|
||||
// Decoding less video keeps the device cooler
|
||||
let maxVideoQuality = performanceMonitor.maxVideoQuality
|
||||
|
||||
return quality.rawValue > maxVideoQuality.rawValue ? maxVideoQuality : quality
|
||||
}
|
||||
|
||||
private func performanceLimitsDidChange(maxVideoQuality: SimulcastVideoQuality, reason: CallPerformanceMonitor.Reason) {
|
||||
self.callController?.setMaxSendVideoQuality(maxVideoQuality)
|
||||
self.updateSimulcastVideoQualities()
|
||||
|
||||
// Let the user know once per call, why the video looks worse than before
|
||||
guard maxVideoQuality != .high, !self.isAudioOnly, !self.hasShownReducedVideoQualityNotice else { return }
|
||||
|
||||
self.hasShownReducedVideoQualityNotice = true
|
||||
|
||||
let notificationText = switch reason {
|
||||
case .lowPowerMode:
|
||||
NSLocalizedString("Video quality was reduced to save battery", comment: "Shown in a call when Low Power Mode is enabled")
|
||||
default:
|
||||
NSLocalizedString("Video quality was reduced to cool down your device", comment: "Shown in a call when the device gets hot")
|
||||
}
|
||||
|
||||
NotificationPresenter.shared().present(text: notificationText, dismissAfterDelay: 5.0, includedStyle: .dark)
|
||||
}
|
||||
|
||||
private func updateSimulcastVideoQualities() {
|
||||
@@ -2141,6 +2175,7 @@ class CallViewController: UIViewController,
|
||||
|
||||
for reaction in callReactions {
|
||||
reactionItems.append(UIAction(title: String(reaction), handler: { [unowned self] _ in
|
||||
HapticFeedback.light()
|
||||
self.callController?.sendReaction(reaction)
|
||||
|
||||
if let account = room.account {
|
||||
@@ -2264,6 +2299,7 @@ class CallViewController: UIViewController,
|
||||
}
|
||||
|
||||
items.append(UIAction(title: raiseHandTitle, image: .init(systemName: "hand.raised.fill"), handler: { [unowned self] _ in
|
||||
HapticFeedback.light()
|
||||
callController.raiseHand(!self.isHandRaised)
|
||||
self.isHandRaised = !self.isHandRaised
|
||||
self.adjustBars()
|
||||
@@ -2313,6 +2349,14 @@ class CallViewController: UIViewController,
|
||||
}))
|
||||
}
|
||||
|
||||
// The microphone mode (Standard, Voice Isolation, Wide Spectrum) can only be changed in the system UI
|
||||
let microphoneModeTitle = String(format: NSLocalizedString("Microphone mode: %@", comment: "Microphone mode: Voice Isolation"),
|
||||
self.microphoneModeName(AVCaptureDevice.activeMicrophoneMode))
|
||||
|
||||
items.append(UIAction(title: microphoneModeTitle, image: .init(systemName: "waveform.and.mic"), handler: { _ in
|
||||
AVCaptureDevice.showSystemUserInterface(.microphoneModes)
|
||||
}))
|
||||
|
||||
if NCUtils.isTestEnvironment {
|
||||
items.append(self.getDebugMenu())
|
||||
}
|
||||
@@ -2320,6 +2364,17 @@ class CallViewController: UIViewController,
|
||||
return items
|
||||
}
|
||||
|
||||
private func microphoneModeName(_ microphoneMode: AVCaptureDevice.MicrophoneMode) -> String {
|
||||
switch microphoneMode {
|
||||
case .voiceIsolation:
|
||||
return NSLocalizedString("Voice Isolation", comment: "Microphone mode that filters out background noise")
|
||||
case .wideSpectrum:
|
||||
return NSLocalizedString("Wide Spectrum", comment: "Microphone mode that picks up all sounds around")
|
||||
default:
|
||||
return NSLocalizedString("Standard", comment: "Default microphone mode")
|
||||
}
|
||||
}
|
||||
|
||||
func adjustSpeakerButton() {
|
||||
DispatchQueue.main.async {
|
||||
guard self.speakerButton != nil else { return }
|
||||
@@ -2496,6 +2551,8 @@ class CallViewController: UIViewController,
|
||||
@IBAction func audioButtonPressed(_ sender: Any) {
|
||||
guard let callController else { return }
|
||||
|
||||
HapticFeedback.light()
|
||||
|
||||
callController.getAudioEnabledState { isEnabled in
|
||||
if CallKitManager.isCallKitAvailable() {
|
||||
DispatchQueue.main.async {
|
||||
@@ -2583,6 +2640,8 @@ class CallViewController: UIViewController,
|
||||
@IBAction func videoButtonPressed(_ sender: Any) {
|
||||
guard let callController else { return }
|
||||
|
||||
HapticFeedback.light()
|
||||
|
||||
callController.getVideoEnabledState { isEnabled in
|
||||
self.setLocalVideoEnabled(!isEnabled)
|
||||
self.userDisabledVideo = isEnabled
|
||||
@@ -2682,6 +2741,7 @@ class CallViewController: UIViewController,
|
||||
}
|
||||
|
||||
@IBAction func hangupButtonPressed(_ sender: Any) {
|
||||
HapticFeedback.medium()
|
||||
self.hangup(forAll: (room.type == .oneToOne))
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,8 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
|
||||
private var connectionsDict = [PeerKey: NCPeerConnection]()
|
||||
private var pendingOffersDict = [PeerKey: Timer]()
|
||||
private var simulcastVideoQualities = [SessionId: SimulcastVideoQuality]()
|
||||
// Lowered while the device is hot or in Low Power Mode, see CallPerformanceMonitor
|
||||
private var maxSendVideoQuality: SimulcastVideoQuality = .high
|
||||
private var remoteVideoBlocked = [SessionId: Bool]()
|
||||
|
||||
private var sessionsInCall = [String]()
|
||||
@@ -1127,6 +1129,7 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
|
||||
peerConnectionWrapper?.delegate = self
|
||||
peerConnectionWrapper?.isOwnScreensharePeer = ownScreenshare
|
||||
peerConnectionWrapper?.preferredVideoCodec = self.preferredVideoCodec
|
||||
peerConnectionWrapper?.maxSendVideoQuality = self.maxSendVideoQuality
|
||||
peerConnectionWrapper?.receiverKeyRing = self.callEncryption?.keyRing(forSessionId: sessionId)
|
||||
|
||||
// Try to get displayName early
|
||||
@@ -1214,6 +1217,19 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
|
||||
}
|
||||
}
|
||||
|
||||
func setMaxSendVideoQuality(_ quality: SimulcastVideoQuality) {
|
||||
WebRTCCommon.shared.dispatch {
|
||||
guard quality != self.maxSendVideoQuality else { return }
|
||||
|
||||
self.maxSendVideoQuality = quality
|
||||
|
||||
for (_, peerConnectionWrapper) in self.connectionsDict {
|
||||
peerConnectionWrapper.maxSendVideoQuality = quality
|
||||
peerConnectionWrapper.applyMaxSendVideoQuality()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Blocking the video in the MCU while it is not shown saves bandwidth, same as web
|
||||
func setRemoteVideoBlocked(_ blocked: Bool, forPeerId peerId: String) {
|
||||
WebRTCCommon.shared.dispatch {
|
||||
@@ -1319,6 +1335,7 @@ internal class NCCallController: NSObject, NCPeerConnectionDelegate, NCSignaling
|
||||
peerConnectionWrapper.roomType = kRoomTypeVideo
|
||||
peerConnectionWrapper.delegate = self
|
||||
peerConnectionWrapper.preferredVideoCodec = self.preferredVideoCodec
|
||||
peerConnectionWrapper.maxSendVideoQuality = self.maxSendVideoQuality
|
||||
|
||||
self.publisherPeerConnection = peerConnectionWrapper
|
||||
|
||||
|
||||
@@ -825,12 +825,14 @@ import Toast
|
||||
|
||||
try await NCAPIController.sharedInstance().scheduleMessage(temporaryMessage.sendingMessage, inRoom: self.room.token, sendAt: timestamp, replyTo: replyToMessage?.messageId, silent: silently, threadId: self.thread?.threadId, forAccount: self.account)
|
||||
NotificationPresenter.shared().present(text: NSLocalizedString("Message successfully scheduled", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
|
||||
HapticFeedback.success()
|
||||
|
||||
self.clearInputAfterSend()
|
||||
NCRoomsManager.shared.updateRoom(self.room.token, forAccount: self.account)
|
||||
} catch {
|
||||
print(error)
|
||||
NotificationPresenter.shared().present(text: NSLocalizedString("Message scheduling failed", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
|
||||
HapticFeedback.error()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -862,6 +864,7 @@ import Toast
|
||||
|
||||
switch button.tag {
|
||||
case sendButtonTagMessage:
|
||||
HapticFeedback.light()
|
||||
self.sendCurrentMessage(silently: false)
|
||||
super.didPressRightButton(sender)
|
||||
case sendButtonTagVoice:
|
||||
@@ -1433,6 +1436,7 @@ import Toast
|
||||
let pasteboard = UIPasteboard.general
|
||||
pasteboard.string = message.parsedMessage().string
|
||||
NotificationPresenter.shared().present(text: NSLocalizedString("Message copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
|
||||
HapticFeedback.success()
|
||||
}
|
||||
|
||||
func didPressCopyLink(for message: NCChatMessage) {
|
||||
@@ -1445,6 +1449,7 @@ import Toast
|
||||
pasteboard.string = url
|
||||
|
||||
NotificationPresenter.shared().present(text: NSLocalizedString("Message link copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
|
||||
HapticFeedback.success()
|
||||
}
|
||||
|
||||
func didPressCopySelection(for message: NCChatMessage) {
|
||||
@@ -1634,6 +1639,7 @@ import Toast
|
||||
|
||||
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
|
||||
if textField == self.emojiTextField, string.isSingleEmoji, let interactingMessage = self.interactingMessage {
|
||||
HapticFeedback.light()
|
||||
self.addReaction(reaction: string, to: interactingMessage)
|
||||
textField.resignFirstResponder()
|
||||
}
|
||||
@@ -2612,6 +2618,7 @@ import Toast
|
||||
let intOffset = Int(offset!.magnitude)
|
||||
showExpandedVoiceMessageRecordingView(offset: intOffset)
|
||||
print("LOCKED")
|
||||
HapticFeedback.rigid()
|
||||
isVoiceRecordingLocked = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +145,9 @@ import UIKit
|
||||
if let responsePoll = responsePoll, error == nil {
|
||||
self.poll = responsePoll
|
||||
self.editingVote = false
|
||||
HapticFeedback.success()
|
||||
} else {
|
||||
HapticFeedback.error()
|
||||
}
|
||||
self.setupPollView()
|
||||
}
|
||||
|
||||
@@ -35,6 +35,9 @@ import SwiftUI
|
||||
private var isLeavingChat = false
|
||||
|
||||
private var chatViewPresentedTimestamp = Date().timeIntervalSince1970
|
||||
|
||||
private var doubleTapReactionGesture: UITapGestureRecognizer?
|
||||
private var lastCelebrationTimestamp: TimeInterval = 0
|
||||
private var generateSummaryFromMessageId: Int?
|
||||
private var generateSummaryTimer: Timer?
|
||||
|
||||
@@ -194,6 +197,23 @@ import SwiftUI
|
||||
}
|
||||
|
||||
func startCall(withVideo video: Bool, silently: Bool, button: BarButtonItemWithActivity) {
|
||||
guard CallPreflightViewController.isNeeded(for: self.room, withVideo: video) else {
|
||||
self.startCallAfterPreflight(withVideo: video, silently: silently, button: button)
|
||||
return
|
||||
}
|
||||
|
||||
let room = self.room
|
||||
let preflightViewController = CallPreflightViewController(room: room, withVideo: video) { [weak self] result in
|
||||
guard let self, let result else { return }
|
||||
|
||||
CallPreflightPreferences.store(result, for: room.token)
|
||||
self.startCallAfterPreflight(withVideo: video, silently: silently, button: button)
|
||||
}
|
||||
|
||||
self.present(preflightViewController, animated: true)
|
||||
}
|
||||
|
||||
private func startCallAfterPreflight(withVideo video: Bool, silently: Bool, button: BarButtonItemWithActivity) {
|
||||
button.showIndicator()
|
||||
if self.room.recordingConsent {
|
||||
NCUserInterfaceController.sharedInstance().presentRecordingConsentAlert(for: self.room) { confirmed in
|
||||
@@ -631,6 +651,8 @@ import SwiftUI
|
||||
|
||||
// Disable room info, input bar and call buttons until joining room
|
||||
self.disableRoomControls()
|
||||
|
||||
self.addDoubleTapReactionGesture()
|
||||
}
|
||||
|
||||
public override func viewWillAppear(_ animated: Bool) {
|
||||
@@ -1782,6 +1804,8 @@ import SwiftUI
|
||||
if firstNewMessagesAfterHistory {
|
||||
self.chatBackgroundView.loadingView.stopAnimating()
|
||||
self.chatBackgroundView.loadingView.isHidden = true
|
||||
} else {
|
||||
self.celebrateIfNeeded(forReceivedMessages: messages)
|
||||
}
|
||||
|
||||
if self.highlightMessageId > 0, let indexPath = self.indexPathAndMessage(forMessageId: self.highlightMessageId)?.indexPath {
|
||||
@@ -1925,6 +1949,11 @@ import SwiftUI
|
||||
message.isOfflineMessage = isOfflineMessage
|
||||
}
|
||||
|
||||
// Offline messages are sent later automatically, only a real failure needs the user's attention
|
||||
if !isOfflineMessage {
|
||||
HapticFeedback.error()
|
||||
}
|
||||
|
||||
} else {
|
||||
// No referenceId -> show generic error
|
||||
self.textView.text = message
|
||||
@@ -2293,6 +2322,99 @@ import SwiftUI
|
||||
super.didCommitTextEditing(sender)
|
||||
}
|
||||
|
||||
// MARK: - Double tap to react
|
||||
|
||||
private func addDoubleTapReactionGesture() {
|
||||
guard let tableView = self.tableView else { return }
|
||||
|
||||
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapReaction(_:)))
|
||||
doubleTapGesture.numberOfTapsRequired = 2
|
||||
doubleTapGesture.delegate = self
|
||||
tableView.addGestureRecognizer(doubleTapGesture)
|
||||
|
||||
self.doubleTapReactionGesture = doubleTapGesture
|
||||
}
|
||||
|
||||
// The reaction a double tap adds: the one used most, which is 👍 until the user reacted a few times
|
||||
private var doubleTapReaction: String {
|
||||
return self.account.frequentlyUsedEmojis.first ?? "👍"
|
||||
}
|
||||
|
||||
func handleDoubleTapReaction(_ gestureRecognizer: UITapGestureRecognizer) {
|
||||
guard gestureRecognizer.state == .ended, let tableView = self.tableView else { return }
|
||||
|
||||
let location = gestureRecognizer.location(in: tableView)
|
||||
|
||||
guard let indexPath = tableView.indexPathForRow(at: location),
|
||||
let message = self.message(for: indexPath),
|
||||
!message.isSystemMessage, !message.isDeleting,
|
||||
self.room.canReact, self.isMessageReactable(message: message)
|
||||
else { return }
|
||||
|
||||
let emoji = self.doubleTapReaction
|
||||
let reaction = message.reactionsArray().first(where: { $0.reaction == emoji }) ?? NCChatReaction(reaction: emoji)
|
||||
|
||||
// Like the reactions below a message, a double tap toggles the reaction
|
||||
if !reaction.userReacted {
|
||||
ChatEffects.showReactionBurst(emoji, at: gestureRecognizer.location(in: self.view), in: self.view)
|
||||
}
|
||||
|
||||
HapticFeedback.light()
|
||||
self.addOrRemoveReaction(reaction: reaction, in: message)
|
||||
}
|
||||
|
||||
private func isInteractiveMessageContent(_ view: UIView?) -> Bool {
|
||||
var currentView = view
|
||||
|
||||
// Images, files, polls, players and so on have their own taps, a double tap there should not add a reaction
|
||||
while let checkedView = currentView, !(checkedView is UITableViewCell) {
|
||||
if checkedView is UIControl || checkedView is UIImageView || checkedView is ReactionsView ||
|
||||
checkedView is AudioPlayerView || checkedView is PollMessageView || checkedView is ReferenceView ||
|
||||
checkedView is GroupedFilePreviewView || checkedView is QuotedMessageView {
|
||||
return true
|
||||
}
|
||||
|
||||
currentView = checkedView.superview
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
public override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
|
||||
if gestureRecognizer == self.doubleTapReactionGesture {
|
||||
return !self.isInteractiveMessageContent(touch.view)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
public override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
|
||||
// A double tap on the message text would otherwise select a word instead of adding the reaction
|
||||
if gestureRecognizer == self.doubleTapReactionGesture, otherGestureRecognizer.view is UITextView,
|
||||
let otherTapGesture = otherGestureRecognizer as? UITapGestureRecognizer, otherTapGesture.numberOfTapsRequired >= 2 {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// MARK: - Celebration
|
||||
|
||||
private func celebrateIfNeeded(forReceivedMessages messages: [NCChatMessage]) {
|
||||
// Only for messages that were written while the chat is open, not for the history
|
||||
let hasNewCelebration = messages.contains { message in
|
||||
!message.isSystemMessage && message.timestamp >= Int(self.chatViewPresentedTimestamp) &&
|
||||
ChatEffects.isCelebration(message.message)
|
||||
}
|
||||
|
||||
// Several celebrating messages right after each other only need one round of confetti
|
||||
let now = Date().timeIntervalSince1970
|
||||
guard hasNewCelebration, now - self.lastCelebrationTimestamp > 10 else { return }
|
||||
|
||||
self.lastCelebrationTimestamp = now
|
||||
ChatEffects.showConfetti(in: self.view)
|
||||
}
|
||||
|
||||
// MARK: - ChatMessageTableViewCellDelegate delegate
|
||||
|
||||
override public func cellDidSelectedReaction(_ reaction: NCChatReaction!, for message: NCChatMessage) {
|
||||
@@ -2550,6 +2672,8 @@ import SwiftUI
|
||||
let emojiAction = UIAction(title: emoji, image: self.getEmojiImage(for: emoji)) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
|
||||
HapticFeedback.light()
|
||||
|
||||
// Wait for the menu to be dismissed, otherwise the message is reloaded while the menu animates
|
||||
self.contextMenuActionBlock = {
|
||||
self.addOrRemoveReaction(reaction: reaction, in: message)
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import CoreSpotlight
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
// Makes the conversations findable in the system search (Spotlight).
|
||||
// Only the names and descriptions are indexed, never any messages. Sensitive conversations are not indexed at all.
|
||||
class ConversationsSpotlightIndexer {
|
||||
|
||||
public static let shared = ConversationsSpotlightIndexer()
|
||||
|
||||
private let indexedAccountIdsKey = "spotlightIndexedAccountIds"
|
||||
|
||||
// What was indexed last per account, to not index the same conversations again on every rooms update
|
||||
private var indexedSignatures = [String: String]()
|
||||
|
||||
func start() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCRoomsManagerDidUpdateRooms, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCSettingsControllerDidChangeActiveAccount, object: nil)
|
||||
|
||||
self.setNeedsUpdate()
|
||||
}
|
||||
|
||||
@objc func setNeedsUpdate() {
|
||||
DispatchQueue.main.async {
|
||||
self.update()
|
||||
}
|
||||
}
|
||||
|
||||
private func update() {
|
||||
guard CSSearchableIndex.isIndexingAvailable() else { return }
|
||||
|
||||
let index = CSSearchableIndex.default()
|
||||
let accounts = NCDatabaseManager.sharedInstance().allAccounts()
|
||||
|
||||
// Remove the conversations of accounts that were logged out
|
||||
let accountIds = Set(accounts.map(\.accountId))
|
||||
let removedAccountIds = self.indexedAccountIds.subtracting(accountIds)
|
||||
|
||||
if !removedAccountIds.isEmpty {
|
||||
index.deleteSearchableItems(withDomainIdentifiers: Array(removedAccountIds))
|
||||
removedAccountIds.forEach { self.indexedSignatures.removeValue(forKey: $0) }
|
||||
}
|
||||
|
||||
self.indexedAccountIds = self.indexedAccountIds.intersection(accountIds)
|
||||
|
||||
guard !accounts.isEmpty else { return }
|
||||
|
||||
// Rooms are only updated for the active account
|
||||
let account = NCDatabaseManager.sharedInstance().activeAccount()
|
||||
let rooms = NCDatabaseManager.sharedInstance().roomsForAccountId(account.accountId, withRealm: nil)
|
||||
.filter { !$0.isSensitive }
|
||||
.sorted { $0.internalId < $1.internalId }
|
||||
|
||||
let signature = rooms.map { "\($0.internalId)\u{1F}\($0.displayName ?? "")\u{1F}\($0.roomDescription ?? "")" }.joined(separator: "\u{1E}")
|
||||
|
||||
guard indexedSignatures[account.accountId] != signature else { return }
|
||||
|
||||
let showAccountName = accounts.count > 1
|
||||
|
||||
let items = rooms.map { room in
|
||||
let attributes = CSSearchableItemAttributeSet(contentType: .content)
|
||||
attributes.title = room.displayName
|
||||
attributes.contentDescription = showAccountName ? account.userDisplayName : room.roomDescription
|
||||
attributes.keywords = ["Talk"]
|
||||
|
||||
return CSSearchableItem(uniqueIdentifier: room.internalId, domainIdentifier: account.accountId, attributeSet: attributes)
|
||||
}
|
||||
|
||||
// Replace all conversations of the account, so removed conversations are removed from the index as well
|
||||
index.deleteSearchableItems(withDomainIdentifiers: [account.accountId]) { _ in
|
||||
index.indexSearchableItems(items) { error in
|
||||
if let error {
|
||||
NCLog.log("Could not index conversations in Spotlight: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
indexedSignatures[account.accountId] = signature
|
||||
self.indexedAccountIds.insert(account.accountId)
|
||||
}
|
||||
|
||||
private var indexedAccountIds: Set<String> {
|
||||
get { Set(UserDefaults.standard.stringArray(forKey: indexedAccountIdsKey) ?? []) }
|
||||
set { UserDefaults.standard.set(Array(newValue), forKey: indexedAccountIdsKey) }
|
||||
}
|
||||
|
||||
// MARK: - Opening a search result
|
||||
|
||||
static func conversationURL(for userActivity: NSUserActivity) -> NSURLComponents? {
|
||||
guard userActivity.activityType == CSSearchableItemActionType,
|
||||
let internalId = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String,
|
||||
let room = NCDatabaseManager.sharedInstance().room(withInternalId: internalId),
|
||||
let account = room.account
|
||||
else { return nil }
|
||||
|
||||
let urlComponents = NSURLComponents()
|
||||
urlComponents.scheme = "nextcloudtalk"
|
||||
urlComponents.host = "open-conversation"
|
||||
urlComponents.queryItems = [
|
||||
URLQueryItem(name: "server", value: account.server),
|
||||
URLQueryItem(name: "user", value: account.userId),
|
||||
URLQueryItem(name: "withRoomToken", value: room.token)
|
||||
]
|
||||
|
||||
return urlComponents
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import WidgetKit
|
||||
|
||||
// Keeps the data of the home and lock screen widgets up to date, see ConversationsWidgetData
|
||||
class ConversationsWidgetController {
|
||||
|
||||
public static let shared = ConversationsWidgetController()
|
||||
|
||||
// Enough for the large widget, the smaller ones show less
|
||||
private let maxConversations = 6
|
||||
private let avatarSize = CGSize(width: 88, height: 88)
|
||||
|
||||
private var lastSavedData: ConversationsWidgetData?
|
||||
private var pendingUpdate: DispatchWorkItem?
|
||||
private var avatarsBeingLoaded = Set<String>()
|
||||
|
||||
func start() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCRoomsManagerDidUpdateRooms, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(setNeedsUpdate), name: .NCSettingsControllerDidChangeActiveAccount, object: nil)
|
||||
|
||||
self.setNeedsUpdate()
|
||||
}
|
||||
|
||||
// Rooms are often updated several times in a row, so the update is slightly delayed to only do it once
|
||||
@objc func setNeedsUpdate() {
|
||||
DispatchQueue.main.async {
|
||||
self.pendingUpdate?.cancel()
|
||||
|
||||
let update = DispatchWorkItem {
|
||||
self.update()
|
||||
}
|
||||
|
||||
self.pendingUpdate = update
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: update)
|
||||
}
|
||||
}
|
||||
|
||||
private func update() {
|
||||
guard NCDatabaseManager.sharedInstance().numberOfAccounts() > 0 else {
|
||||
self.removeData()
|
||||
return
|
||||
}
|
||||
|
||||
let account = NCDatabaseManager.sharedInstance().activeAccount()
|
||||
let rooms = NCDatabaseManager.sharedInstance().roomsForAccountId(account.accountId, withRealm: nil).filter { !$0.isArchived }
|
||||
|
||||
// Favorites first, the remaining space is filled with the most recent conversations
|
||||
let byLastActivity: (NCRoom, NCRoom) -> Bool = { $0.lastActivity > $1.lastActivity }
|
||||
let favoriteRooms = rooms.filter(\.isFavorite).sorted(by: byLastActivity)
|
||||
let otherRooms = rooms.filter { !$0.isFavorite }.sorted(by: byLastActivity)
|
||||
let shownRooms = Array((favoriteRooms + otherRooms).prefix(maxConversations))
|
||||
|
||||
let avatarsDirectoryURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: groupIdentifier)
|
||||
|
||||
let conversations = shownRooms.map { room in
|
||||
let avatarFileName = self.avatarFileName(for: room)
|
||||
let avatarExists = avatarsDirectoryURL.map { FileManager.default.fileExists(atPath: $0.appendingPathComponent(avatarFileName).path) } ?? false
|
||||
|
||||
return ConversationsWidgetData.Conversation(id: room.internalId,
|
||||
token: room.token,
|
||||
displayName: room.displayName,
|
||||
unreadMessages: room.unreadMessages,
|
||||
unreadMention: room.unreadMention,
|
||||
isFavorite: room.isFavorite,
|
||||
hasCall: room.hasCall,
|
||||
avatarFileName: avatarExists ? avatarFileName : nil)
|
||||
}
|
||||
|
||||
let data = ConversationsWidgetData(server: account.server,
|
||||
userId: account.userId,
|
||||
conversations: conversations,
|
||||
unreadConversations: rooms.filter { $0.unreadMessages > 0 }.count,
|
||||
unreadMentions: rooms.filter(\.unreadMention).count)
|
||||
|
||||
self.removeUnusedAvatars(keeping: Set(shownRooms.map { self.avatarFileName(for: $0) }))
|
||||
self.loadMissingAvatars(for: shownRooms)
|
||||
|
||||
guard data != lastSavedData else { return }
|
||||
|
||||
do {
|
||||
try data.save(appGroupIdentifier: groupIdentifier)
|
||||
self.lastSavedData = data
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
} catch {
|
||||
NCLog.log("Could not save widget data: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
private func removeData() {
|
||||
guard lastSavedData != nil || ConversationsWidgetData.load(appGroupIdentifier: groupIdentifier) != nil else { return }
|
||||
|
||||
ConversationsWidgetData.remove(appGroupIdentifier: groupIdentifier)
|
||||
self.lastSavedData = nil
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
}
|
||||
|
||||
// MARK: - Avatars
|
||||
|
||||
private func avatarFileName(for room: NCRoom) -> String {
|
||||
// The version changes with the avatar, so a changed avatar is stored as a new file
|
||||
let name = "\(room.internalId)-\(room.avatarVersion ?? "")"
|
||||
let allowedCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
|
||||
let fileName = String(name.unicodeScalars.map { allowedCharacters.contains($0) ? Character($0) : "_" })
|
||||
|
||||
return "\(fileName).png"
|
||||
}
|
||||
|
||||
private func loadMissingAvatars(for rooms: [NCRoom]) {
|
||||
guard let avatarsDirectoryURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: groupIdentifier) else { return }
|
||||
|
||||
for room in rooms {
|
||||
let fileName = self.avatarFileName(for: room)
|
||||
let fileURL = avatarsDirectoryURL.appendingPathComponent(fileName)
|
||||
|
||||
guard !FileManager.default.fileExists(atPath: fileURL.path), !avatarsBeingLoaded.contains(fileName) else { continue }
|
||||
|
||||
avatarsBeingLoaded.insert(fileName)
|
||||
|
||||
_ = AvatarManager.shared.getAvatar(for: room, with: .light) { [weak self] image in
|
||||
DispatchQueue.main.async {
|
||||
guard let self else { return }
|
||||
|
||||
self.avatarsBeingLoaded.remove(fileName)
|
||||
|
||||
guard let image, let pngData = self.resizedAvatar(image).pngData() else { return }
|
||||
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: avatarsDirectoryURL, withIntermediateDirectories: true)
|
||||
try pngData.write(to: fileURL, options: [.atomic, .noFileProtection])
|
||||
self.setNeedsUpdate()
|
||||
} catch {
|
||||
NCLog.log("Could not save widget avatar: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func resizedAvatar(_ image: UIImage) -> UIImage {
|
||||
let format = UIGraphicsImageRendererFormat()
|
||||
format.scale = 1
|
||||
|
||||
return UIGraphicsImageRenderer(size: avatarSize, format: format).image { _ in
|
||||
image.draw(in: CGRect(origin: .zero, size: avatarSize))
|
||||
}
|
||||
}
|
||||
|
||||
private func removeUnusedAvatars(keeping fileNames: Set<String>) {
|
||||
guard let avatarsDirectoryURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: groupIdentifier),
|
||||
let storedFileNames = try? FileManager.default.contentsOfDirectory(atPath: avatarsDirectoryURL.path)
|
||||
else { return }
|
||||
|
||||
for storedFileName in storedFileNames where !fileNames.contains(storedFileName) {
|
||||
try? FileManager.default.removeItem(at: avatarsDirectoryURL.appendingPathComponent(storedFileName))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -561,6 +561,12 @@ class NCRoomsManager: NSObject, CallViewControllerDelegate {
|
||||
|
||||
callViewController.videoDisabledAtStart = !videoEnabled
|
||||
callViewController.voiceChatModeAtStart = voiceChatMode
|
||||
|
||||
// What was chosen in the check before joining the call
|
||||
if let preflightResult = CallPreflightPreferences.take(for: room.token) {
|
||||
callViewController.audioDisabledAtStart = !preflightResult.microphoneEnabled
|
||||
callViewController.videoDisabledAtStart = callViewController.videoDisabledAtStart || !preflightResult.cameraEnabled
|
||||
}
|
||||
callViewController.initiator = initiator
|
||||
callViewController.silentCall = silently
|
||||
callViewController.recordingConsent = recordingConsent
|
||||
|
||||
@@ -1485,6 +1485,7 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
|
||||
}
|
||||
|
||||
private func addRoomToFavorites(_ room: NCRoom) {
|
||||
HapticFeedback.selection()
|
||||
NCAPIController.sharedInstance().addRoomToFavorites(room.token, forAccount: NCDatabaseManager.sharedInstance().activeAccount()) { error in
|
||||
if let error {
|
||||
NSLog("Error adding room to favorites: %@", error.description)
|
||||
@@ -1494,6 +1495,7 @@ class RoomsTableViewController: UITableViewController, CCCertificateDelegate, UI
|
||||
}
|
||||
|
||||
private func removeRoomFromFavorites(_ room: NCRoom) {
|
||||
HapticFeedback.selection()
|
||||
NCAPIController.sharedInstance().removeRoomFromFavorites(room.token, forAccount: NCDatabaseManager.sharedInstance().activeAccount()) { error in
|
||||
if let error {
|
||||
NSLog("Error removing room from favorites: %@", error.description)
|
||||
|
||||
@@ -432,6 +432,10 @@ public class NCSettingsController: NSObject {
|
||||
NCRoomsManager.shared.chatViewController?.leaveChat()
|
||||
self.createAccountsFile()
|
||||
|
||||
// Don't keep showing the conversations of the removed account
|
||||
ConversationsWidgetController.shared.setNeedsUpdate()
|
||||
ConversationsSpotlightIndexer.shared.setNeedsUpdate()
|
||||
|
||||
// Activate any of the inactive accounts
|
||||
self.switchToAnyInactiveAccount()
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ public class NCUserDefaults: NSObject {
|
||||
private static let includeCallsInRecentsKey = "ncIncludeCallsInRecents"
|
||||
private static let preferredCallViewModeKey = "ncPreferredCallViewMode"
|
||||
private static let speakerViewStripeHiddenKey = "ncSpeakerViewStripeHidden"
|
||||
private static let showCallPreflightKey = "ncShowCallPreflight"
|
||||
|
||||
public static func setPreferredCameraFlashMode(_ flashMode: Int) {
|
||||
UserDefaults.standard.set(flashMode, forKey: preferredCameraFlashModeKey)
|
||||
@@ -59,4 +60,13 @@ public class NCUserDefaults: NSObject {
|
||||
public static func speakerViewStripeHidden() -> Bool {
|
||||
return UserDefaults.standard.bool(forKey: speakerViewStripeHiddenKey)
|
||||
}
|
||||
|
||||
public static func setShowCallPreflight(_ enabled: Bool) {
|
||||
UserDefaults.standard.set(enabled, forKey: showCallPreflightKey)
|
||||
}
|
||||
|
||||
// Check camera and microphone before joining a call, enabled by default
|
||||
public static func showCallPreflight() -> Bool {
|
||||
return UserDefaults.standard.object(forKey: showCallPreflightKey) as? Bool ?? true
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ enum AccountSettingsOptions: Int {
|
||||
enum ConfigurationSectionOption: Int {
|
||||
case kConfigurationSectionOptionVideo = 0
|
||||
case kConfigurationSectionOptionRecents
|
||||
case kConfigurationSectionOptionCallPreflight
|
||||
}
|
||||
|
||||
enum AdvancedSectionOption: Int {
|
||||
@@ -55,6 +56,7 @@ class SettingsTableViewController: UITableViewController, UITextFieldDelegate, U
|
||||
var contactSyncSwitch = UISwitch()
|
||||
var setPhoneAction: UIAlertAction?
|
||||
var includeInRecentsSwitch = UISwitch()
|
||||
var callPreflightSwitch = UISwitch()
|
||||
|
||||
var totalImageCacheSize = 0
|
||||
var totalFileCacheSize = 0
|
||||
@@ -100,6 +102,9 @@ class SettingsTableViewController: UITableViewController, UITextFieldDelegate, U
|
||||
includeInRecentsSwitch.frame = .zero
|
||||
includeInRecentsSwitch.addTarget(self, action: #selector(includeInRecentsValueChanged(_:)), for: .valueChanged)
|
||||
|
||||
callPreflightSwitch.frame = .zero
|
||||
callPreflightSwitch.addTarget(self, action: #selector(callPreflightValueChanged(_:)), for: .valueChanged)
|
||||
|
||||
typingIndicatorSwitch.frame = .zero
|
||||
typingIndicatorSwitch.addTarget(self, action: #selector(typingIndicatorValueChanged(_:)), for: .valueChanged)
|
||||
|
||||
@@ -188,6 +193,9 @@ class SettingsTableViewController: UITableViewController, UITextFieldDelegate, U
|
||||
// Calls in recents
|
||||
options.append(ConfigurationSectionOption.kConfigurationSectionOptionRecents.rawValue)
|
||||
|
||||
// Check camera and microphone before joining a call
|
||||
options.append(ConfigurationSectionOption.kConfigurationSectionOptionCallPreflight.rawValue)
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
@@ -521,6 +529,10 @@ class SettingsTableViewController: UITableViewController, UITextFieldDelegate, U
|
||||
CallKitManager.sharedInstance().setIncludeInRecents(toValue: includeInRecentsSwitch.isOn)
|
||||
}
|
||||
|
||||
@objc func callPreflightValueChanged(_ sender: Any?) {
|
||||
NCUserDefaults.setShowCallPreflight(callPreflightSwitch.isOn)
|
||||
}
|
||||
|
||||
// MARK: - Advanced actions
|
||||
|
||||
func diagnosticsPressed() {
|
||||
@@ -922,6 +934,16 @@ extension SettingsTableViewController {
|
||||
includeInRecentsSwitch.isOn = NCUserDefaults.includeCallsInRecents()
|
||||
return cell
|
||||
|
||||
case ConfigurationSectionOption.kConfigurationSectionOptionCallPreflight.rawValue:
|
||||
let cell: SettingsTableViewCell = tableView.dequeueOrCreateCell(withIdentifier: configurationCellIdentifier, style: .default)
|
||||
cell.textLabel?.text = NSLocalizedString("Check camera and microphone before calls", comment: "")
|
||||
cell.textLabel?.numberOfLines = 0
|
||||
cell.setSettingsImage(image: UIImage(systemName: "person.crop.square.badge.camera")?.applyingSymbolConfiguration(iconConfiguration))
|
||||
cell.selectionStyle = .none
|
||||
cell.accessoryView = callPreflightSwitch
|
||||
callPreflightSwitch.isOn = NCUserDefaults.showCallPreflight()
|
||||
return cell
|
||||
|
||||
default:
|
||||
return UITableViewCell()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
// Small, purely decorative animations in the chat.
|
||||
// All effects are skipped when "Reduce Motion" is enabled.
|
||||
@MainActor
|
||||
enum ChatEffects {
|
||||
|
||||
// MARK: - Celebration
|
||||
|
||||
// Emojis that let it rain confetti. Only emojis, so it works the same in every language.
|
||||
static let celebrationEmojis: Set<Character> = ["🎉", "🥳", "🎊", "🎂"]
|
||||
|
||||
static func isCelebration(_ messageText: String?) -> Bool {
|
||||
guard let messageText else { return false }
|
||||
|
||||
return messageText.contains { celebrationEmojis.contains($0) }
|
||||
}
|
||||
|
||||
/// Lets confetti fall from the top of the view for a moment. The view is removed again afterwards.
|
||||
static func showConfetti(in view: UIView) {
|
||||
guard !UIAccessibility.isReduceMotionEnabled else { return }
|
||||
|
||||
let confettiView = UIView(frame: view.bounds)
|
||||
confettiView.isUserInteractionEnabled = false
|
||||
confettiView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
confettiView.accessibilityElementsHidden = true
|
||||
view.addSubview(confettiView)
|
||||
|
||||
let emitter = CAEmitterLayer()
|
||||
emitter.emitterPosition = CGPoint(x: view.bounds.midX, y: -10)
|
||||
emitter.emitterShape = .line
|
||||
emitter.emitterSize = CGSize(width: view.bounds.width, height: 1)
|
||||
emitter.beginTime = CACurrentMediaTime()
|
||||
|
||||
let colors: [UIColor] = [.systemRed, .systemOrange, .systemYellow, .systemGreen, .systemBlue, .systemPurple, .systemPink]
|
||||
let confettiImage = self.confettiPieceImage()
|
||||
|
||||
emitter.emitterCells = colors.map { color in
|
||||
let cell = CAEmitterCell()
|
||||
cell.contents = confettiImage
|
||||
cell.color = color.cgColor
|
||||
cell.birthRate = 10
|
||||
cell.lifetime = 6
|
||||
cell.velocity = 180
|
||||
cell.velocityRange = 60
|
||||
cell.emissionLongitude = .pi
|
||||
cell.emissionRange = .pi / 6
|
||||
cell.yAcceleration = 120
|
||||
cell.spin = 3
|
||||
cell.spinRange = 4
|
||||
cell.scale = 0.6
|
||||
cell.scaleRange = 0.3
|
||||
cell.alphaSpeed = -0.12
|
||||
return cell
|
||||
}
|
||||
|
||||
confettiView.layer.addSublayer(emitter)
|
||||
|
||||
// Stop emitting new pieces after a short burst, then remove the view once all pieces are gone
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
|
||||
emitter.birthRate = 0
|
||||
}
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
|
||||
confettiView.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
|
||||
private static func confettiPieceImage() -> CGImage? {
|
||||
let size = CGSize(width: 8, height: 12)
|
||||
|
||||
return UIGraphicsImageRenderer(size: size).image { context in
|
||||
UIColor.white.setFill()
|
||||
context.fill(CGRect(origin: .zero, size: size))
|
||||
}.cgImage
|
||||
}
|
||||
|
||||
// MARK: - Reaction burst
|
||||
|
||||
/// Shows the emoji growing at the given point, while smaller copies of it fly outwards.
|
||||
static func showReactionBurst(_ emoji: String, at point: CGPoint, in view: UIView) {
|
||||
guard !UIAccessibility.isReduceMotionEnabled else { return }
|
||||
|
||||
let mainLabel = self.emojiLabel(emoji, fontSize: 56)
|
||||
mainLabel.center = point
|
||||
mainLabel.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
|
||||
view.addSubview(mainLabel)
|
||||
|
||||
UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8) {
|
||||
mainLabel.transform = .identity
|
||||
} completion: { _ in
|
||||
UIView.animate(withDuration: 0.4, delay: 0.15, options: .curveEaseIn) {
|
||||
mainLabel.transform = CGAffineTransform(translationX: 0, y: -40).scaledBy(x: 0.6, y: 0.6)
|
||||
mainLabel.alpha = 0
|
||||
} completion: { _ in
|
||||
mainLabel.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
|
||||
let particleCount = 6
|
||||
|
||||
for index in 0..<particleCount {
|
||||
let particleLabel = self.emojiLabel(emoji, fontSize: 20)
|
||||
particleLabel.center = point
|
||||
particleLabel.alpha = 0.9
|
||||
view.addSubview(particleLabel)
|
||||
|
||||
let angle = (CGFloat(index) / CGFloat(particleCount)) * 2 * .pi + CGFloat.random(in: -0.3...0.3)
|
||||
let distance = CGFloat.random(in: 50...80)
|
||||
let translation = CGAffineTransform(translationX: cos(angle) * distance, y: sin(angle) * distance)
|
||||
|
||||
UIView.animate(withDuration: 0.6, delay: 0.05, options: .curveEaseOut) {
|
||||
particleLabel.transform = translation.scaledBy(x: 0.5, y: 0.5)
|
||||
particleLabel.alpha = 0
|
||||
} completion: { _ in
|
||||
particleLabel.removeFromSuperview()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func emojiLabel(_ emoji: String, fontSize: CGFloat) -> UILabel {
|
||||
let label = UILabel()
|
||||
label.text = emoji
|
||||
label.font = .systemFont(ofSize: fontSize)
|
||||
label.isUserInteractionEnabled = false
|
||||
label.isAccessibilityElement = false
|
||||
label.sizeToFit()
|
||||
|
||||
return label
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
// Central place for haptic feedback, so the same kind of action feels the same everywhere in the app.
|
||||
// UIFeedbackGenerator respects the system haptics setting, there's no need for an additional check here.
|
||||
@MainActor
|
||||
enum HapticFeedback {
|
||||
|
||||
private static let lightImpactGenerator = UIImpactFeedbackGenerator(style: .light)
|
||||
private static let mediumImpactGenerator = UIImpactFeedbackGenerator(style: .medium)
|
||||
private static let rigidImpactGenerator = UIImpactFeedbackGenerator(style: .rigid)
|
||||
private static let selectionGenerator = UISelectionFeedbackGenerator()
|
||||
private static let notificationGenerator = UINotificationFeedbackGenerator()
|
||||
|
||||
/// A small tap, e.g. when sending a message or toggling a call button
|
||||
static func light() {
|
||||
lightImpactGenerator.impactOccurred()
|
||||
}
|
||||
|
||||
/// A more noticeable tap for actions with a bigger effect, e.g. leaving a call
|
||||
static func medium() {
|
||||
mediumImpactGenerator.impactOccurred()
|
||||
}
|
||||
|
||||
/// A short, firm tap for something snapping into place, e.g. locking a voice recording
|
||||
static func rigid() {
|
||||
rigidImpactGenerator.impactOccurred()
|
||||
}
|
||||
|
||||
/// A tick for changing a selection or toggling a state, e.g. adding a conversation to favorites
|
||||
static func selection() {
|
||||
selectionGenerator.selectionChanged()
|
||||
}
|
||||
|
||||
static func success() {
|
||||
notificationGenerator.notificationOccurred(.success)
|
||||
}
|
||||
|
||||
static func warning() {
|
||||
notificationGenerator.notificationOccurred(.warning)
|
||||
}
|
||||
|
||||
static func error() {
|
||||
notificationGenerator.notificationOccurred(.error)
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,9 @@ public class NCPeerConnection: NSObject {
|
||||
var showRemoteVideoInOriginalSize = false
|
||||
var addedTime: Int = 0
|
||||
var selectedSimulcastVideoQuality: SimulcastVideoQuality?
|
||||
// The highest video quality we send, lowered while the device is hot or in Low Power Mode
|
||||
var maxSendVideoQuality: SimulcastVideoQuality = .high
|
||||
private var appliedMaxSendVideoQuality: SimulcastVideoQuality = .high
|
||||
var isRemoteVideoBlockedInMCU = false
|
||||
|
||||
// Keys of the remote participant, set for end-to-end encrypted calls before any media is received
|
||||
@@ -422,11 +425,65 @@ public class NCPeerConnection: NSObject {
|
||||
disableSimulcastIfUnsupported()
|
||||
}
|
||||
|
||||
// The codec is only known now, so a limit that was set before can be applied now
|
||||
applyMaxSendVideoQuality()
|
||||
|
||||
if peerConnection?.remoteDescription != nil {
|
||||
drainRemoteCandidates()
|
||||
}
|
||||
}
|
||||
|
||||
func applyMaxSendVideoQuality() {
|
||||
WebRTCCommon.shared.assertQueue()
|
||||
|
||||
// Screen shares need to stay readable, they are not limited
|
||||
guard roomType == kRoomTypeVideo,
|
||||
maxSendVideoQuality != .high || appliedMaxSendVideoQuality != .high
|
||||
else { return }
|
||||
|
||||
for transceiver in peerConnection?.transceivers ?? [] where transceiver.mediaType == .video {
|
||||
let parameters = transceiver.sender.parameters
|
||||
|
||||
if NCPeerConnection.limitSendEncodings(parameters.encodings, withCodec: parameters.codecs.first?.name, to: maxSendVideoQuality) {
|
||||
transceiver.sender.parameters = parameters
|
||||
}
|
||||
}
|
||||
|
||||
appliedMaxSendVideoQuality = maxSendVideoQuality
|
||||
}
|
||||
|
||||
// Returns false, when the encodings could not be limited (yet)
|
||||
static func limitSendEncodings(_ encodings: [RTCRtpEncodingParameters], withCodec codecName: String?, to quality: SimulcastVideoQuality) -> Bool {
|
||||
guard !encodings.isEmpty else { return false }
|
||||
|
||||
if encodings.count > 1 {
|
||||
// Before the negotiation finished it's unknown whether simulcast is used
|
||||
guard let codecName else { return false }
|
||||
|
||||
if codecName.caseInsensitiveCompare(kRTCVideoCodecVp8Name) == .orderedSame {
|
||||
// The layers are ordered from lowest to highest, so their index matches the quality
|
||||
for (index, encoding) in encodings.enumerated() {
|
||||
encoding.isActive = index <= quality.rawValue
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// A single stream (no simulcast, or only the highest layer active) can only be scaled down
|
||||
let scaleResolutionDownBy: Double = switch quality {
|
||||
case .low: 4
|
||||
case .medium: 2
|
||||
case .high: 1
|
||||
}
|
||||
|
||||
for encoding in encodings where encoding.isActive {
|
||||
encoding.scaleResolutionDownBy = NSNumber(value: scaleResolutionDownBy)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Only the VP8 encoder supports simulcast, others encode a single stream
|
||||
private func disableSimulcastIfUnsupported() {
|
||||
for transceiver in peerConnection?.transceivers ?? [] where transceiver.mediaType == .video {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import XCTest
|
||||
import WebRTC
|
||||
@testable import NextcloudTalk
|
||||
|
||||
final class UnitCallPerformanceTest: XCTestCase {
|
||||
|
||||
func testMaxVideoQuality() {
|
||||
func maxVideoQuality(_ thermalState: ProcessInfo.ThermalState, _ lowPower: Bool) -> SimulcastVideoQuality {
|
||||
return CallPerformanceMonitor.maxVideoQuality(thermalState: thermalState, isLowPowerModeEnabled: lowPower).quality
|
||||
}
|
||||
|
||||
XCTAssertEqual(maxVideoQuality(.nominal, false), .high)
|
||||
XCTAssertEqual(maxVideoQuality(.fair, false), .high)
|
||||
XCTAssertEqual(maxVideoQuality(.nominal, true), .medium)
|
||||
XCTAssertEqual(maxVideoQuality(.serious, false), .medium)
|
||||
XCTAssertEqual(maxVideoQuality(.serious, true), .medium)
|
||||
XCTAssertEqual(maxVideoQuality(.critical, false), .low)
|
||||
XCTAssertEqual(maxVideoQuality(.critical, true), .low)
|
||||
|
||||
XCTAssertEqual(CallPerformanceMonitor.maxVideoQuality(thermalState: .serious, isLowPowerModeEnabled: true).reason, .thermalState)
|
||||
XCTAssertEqual(CallPerformanceMonitor.maxVideoQuality(thermalState: .fair, isLowPowerModeEnabled: true).reason, .lowPowerMode)
|
||||
}
|
||||
|
||||
private func simulcastEncodings() -> [RTCRtpEncodingParameters] {
|
||||
return [4.0, 2.0, 1.0].map { scale in
|
||||
let encoding = RTCRtpEncodingParameters()
|
||||
encoding.scaleResolutionDownBy = NSNumber(value: scale)
|
||||
encoding.isActive = true
|
||||
return encoding
|
||||
}
|
||||
}
|
||||
|
||||
func testLimitSimulcastEncodings() {
|
||||
let encodings = simulcastEncodings()
|
||||
|
||||
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecVp8Name, to: .medium))
|
||||
XCTAssertEqual(encodings.map(\.isActive), [true, true, false])
|
||||
// The layers themselves are not scaled, only switched off
|
||||
XCTAssertEqual(encodings.map { $0.scaleResolutionDownBy?.doubleValue }, [4, 2, 1])
|
||||
|
||||
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecVp8Name, to: .low))
|
||||
XCTAssertEqual(encodings.map(\.isActive), [true, false, false])
|
||||
|
||||
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecVp8Name, to: .high))
|
||||
XCTAssertEqual(encodings.map(\.isActive), [true, true, true])
|
||||
}
|
||||
|
||||
func testLimitSimulcastEncodingsBeforeNegotiation() {
|
||||
let encodings = simulcastEncodings()
|
||||
|
||||
XCTAssertFalse(NCPeerConnection.limitSendEncodings(encodings, withCodec: nil, to: .low))
|
||||
XCTAssertEqual(encodings.map(\.isActive), [true, true, true])
|
||||
}
|
||||
|
||||
func testLimitSingleStream() {
|
||||
let encoding = RTCRtpEncodingParameters()
|
||||
encoding.isActive = true
|
||||
|
||||
XCTAssertTrue(NCPeerConnection.limitSendEncodings([encoding], withCodec: nil, to: .medium))
|
||||
XCTAssertEqual(encoding.scaleResolutionDownBy?.doubleValue, 2)
|
||||
|
||||
XCTAssertTrue(NCPeerConnection.limitSendEncodings([encoding], withCodec: nil, to: .high))
|
||||
XCTAssertEqual(encoding.scaleResolutionDownBy?.doubleValue, 1)
|
||||
}
|
||||
|
||||
func testLimitSimulcastWithUnsupportedCodec() {
|
||||
// Only the highest layer is active without VP8, see disableSimulcastIfUnsupported
|
||||
let encodings = simulcastEncodings()
|
||||
encodings[0].isActive = false
|
||||
encodings[1].isActive = false
|
||||
|
||||
XCTAssertTrue(NCPeerConnection.limitSendEncodings(encodings, withCodec: kRTCVideoCodecH264Name, to: .low))
|
||||
XCTAssertEqual(encodings.map(\.isActive), [false, false, true])
|
||||
XCTAssertEqual(encodings.map { $0.scaleResolutionDownBy?.doubleValue }, [4, 2, 4])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import NextcloudTalk
|
||||
|
||||
final class UnitCallPreflightTest: XCTestCase {
|
||||
|
||||
func testMicrophoneLevelNormalization() {
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: -160), 0)
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: -50), 0)
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: -25), 0.5, accuracy: 0.001)
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: 0), 1)
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: 6), 1)
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: -.infinity), 0)
|
||||
XCTAssertEqual(CallPreflightModel.normalizedLevel(fromDecibels: .nan), 0)
|
||||
}
|
||||
|
||||
func testPreflightResultIsTakenOnlyOnceAndOnlyForTheSameConversation() {
|
||||
let result = CallPreflightResult(cameraEnabled: false, microphoneEnabled: true)
|
||||
|
||||
CallPreflightPreferences.store(result, for: "token1")
|
||||
|
||||
XCTAssertNil(CallPreflightPreferences.take(for: "token2"))
|
||||
XCTAssertEqual(CallPreflightPreferences.take(for: "token1"), result)
|
||||
XCTAssertNil(CallPreflightPreferences.take(for: "token1"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import NextcloudTalk
|
||||
|
||||
final class UnitChatEffectsTest: XCTestCase {
|
||||
|
||||
@MainActor
|
||||
func testCelebrationDetection() {
|
||||
XCTAssertTrue(ChatEffects.isCelebration("Happy birthday 🎂"))
|
||||
XCTAssertTrue(ChatEffects.isCelebration("🎉"))
|
||||
XCTAssertTrue(ChatEffects.isCelebration("We shipped it 🥳🥳"))
|
||||
XCTAssertFalse(ChatEffects.isCelebration("Happy birthday"))
|
||||
XCTAssertFalse(ChatEffects.isCelebration("👍"))
|
||||
XCTAssertFalse(ChatEffects.isCelebration(""))
|
||||
XCTAssertFalse(ChatEffects.isCelebration(nil))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import NextcloudTalk
|
||||
|
||||
final class UnitConversationsWidgetDataTest: XCTestCase {
|
||||
|
||||
private let conversation = ConversationsWidgetData.Conversation(id: "account@token", token: "abc123", displayName: "Design & Dev",
|
||||
unreadMessages: 2, unreadMention: true, isFavorite: true,
|
||||
hasCall: false, avatarFileName: nil)
|
||||
|
||||
func testOpenURL() throws {
|
||||
let data = ConversationsWidgetData(server: "https://cloud.example.com/sub", userId: "alice smith", conversations: [conversation],
|
||||
unreadConversations: 1, unreadMentions: 1)
|
||||
|
||||
let url = try XCTUnwrap(data.openURL(for: conversation))
|
||||
let components = try XCTUnwrap(NSURLComponents(url: url, resolvingAgainstBaseURL: false))
|
||||
let queryItems = (components.queryItems ?? []) as NSArray
|
||||
|
||||
XCTAssertEqual(components.scheme, "nextcloudtalk")
|
||||
XCTAssertEqual(components.host, "open-conversation")
|
||||
XCTAssertEqual(NCUtils.value(forKey: "server", fromQueryItems: queryItems), "https://cloud.example.com/sub")
|
||||
XCTAssertEqual(NCUtils.value(forKey: "user", fromQueryItems: queryItems), "alice smith")
|
||||
XCTAssertEqual(NCUtils.value(forKey: "withRoomToken", fromQueryItems: queryItems), "abc123")
|
||||
}
|
||||
|
||||
func testCodableRoundTrip() throws {
|
||||
let data = ConversationsWidgetData(server: "https://cloud.example.com", userId: "alice", conversations: [conversation],
|
||||
unreadConversations: 1, unreadMentions: 1)
|
||||
|
||||
let decoded = try JSONDecoder().decode(ConversationsWidgetData.self, from: JSONEncoder().encode(data))
|
||||
|
||||
XCTAssertEqual(decoded, data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import WidgetKit
|
||||
|
||||
// Home screen widget with the favorite conversations, filled up with the most recent ones
|
||||
struct ConversationsWidget: Widget {
|
||||
|
||||
var body: some WidgetConfiguration {
|
||||
StaticConfiguration(kind: ConversationsWidgetData.conversationsWidgetKind, provider: ConversationsProvider()) { entry in
|
||||
ConversationsWidgetView(entry: entry)
|
||||
.widgetBackground { Color(UIColor.systemBackground) }
|
||||
}
|
||||
.configurationDisplayName(NSLocalizedString("Conversations", comment: "Name of the widget"))
|
||||
.description(NSLocalizedString("Your favorite and most recent conversations.", comment: "Description of the conversations widget"))
|
||||
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
|
||||
}
|
||||
}
|
||||
|
||||
struct ConversationsWidgetView: View {
|
||||
|
||||
@Environment(\.widgetFamily) private var family
|
||||
|
||||
let entry: ConversationsEntry
|
||||
|
||||
var body: some View {
|
||||
if let data = entry.data {
|
||||
switch family {
|
||||
case .systemSmall:
|
||||
SmallConversationsView(data: data)
|
||||
case .systemMedium:
|
||||
ConversationsGridView(data: data, conversations: Array(data.conversations.prefix(4)))
|
||||
default:
|
||||
ConversationsListView(data: data, conversations: Array(data.conversations.prefix(6)))
|
||||
}
|
||||
} else {
|
||||
Text(NSLocalizedString("Log in to Nextcloud Talk to see your conversations here", comment: "Shown in a widget, when no account is logged in"))
|
||||
.font(.footnote)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Small
|
||||
|
||||
struct SmallConversationsView: View {
|
||||
|
||||
let data: ConversationsWidgetData
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Image(systemName: "bubble.left.and.bubble.right.fill")
|
||||
.foregroundColor(.talkAccent)
|
||||
Spacer()
|
||||
if data.unreadMentions > 0 {
|
||||
UnreadBadge(text: "@", isMention: true)
|
||||
}
|
||||
}
|
||||
|
||||
Text("\(data.unreadConversations)")
|
||||
.font(.system(size: 34, weight: .bold, design: .rounded))
|
||||
.minimumScaleFactor(0.6)
|
||||
|
||||
Text(NSLocalizedString("Unread conversations", comment: "Shown in a widget below the number of conversations with unread messages"))
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
.lineLimit(2)
|
||||
|
||||
Spacer(minLength: 0)
|
||||
|
||||
// The most recent unread conversation, or the first favorite
|
||||
if let conversation = data.conversations.first(where: { $0.unreadMessages > 0 }) ?? data.conversations.first {
|
||||
Text(conversation.displayName)
|
||||
.font(.footnote.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
.privacySensitive()
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Medium
|
||||
|
||||
struct ConversationsGridView: View {
|
||||
|
||||
let data: ConversationsWidgetData
|
||||
let conversations: [ConversationsWidgetData.Conversation]
|
||||
|
||||
var body: some View {
|
||||
if conversations.isEmpty {
|
||||
NoConversationsView()
|
||||
} else {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
ForEach(conversations) { conversation in
|
||||
ConversationLink(url: data.openURL(for: conversation)) {
|
||||
VStack(spacing: 6) {
|
||||
ConversationAvatar(conversation: conversation, size: 52)
|
||||
.overlay(alignment: .topTrailing) {
|
||||
if conversation.unreadMessages > 0 {
|
||||
UnreadBadge(conversation: conversation)
|
||||
.offset(x: 6, y: -4)
|
||||
}
|
||||
}
|
||||
|
||||
Text(conversation.displayName)
|
||||
.font(.caption)
|
||||
.lineLimit(2)
|
||||
.multilineTextAlignment(.center)
|
||||
.privacySensitive()
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Large
|
||||
|
||||
struct ConversationsListView: View {
|
||||
|
||||
let data: ConversationsWidgetData
|
||||
let conversations: [ConversationsWidgetData.Conversation]
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack {
|
||||
Image(systemName: "bubble.left.and.bubble.right.fill")
|
||||
.foregroundColor(.talkAccent)
|
||||
Text(NSLocalizedString("Conversations", comment: ""))
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
}
|
||||
|
||||
if conversations.isEmpty {
|
||||
NoConversationsView()
|
||||
} else {
|
||||
ForEach(conversations) { conversation in
|
||||
ConversationLink(url: data.openURL(for: conversation)) {
|
||||
HStack(spacing: 10) {
|
||||
ConversationAvatar(conversation: conversation, size: 36)
|
||||
|
||||
Text(conversation.displayName)
|
||||
.font(.subheadline.weight(conversation.unreadMessages > 0 ? .semibold : .regular))
|
||||
.lineLimit(1)
|
||||
.privacySensitive()
|
||||
|
||||
Spacer(minLength: 4)
|
||||
|
||||
if conversation.hasCall {
|
||||
Image(systemName: "video.fill")
|
||||
.foregroundColor(.green)
|
||||
.font(.caption)
|
||||
}
|
||||
|
||||
if conversation.isFavorite {
|
||||
Image(systemName: "star.fill")
|
||||
.foregroundColor(.yellow)
|
||||
.font(.caption2)
|
||||
}
|
||||
|
||||
if conversation.unreadMessages > 0 {
|
||||
UnreadBadge(conversation: conversation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Components
|
||||
|
||||
struct ConversationLink<Content: View>: View {
|
||||
|
||||
let url: URL?
|
||||
@ViewBuilder let content: () -> Content
|
||||
|
||||
var body: some View {
|
||||
if let url {
|
||||
Link(destination: url, label: content)
|
||||
} else {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct NoConversationsView: View {
|
||||
var body: some View {
|
||||
Text(NSLocalizedString("No conversations yet", comment: "Shown in a widget"))
|
||||
.font(.footnote)
|
||||
.foregroundColor(.secondary)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
struct UnreadBadge: View {
|
||||
|
||||
let text: String
|
||||
let isMention: Bool
|
||||
|
||||
init(text: String, isMention: Bool) {
|
||||
self.text = text
|
||||
self.isMention = isMention
|
||||
}
|
||||
|
||||
init(conversation: ConversationsWidgetData.Conversation) {
|
||||
self.text = conversation.unreadMessages > 99 ? "99+" : "\(conversation.unreadMessages)"
|
||||
self.isMention = conversation.unreadMention
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Text(text)
|
||||
.font(.caption2.weight(.bold))
|
||||
.foregroundColor(isMention ? .white : .primary)
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 2)
|
||||
.background(Capsule().fill(isMention ? Color.talkAccent : Color(UIColor.systemGray5)))
|
||||
}
|
||||
}
|
||||
|
||||
struct ConversationAvatar: View {
|
||||
|
||||
let conversation: ConversationsWidgetData.Conversation
|
||||
let size: CGFloat
|
||||
|
||||
private static let colors: [Color] = [.blue, .green, .orange, .pink, .purple, .teal, .indigo, .red]
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let image = WidgetStorage.avatar(named: conversation.avatarFileName) {
|
||||
Image(uiImage: image)
|
||||
.resizable()
|
||||
.scaledToFill()
|
||||
} else {
|
||||
ZStack {
|
||||
Self.colors[colorIndex]
|
||||
Text(initials)
|
||||
.font(.system(size: size * 0.4, weight: .semibold))
|
||||
.foregroundColor(.white)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(width: size, height: size)
|
||||
.clipShape(Circle())
|
||||
}
|
||||
|
||||
private var initials: String {
|
||||
return conversation.displayName.split(separator: " ").prefix(2).compactMap(\.first).map(String.init).joined().uppercased()
|
||||
}
|
||||
|
||||
// Stable over launches, unlike hashValue
|
||||
private var colorIndex: Int {
|
||||
return conversation.displayName.unicodeScalars.reduce(0) { $0 + Int($1.value) } % Self.colors.count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
// What the widgets show. The app writes it into the shared app group container whenever the
|
||||
// conversations change and the widgets only read it, so they need neither network access nor the database.
|
||||
// This file is part of the app and of the widget extension.
|
||||
struct ConversationsWidgetData: Codable, Equatable {
|
||||
|
||||
struct Conversation: Codable, Equatable, Identifiable {
|
||||
// The internalId of the room
|
||||
let id: String
|
||||
let token: String
|
||||
let displayName: String
|
||||
let unreadMessages: Int
|
||||
let unreadMention: Bool
|
||||
let isFavorite: Bool
|
||||
let hasCall: Bool
|
||||
// Name of the avatar image in the avatars directory, if it was stored already
|
||||
let avatarFileName: String?
|
||||
}
|
||||
|
||||
let server: String
|
||||
let userId: String
|
||||
let conversations: [Conversation]
|
||||
let unreadConversations: Int
|
||||
let unreadMentions: Int
|
||||
|
||||
static let conversationsWidgetKind = "ConversationsWidget"
|
||||
static let unreadWidgetKind = "UnreadConversationsWidget"
|
||||
|
||||
private static let directoryName = "Widgets"
|
||||
private static let dataFileName = "conversations.json"
|
||||
private static let avatarsDirectoryName = "Avatars"
|
||||
|
||||
// Opens the conversation, same as a nextcloudtalk:// link from the web
|
||||
func openURL(for conversation: Conversation) -> URL? {
|
||||
var components = URLComponents()
|
||||
components.scheme = "nextcloudtalk"
|
||||
components.host = "open-conversation"
|
||||
components.queryItems = [
|
||||
URLQueryItem(name: "server", value: server),
|
||||
URLQueryItem(name: "user", value: userId),
|
||||
URLQueryItem(name: "withRoomToken", value: conversation.token)
|
||||
]
|
||||
|
||||
return components.url
|
||||
}
|
||||
|
||||
// MARK: - Storage
|
||||
|
||||
static func directoryURL(appGroupIdentifier: String) -> URL? {
|
||||
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(directoryName, isDirectory: true)
|
||||
}
|
||||
|
||||
static func avatarsDirectoryURL(appGroupIdentifier: String) -> URL? {
|
||||
return directoryURL(appGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(avatarsDirectoryName, isDirectory: true)
|
||||
}
|
||||
|
||||
static func load(appGroupIdentifier: String) -> ConversationsWidgetData? {
|
||||
guard let fileURL = directoryURL(appGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(dataFileName),
|
||||
let data = try? Data(contentsOf: fileURL)
|
||||
else { return nil }
|
||||
|
||||
return try? JSONDecoder().decode(ConversationsWidgetData.self, from: data)
|
||||
}
|
||||
|
||||
func save(appGroupIdentifier: String) throws {
|
||||
guard let directoryURL = Self.directoryURL(appGroupIdentifier: appGroupIdentifier) else { return }
|
||||
|
||||
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
let data = try JSONEncoder().encode(self)
|
||||
// The widget reads the file while the device is locked as well
|
||||
try data.write(to: directoryURL.appendingPathComponent(Self.dataFileName), options: [.atomic, .noFileProtection])
|
||||
}
|
||||
|
||||
static func remove(appGroupIdentifier: String) {
|
||||
guard let directoryURL = directoryURL(appGroupIdentifier: appGroupIdentifier) else { return }
|
||||
|
||||
try? FileManager.default.removeItem(at: directoryURL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Talk</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>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>$(MARKETING_VERSION)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NCAppGroupIdentifier</key>
|
||||
<string>group.com.nextcloud.Talk</string>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.widgetkit-extension</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?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>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.com.nextcloud.Talk</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,98 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import WidgetKit
|
||||
|
||||
@main
|
||||
struct TalkWidgetsBundle: WidgetBundle {
|
||||
var body: some Widget {
|
||||
ConversationsWidget()
|
||||
UnreadConversationsWidget()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Timeline
|
||||
|
||||
struct ConversationsEntry: TimelineEntry {
|
||||
let date: Date
|
||||
// Nil, when no account is logged in
|
||||
let data: ConversationsWidgetData?
|
||||
}
|
||||
|
||||
struct ConversationsProvider: TimelineProvider {
|
||||
|
||||
func placeholder(in context: Context) -> ConversationsEntry {
|
||||
return ConversationsEntry(date: Date(), data: .preview)
|
||||
}
|
||||
|
||||
func getSnapshot(in context: Context, completion: @escaping (ConversationsEntry) -> Void) {
|
||||
// The widget gallery shows example conversations, until there are real ones
|
||||
let data = WidgetStorage.loadData() ?? (context.isPreview ? .preview : nil)
|
||||
completion(ConversationsEntry(date: Date(), data: data))
|
||||
}
|
||||
|
||||
func getTimeline(in context: Context, completion: @escaping (Timeline<ConversationsEntry>) -> Void) {
|
||||
// The app reloads the widgets whenever the conversations change, there's nothing to refresh on our own
|
||||
let entry = ConversationsEntry(date: Date(), data: WidgetStorage.loadData())
|
||||
completion(Timeline(entries: [entry], policy: .never))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Storage
|
||||
|
||||
enum WidgetStorage {
|
||||
|
||||
// Set in the Info.plist, as it differs for branded apps
|
||||
static var appGroupIdentifier: String {
|
||||
return Bundle.main.object(forInfoDictionaryKey: "NCAppGroupIdentifier") as? String ?? "group.com.nextcloud.Talk"
|
||||
}
|
||||
|
||||
static func loadData() -> ConversationsWidgetData? {
|
||||
return ConversationsWidgetData.load(appGroupIdentifier: appGroupIdentifier)
|
||||
}
|
||||
|
||||
static func avatar(named fileName: String?) -> UIImage? {
|
||||
guard let fileName,
|
||||
let fileURL = ConversationsWidgetData.avatarsDirectoryURL(appGroupIdentifier: appGroupIdentifier)?.appendingPathComponent(fileName)
|
||||
else { return nil }
|
||||
|
||||
return UIImage(contentsOfFile: fileURL.path)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Preview data
|
||||
|
||||
extension ConversationsWidgetData {
|
||||
|
||||
static let preview = ConversationsWidgetData(server: "", userId: "", conversations: [
|
||||
.init(id: "1", token: "1", displayName: "Design team", unreadMessages: 3, unreadMention: true, isFavorite: true, hasCall: false, avatarFileName: nil),
|
||||
.init(id: "2", token: "2", displayName: "Alice", unreadMessages: 1, unreadMention: false, isFavorite: true, hasCall: false, avatarFileName: nil),
|
||||
.init(id: "3", token: "3", displayName: "Weekly sync", unreadMessages: 0, unreadMention: false, isFavorite: false, hasCall: true, avatarFileName: nil),
|
||||
.init(id: "4", token: "4", displayName: "Bob", unreadMessages: 0, unreadMention: false, isFavorite: false, hasCall: false, avatarFileName: nil),
|
||||
.init(id: "5", token: "5", displayName: "Support", unreadMessages: 12, unreadMention: false, isFavorite: false, hasCall: false, avatarFileName: nil),
|
||||
.init(id: "6", token: "6", displayName: "Marketing", unreadMessages: 0, unreadMention: false, isFavorite: false, hasCall: false, avatarFileName: nil)
|
||||
], unreadConversations: 3, unreadMentions: 1)
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
extension Color {
|
||||
// The Nextcloud blue
|
||||
static let talkAccent = Color(red: 0, green: 130 / 255, blue: 201 / 255)
|
||||
}
|
||||
|
||||
extension View {
|
||||
|
||||
// iOS 17 requires the widget background to be set like this, so it can be removed e.g. in StandBy
|
||||
@ViewBuilder
|
||||
func widgetBackground<Background: View>(@ViewBuilder _ background: () -> Background) -> some View {
|
||||
if #available(iOSApplicationExtension 17.0, *) {
|
||||
self.containerBackground(for: .widget, content: background)
|
||||
} else {
|
||||
self.background(background())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import WidgetKit
|
||||
|
||||
// Lock screen widget with the number of unread conversations and mentions
|
||||
struct UnreadConversationsWidget: Widget {
|
||||
|
||||
var body: some WidgetConfiguration {
|
||||
StaticConfiguration(kind: ConversationsWidgetData.unreadWidgetKind, provider: ConversationsProvider()) { entry in
|
||||
UnreadConversationsWidgetView(entry: entry)
|
||||
.widgetBackground { Color.clear }
|
||||
.widgetURL(URL(string: "nextcloudtalk://"))
|
||||
}
|
||||
.configurationDisplayName(NSLocalizedString("Unread conversations", comment: "Name of the widget"))
|
||||
.description(NSLocalizedString("The number of conversations with unread messages and mentions.", comment: "Description of the unread conversations widget"))
|
||||
.supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryInline])
|
||||
}
|
||||
}
|
||||
|
||||
struct UnreadConversationsWidgetView: View {
|
||||
|
||||
@Environment(\.widgetFamily) private var family
|
||||
|
||||
let entry: ConversationsEntry
|
||||
|
||||
private var unreadConversations: Int { entry.data?.unreadConversations ?? 0 }
|
||||
private var unreadMentions: Int { entry.data?.unreadMentions ?? 0 }
|
||||
|
||||
var body: some View {
|
||||
switch family {
|
||||
case .accessoryCircular:
|
||||
ZStack {
|
||||
AccessoryWidgetBackground()
|
||||
VStack(spacing: 0) {
|
||||
Image(systemName: unreadMentions > 0 ? "at" : "bubble.left.and.bubble.right.fill")
|
||||
.font(.caption)
|
||||
Text("\(unreadConversations)")
|
||||
.font(.system(.title3, design: .rounded).weight(.semibold))
|
||||
.minimumScaleFactor(0.5)
|
||||
}
|
||||
}
|
||||
case .accessoryRectangular:
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Label("Talk", systemImage: "bubble.left.and.bubble.right.fill")
|
||||
.font(.headline)
|
||||
Text(String(format: NSLocalizedString("Unread: %ld", comment: "Number of conversations with unread messages"), unreadConversations))
|
||||
Text(String(format: NSLocalizedString("Mentions: %ld", comment: "Number of conversations with unread mentions"), unreadMentions))
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
default:
|
||||
Label(String(format: NSLocalizedString("Unread: %ld", comment: "Number of conversations with unread messages"), unreadConversations),
|
||||
systemImage: "bubble.left.and.bubble.right.fill")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user