/* Copyright 2016 OpenMarket Ltd Copyright 2018 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #import "MXKAuthenticationRecaptchaWebView.h" NSString *kMXKRecaptchaHTMLString = @" \ \ \ \ \ \
\ \ \ "; @interface MXKAuthenticationRecaptchaWebView () { // The block called when the reCAPTCHA response is received void (^onResponse)(NSString *); // Activity indicator UIActivityIndicatorView *activityIndicator; } @end @implementation MXKAuthenticationRecaptchaWebView - (void)dealloc { if (activityIndicator) { [activityIndicator removeFromSuperview]; activityIndicator = nil; } } - (void)openRecaptchaWidgetWithSiteKey:(NSString*)siteKey fromHomeServer:(NSString*)homeServer callback:(void (^)(NSString *response))callback { self.navigationDelegate = self; onResponse = callback; // Add activity indicator activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; activityIndicator.center = self.center; [self addSubview:activityIndicator]; [activityIndicator startAnimating]; NSString *htmlString = [NSString stringWithFormat:kMXKRecaptchaHTMLString, siteKey]; [self loadHTMLString:htmlString baseURL:[NSURL URLWithString:homeServer]]; } #pragma mark - WKNavigationDelegate - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { if (activityIndicator) { [activityIndicator stopAnimating]; [activityIndicator removeFromSuperview]; activityIndicator = nil; } } - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *urlString = navigationAction.request.URL.absoluteString; if ([urlString hasPrefix:@"js:"]) { // Listen only to scheme of the JS-WKWebView bridge NSString *jsonString = [[[urlString componentsSeparatedByString:@"js:"] lastObject] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *error; NSDictionary *parameters = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; if (!error) { if ([@"verifyCallback" isEqualToString:parameters[@"action"]]) { // Transfer the reCAPTCHA response onResponse(parameters[@"response"]); } } decisionHandler(WKNavigationActionPolicyCancel); return; } decisionHandler(WKNavigationActionPolicyAllow); } @end