summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/private/SDLVoiceCommandUpdateOperation.m
blob: 184615d635346b42e4a3b0dedd638b2d62ea0408 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//
//  SDLVoiceCommandUpdateOperation.m
//  SmartDeviceLink
//
//  Created by Joel Fischer on 11/6/20.
//  Copyright © 2020 smartdevicelink. All rights reserved.
//

#import "SDLVoiceCommandUpdateOperation.h"

#import "SDLAddCommand.h"
#import "SDLConnectionManagerType.h"
#import "SDLDeleteCommand.h"
#import "SDLError.h"
#import "SDLLogMacros.h"
#import "SDLVoiceCommand.h"

NS_ASSUME_NONNULL_BEGIN

@interface SDLVoiceCommand()

@property (assign, nonatomic) UInt32 commandId;

@end

@interface SDLVoiceCommandUpdateOperation ()

@property (weak, nonatomic) id<SDLConnectionManagerType> connectionManager;
@property (copy, nonatomic) NSArray<SDLVoiceCommand *> *pendingVoiceCommands;
@property (strong, nonatomic) NSMutableArray<SDLVoiceCommand *> *currentVoiceCommands;
@property (copy, nonatomic) SDLVoiceCommandUpdateCompletionHandler completionHandler;

@property (copy, nonatomic, nullable) NSError *internalError;

@end

@implementation SDLVoiceCommandUpdateOperation

- (instancetype)initWithConnectionManager:(id<SDLConnectionManagerType>)connectionManager pendingVoiceCommands:(NSArray<SDLVoiceCommand *> *)pendingVoiceCommands oldVoiceCommands:(NSArray<SDLVoiceCommand *> *)oldVoiceCommands updateCompletionHandler:(SDLVoiceCommandUpdateCompletionHandler)completionHandler {
    self = [self init];
    if (!self) { return nil; }

    _connectionManager = connectionManager;
    _pendingVoiceCommands = pendingVoiceCommands;
    _oldVoiceCommands = oldVoiceCommands;
    _currentVoiceCommands = oldVoiceCommands.mutableCopy;
    _completionHandler = completionHandler;

    return self;
}

- (void)start {
    [super start];
    if (self.isCancelled) {
        [self finishOperation];
        return;
    }

    __weak typeof(self) weakSelf = self;
    [self sdl_sendDeleteCurrentVoiceCommands:^{
        // If the operation has been canceled, then don't send the new commands and finish the operation
        if (self.isCancelled) {
            [weakSelf finishOperation];
            return;
        }

        // Send the new commands
        [weakSelf sdl_sendCurrentVoiceCommands:^{
            [weakSelf finishOperation];
        }];
    }];
}

#pragma mark - Sending RPCs

/// Send DeleteCommand RPCs for voice commands that should be deleted
/// @param completionHandler A handler called when all DeleteCommands have completed
- (void)sdl_sendDeleteCurrentVoiceCommands:(void(^)(void))completionHandler {
    if (self.oldVoiceCommands.count == 0) {
        SDLLogD(@"No voice commands to delete");
        return completionHandler();
    }

    NSArray<SDLDeleteCommand *> *deleteVoiceCommands = [self sdl_deleteCommandsForVoiceCommands:self.oldVoiceCommands];
    __block NSMutableDictionary<SDLDeleteCommand *, NSError *> *errors = [NSMutableDictionary dictionary];
    __weak typeof(self) weakSelf = self;
    [self.connectionManager sendRequests:deleteVoiceCommands progressHandler:^(__kindof SDLRPCRequest * _Nonnull request, __kindof SDLRPCResponse * _Nullable response, NSError * _Nullable error, float percentComplete) {
        // Add the request to the error dict or remove it from the current voice commands array
        if (error != nil) {
            errors[request] = error;
        } else {
            [weakSelf sdl_removeCurrentVoiceCommandWithCommandId:((SDLDeleteCommand *)request).cmdID.unsignedIntValue];
        }

        SDLLogV(@"Deleting voice commands progress: %f", percentComplete);
    } completionHandler:^(BOOL success) {
        if (!success) {
            SDLLogE(@"Failed to send voice commands: %@", errors.allKeys);
            SDLLogE(@"Failure reasons: %@", errors.allValues);
            weakSelf.internalError = [NSError sdl_menuManager_failedToUpdateWithDictionary:errors];
            return completionHandler();
        }

        SDLLogD(@"Finished deleting old voice commands");
        return completionHandler();
    }];
}

