added iOS source code
[wl-app.git] / iOS / Pods / Realm / Realm / RLMSyncConfiguration.mm
1 ////////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright 2016 Realm Inc.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 ////////////////////////////////////////////////////////////////////////////
18
19 #import "RLMSyncConfiguration_Private.hpp"
20
21 #import "RLMSyncManager_Private.h"
22 #import "RLMSyncSession_Private.hpp"
23 #import "RLMSyncSessionRefreshHandle.hpp"
24 #import "RLMSyncUser_Private.hpp"
25 #import "RLMSyncUtil_Private.hpp"
26 #import "RLMUtil.hpp"
27
28 #import "sync/sync_manager.hpp"
29 #import "sync/sync_config.hpp"
30
31 #import <realm/sync/protocol.hpp>
32
33 using namespace realm;
34
35 namespace {
36 using ProtocolError = realm::sync::ProtocolError;
37
38 RLMSyncSystemErrorKind errorKindForSyncError(SyncError error) {
39     if (error.is_client_reset_requested()) {
40         return RLMSyncSystemErrorKindClientReset;
41     } else if (error.error_code == ProtocolError::permission_denied) {
42         return RLMSyncSystemErrorKindPermissionDenied;
43     } else if (error.error_code == ProtocolError::bad_authentication) {
44         return RLMSyncSystemErrorKindUser;
45     } else if (error.is_session_level_protocol_error()) {
46         return RLMSyncSystemErrorKindSession;
47     } else if (error.is_connection_level_protocol_error()) {
48         return RLMSyncSystemErrorKindConnection;
49     } else if (error.is_client_error()) {
50         return RLMSyncSystemErrorKindClient;
51     } else {
52         return RLMSyncSystemErrorKindUnknown;
53     }
54 }
55 }
56
57 static BOOL isValidRealmURL(NSURL *url) {
58     NSString *scheme = [url scheme];
59     if (![scheme isEqualToString:@"realm"] && ![scheme isEqualToString:@"realms"]) {
60         return NO;
61     }
62     return YES;
63 }
64
65 @interface RLMSyncConfiguration () {
66     std::unique_ptr<realm::SyncConfig> _config;
67 }
68
69 - (instancetype)initWithUser:(RLMSyncUser *)user
70                     realmURL:(NSURL *)url
71                customFileURL:(nullable NSURL *)customFileURL
72                    isPartial:(BOOL)isPartial
73                   stopPolicy:(RLMSyncStopPolicy)stopPolicy
74                 errorHandler:(std::function<realm::SyncSessionErrorHandler>)errorHandler;
75 @end
76
77 @implementation RLMSyncConfiguration
78
79 @dynamic stopPolicy;
80
81 - (instancetype)initWithRawConfig:(realm::SyncConfig)config {
82     if (self = [super init]) {
83         _config = std::make_unique<realm::SyncConfig>(config);
84     }
85     return self;
86 }
87
88 - (BOOL)isEqual:(id)object {
89     if (![object isKindOfClass:[RLMSyncConfiguration class]]) {
90         return NO;
91     }
92     RLMSyncConfiguration *that = (RLMSyncConfiguration *)object;
93     return [self.realmURL isEqual:that.realmURL]
94         && [self.user isEqual:that.user]
95         && self.stopPolicy == that.stopPolicy;
96 }
97
98 - (void)setEnableSSLValidation:(BOOL)enableSSLValidation {
99     _config->client_validate_ssl = (bool)enableSSLValidation;
100 }
101
102 - (BOOL)enableSSLValidation {
103     return (BOOL)_config->client_validate_ssl;
104 }
105
106 - (void)setIsPartial:(BOOL)isPartial {
107     _config->is_partial = (bool)isPartial;
108 }
109
110 - (BOOL)isPartial {
111     return (BOOL)_config->is_partial;
112 }
113
114 - (realm::SyncConfig)rawConfiguration {
115     return *_config;
116 }
117
118 - (RLMSyncUser *)user {
119     return [[RLMSyncUser alloc] initWithSyncUser:_config->user];
120 }
121
122 - (RLMSyncStopPolicy)stopPolicy {
123     return translateStopPolicy(_config->stop_policy);
124 }
125
126 - (void)setStopPolicy:(RLMSyncStopPolicy)stopPolicy {
127     _config->stop_policy = translateStopPolicy(stopPolicy);
128 }
129
130 - (NSURL *)realmURL {
131     NSString *rawStringURL = @(_config->realm_url().c_str());
132     return [NSURL URLWithString:rawStringURL];
133 }
134
135 - (instancetype)initWithUser:(RLMSyncUser *)user realmURL:(NSURL *)url {
136     return [self initWithUser:user
137                      realmURL:url
138                 customFileURL:nil
139                     isPartial:NO
140                    stopPolicy:RLMSyncStopPolicyAfterChangesUploaded
141                  errorHandler:nullptr];
142 }
143
144 - (instancetype)initWithUser:(RLMSyncUser *)user
145                     realmURL:(NSURL *)url
146                customFileURL:(nullable NSURL *)customFileURL
147                    isPartial:(BOOL)isPartial
148                   stopPolicy:(RLMSyncStopPolicy)stopPolicy
149                 errorHandler:(std::function<realm::SyncSessionErrorHandler>)errorHandler {
150     if (self = [super init]) {
151         if (!isValidRealmURL(url)) {
152             @throw RLMException(@"The provided URL (%@) was not a valid Realm URL.", [url absoluteString]);
153         }
154         auto bindHandler = [=](auto&,
155                                const SyncConfig& config,
156                                const std::shared_ptr<SyncSession>& session) {
157             const std::shared_ptr<SyncUser>& user = config.user;
158             NSURL *realmURL = [NSURL URLWithString:@(config.realm_url().c_str())];
159             NSString *path = [realmURL path];
160             REALM_ASSERT(realmURL && path);
161             RLMSyncSessionRefreshHandle *handle = [[RLMSyncSessionRefreshHandle alloc] initWithRealmURL:realmURL
162                                                                                                    user:user
163                                                                                                 session:std::move(session)
164                                                                                         completionBlock:[RLMSyncManager sharedManager].sessionCompletionNotifier];
165             context_for(user).register_refresh_handle([path UTF8String], handle);
166         };
167         if (!errorHandler) {
168             errorHandler = [=](std::shared_ptr<SyncSession> errored_session,
169                                SyncError error) {
170                 RLMSyncSession *session = [[RLMSyncSession alloc] initWithSyncSession:errored_session];
171                 NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:error.user_info.size()];
172                 for (auto& pair : error.user_info) {
173                     userInfo[@(pair.first.c_str())] = @(pair.second.c_str());
174                 }
175                 // FIXME: how should the binding respond if the `is_fatal` bool is true?
176                 [[RLMSyncManager sharedManager] _fireErrorWithCode:error.error_code.value()
177                                                            message:@(error.message.c_str())
178                                                            isFatal:error.is_fatal
179                                                            session:session
180                                                           userInfo:userInfo
181                                                         errorClass:errorKindForSyncError(error)];
182             };
183         }
184
185         _config = std::make_unique<SyncConfig>(SyncConfig{
186             [user _syncUser],
187             [[url absoluteString] UTF8String]
188         });
189         _config->stop_policy = translateStopPolicy(stopPolicy);
190         _config->bind_session_handler = std::move(bindHandler);
191         _config->error_handler = std::move(errorHandler);
192         _config->is_partial = isPartial;
193         self.customFileURL = customFileURL;
194         return self;
195     }
196     return nil;
197 }
198
199 @end