/// Send AddCommand RPCs for voice commands that should be added
/// @param completionHandler A handler called when all AddCommands have completed
- (void)sdl_sendCurrentVoiceCommands:(void(^)(void))completionHandler {
    if (self.pendingVoiceCommands.count == 0) {
        SDLLogD(@"No voice commands to send");
        return completionHandler();
    }

    NSArray<SDLAddCommand *> *addCommandsToSend = [self sdl_addCommandsForVoiceCommands:self.pendingVoiceCommands];
    __block NSMutableDictionary<SDLAddCommand *, NSError *> *errors = [NSMutableDictionary dictionary];
    __weak typeof(self) weakSelf = self;
    [self.connectionManager sendRequests:addCommandsToSend progressHandler:^(__kindof SDLRPCRequest * _Nonnull request, __kindof SDLRPCResponse * _Nullable response, NSError * _Nullable error, float percentComplete) {
        // Add the request to the error dict or add it to the current voice commands array
        if (error != nil) {
            errors[request] = error;
        } else {
            [weakSelf.currentVoiceCommands addObject:[weakSelf sdl_pendingVoiceCommandWithCommandId:((SDLAddCommand *)request).cmdID.unsignedIntValue]];
        }

        SDLLogV(@"Sending voice commands progress: %f", percentComplete);
    } completionHandler:^(BOOL success) {
        if (!success) {
            SDLLogE(@"Failed to send voice commands: %@", errors.allKeys);
            SDLLogE(@"Failure reasons: %@", errors.allValues);
            weakSelf.internalError = [NSError sdl_menuManager_failedToUpdateWithDictionary:errors];
            return completionHandler();
        }

        SDLLogD(@"Finished updating voice commands");
        return completionHandler();
    }];
}

#pragma mark - Helpers
#pragma mark Deletes

/// Create DeleteCommand RPCs for passed voice commands
/// @param voiceCommands The voice commands that should be deleted
/// @return The DeleteCommand RPCs for the passed voice commands
- (NSArray<SDLDeleteCommand *> *)sdl_deleteCommandsForVoiceCommands:(NSArray<SDLVoiceCommand *> *)voiceCommands {
    NSMutableArray<SDLDeleteCommand *> *mutableDeletes = [NSMutableArray array];
    for (SDLVoiceCommand *command in voiceCommands) {
        SDLDeleteCommand *delete = [[SDLDeleteCommand alloc] initWithId:command.commandId];
        [mutableDeletes addObject:delete];
    }

    return [mutableDeletes copy];
}

#pragma mark Commands

/// Create AddCommand RPCs for passed voice commands
/// @param voiceCommands The voice commands that should be added
/// @return The AddCommand RPCs for the passed voice commands
- (NSArray<SDLAddCommand *> *)sdl_addCommandsForVoiceCommands:(NSArray<SDLVoiceCommand *> *)voiceCommands {
    NSMutableArray<SDLAddCommand *> *mutableCommands = [NSMutableArray array];
    for (SDLVoiceCommand *voiceCommand in voiceCommands) {
        SDLAddCommand *command = [[SDLAddCommand alloc] init];
        command.vrCommands = voiceCommand.voiceCommands;
        command.cmdID = @(voiceCommand.commandId);

        [mutableCommands addObject:command];
    }

    return [mutableCommands copy];
}

#pragma mark - Managing list of commands on head unit

/// Remove a voice command from the array of voice commands on the head unit based on a command id
/// @param commandId The command id to use to remove a voice command
- (void)sdl_removeCurrentVoiceCommandWithCommandId:(UInt32)commandId {
    for (SDLVoiceCommand *voiceCommand in self.currentVoiceCommands) {
        if (voiceCommand.commandId == commandId) {
            [self.currentVoiceCommands removeObject:voiceCommand];
            break;
        }
    }
}

/// Find a voice command in the pending voice command array based on a command id
/// @param commandId The command id to use to find a voice command
- (nullable SDLVoiceCommand *)sdl_pendingVoiceCommandWithCommandId:(UInt32)commandId {
    for (SDLVoiceCommand *voiceCommand in self.pendingVoiceCommands) {
        if (voiceCommand.commandId == commandId) {
            return voiceCommand;
        }
    }

    return nil;
}

#pragma mark - Operation Overrides

- (void)finishOperation {
    SDLLogV(@"Finishing voice command update operation");
    if (self.isCancelled) {
        self.internalError = [NSError sdl_voiceCommandManager_pendingUpdateSuperseded];
    }

    self.completionHandler(self.currentVoiceCommands.copy, self.error);
    [super finishOperation];
}

- (nullable NSString *)name {
    return @"com.sdl.voicecommand.update";
}

- (NSOperationQueuePriority)queuePriority {
    return NSOperationQueuePriorityNormal;
}

- (nullable NSError *)error {
    return self.internalError;
}

@end

NS_ASSUME_NONNULL_END