<commit_before>/*
Copyright 2014 OpenMarket 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.
*/

'use strict';

/*
This service wraps up Matrix API calls. 

This serves to isolate the caller from changes to the underlying url paths, as
well as attach common params (e.g. access_token) to requests.
*/
angular.module('matrixService', [])
.factory('matrixService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope) {
        
   /* 
    * Permanent storage of user information
    * The config contains:
    *    - homeserver url
    *    - Identity server url
    *    - user_id
    *    - access_token
    *    - version: the version of this cache
    */    
    var config;
    
    var roomIdToAlias = {};
    var aliasToRoomId = {};
    
    // Current version of permanent storage
    var configVersion = 0;
    var prefixPath = "/_matrix/client/api/v1";
    var MAPPING_PREFIX = "alias_for_";

    var doRequest = function(method, path, params, data, $httpParams) {
        if (!config) {
            console.warn("No config exists. Cannot perform request to "+path);
            return;
        }
    
        // Inject the access token
        if (!params) {
            params = {};
        }
        
        params.access_token = config.access_token;
        
        if (path.indexOf(prefixPath) !== 0) {
            path = prefixPath + path;
        }
        
        return doBaseRequest(config.homeserver, method, path, params, data, undefined, $httpParams);
    };

    var doBaseRequest = function(baseUrl, method, path, params, data, headers, $httpParams) {

        var request = {
            method: method,
            url: baseUrl + path,
            params: params,
            data: data,
            headers: headers
        };

        // Add additional $http parameters
        if ($httpParams) {
            angular.extend(request, $httpParams);
        }

        return $http(request);
    };

    return {
        /****** Home server API ******/
        prefix: prefixPath,

        // Register an user
        register: function(user_name, password, threepidCreds, useCaptcha) {         
            // The REST path spec
            var path = "/register";
            
            var data = {
                 user_id: user_name,
                 password: password,
                 threepidCreds: threepidCreds
            };
            
            if (useCaptcha) {
                // Not all home servers will require captcha on signup, but if this flag is checked,
                // send captcha information.
                // TODO: Might be nice to make this a bit more flexible..
                var challengeToken = Recaptcha.get_challenge();
                var captchaEntry = Recaptcha.get_response();
                var captchaType = "m.login.recaptcha";
                
                data.captcha = {
                    type: captchaType,
                    challenge: challengeToken,
                    response: captchaEntry
                };
            }   

            return doRequest("POST", path, undefined, data);
        },

        // Create a room
        create: function(room_alias, visibility) {
            // The REST path spec
            var path = "/createRoom";

            var req = {
                "visibility": visibility
            };
            if (room_alias) {
                req.room_alias_name = room_alias;
            }
            
            return doRequest("POST", path, undefined, req);
        },

        // Get the user's current state: his presence, the list of his rooms with
        // the last {limit} events
        initialSync: function(limit, feedback) {
            // The REST path spec

            var path = "/initialSync";

            var params = {};
            if (limit) {
                params.limit = limit;<commit_msg>Updated webclient to support the new registration logic.<commit_after>/*
Copyright 2014 OpenMarket 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.
*/

'use strict';

/*
This service wraps up Matrix API calls. 

This serves to isolate the caller from changes to the underlying url paths, as
well as attach common params (e.g. access_token) to requests.
*/
angular.module('matrixService', [])
.factory('matrixService', ['$http', '$q', '$rootScope', function($http, $q, $rootScope) {
        
   /* 
    * Permanent storage of user information
    * The config contains:
    *    - homeserver url
    *    - Identity server url
    *    - user_id
    *    - access_token
    *    - version: the version of this cache
    */    
    var config;
    
    var roomIdToAlias = {};
    var aliasToRoomId = {};
    
    // Current version of permanent storage
    var configVersion = 0;
    var prefixPath = "/_matrix/client/api/v1";
    var MAPPING_PREFIX = "alias_for_";

    var doRequest = function(method, path, params, data, $httpParams) {
        if (!config) {
            console.warn("No config exists. Cannot perform request to "+path);
            return;
        }
    
        // Inject the access token
        if (!params) {
            params = {};
        }
        
        params.access_token = config.access_token;
        
        if (path.indexOf(prefixPath) !== 0) {
            path = prefixPath + path;
        }
        
        return doBaseRequest(config.homeserver, method, path, params, data, undefined, $httpParams);
    };

    var doBaseRequest = function(baseUrl, method, path, params, data, headers, $httpParams) {

        var request = {
            method: method,
            url: baseUrl + path,
            params: params,
            data: data,
            headers: headers
        };

        // Add additional $http parameters
        if ($httpParams) {
            angular.extend(request, $httpParams);
        }

        return $http(request);
    };
    
    var doRegisterLogin = function(path, loginType, sessionId, userName, password, threepidCreds) {
        var data = {};
        if (loginType === "m.login.recaptcha") {
            var challengeToken = Recaptcha.get_challenge();
            var captchaEntry = Recaptcha.get_response();
            data = {
                type: "m.login.recaptcha",
                challenge: challengeToken,
                response: captchaEntry
            };
        }
        else if (loginType === "m.login.email.identity") {
            data = {
                threepidCreds: threepidCreds
            };
        }
        else if (loginType === "m.login.password") {
            data = {
                user_id: userName,
                password: password
            };
        }
        
        if (sessionId) {
            data.session = sessionId;
        }
        data.type = loginType;
        console.log("doRegisterLogin >>> " + loginType);
        return doRequest("POST", path, undefined, data);
    };

    return {
        /****** Home server API ******/
        prefix: prefixPath,

        // Register an user
        register: function(user_name, password, threepidCreds, useCaptcha) {
            // registration is composed of multiple requests, to check you can
            // register, then to actually register. This deferred will fire when
            // all the requests are done, along with the final response.
            var deferred = $q.defer();
            var path = "/register";
            
            // check we can actually register with this HS.
            doRequest("GET", path, undefined, undefined).then(
                function(response) {
                    console.log("/register [1] : "+JSON.stringify(response));
                    var flows = response.data.flows;
                    var knownTypes = [
                        "m.login.password",
                        "m.login.recaptcha",
                        "m.login.email.identity"
                    ];
                    // if they entered 3pid creds, we want to use a flow which uses it.
                    var useThreePidFlow = threepidCreds != undefined;
                    var flowIndex = 0;
                    var firstRegType = undefined;
                    
                    for (var i=0; i<flows.length; i++) {
                        var isThreePidFlow = false;
                        if (flows[i].stages) {
                            for (var j=0; j<flows[i].stages.length; j++) {
                                var regType = flows[i].stages[j];
                                if (knownTypes.indexOf(regType) === -1) {
                                    deferred.reject("Unknown type: "+regType);
                                    return;
                                }
                                if (regType == "m.login.email.identity") {
                                    isThreePidFlow = true;
                                }
                                if (!useCaptcha && regType == "m.login.recaptcha") {
                                    console.error("Web client setup to not use captcha, but HS demands a captcha.");
                                }
                            }
                        }
                        
                        if ( (isThreePidFlow && useThreePidFlow) || (!isThreePidFlow && !useThreePidFlow) ) {
                            flowIndex = i;
                        }
                        
                        if (knownTypes.indexOf(flows[i].type) == -1) {
                            deferred.reject("Unknown type: "+flows[i].type);
                            return;
                        }
                    }
                    
                    // looks like we can register fine, go ahead and do it.
                    console.log("Using flow " + JSON.stringify(flows[flowIndex]));
                    firstRegType = flows[flowIndex].type;
                    var sessionId = undefined;
                    
                    // generic response processor so it can loop as many times as required
                    var loginResponseFunc = function(response) {
                        if (response.data.session) {
                            sessionId = response.data.session;
                        }
                        console.log("login response: " + JSON.stringify(response.data));
                        if (response.data.access_token) {
                            deferred.resolve(response);
                        }
                        else if (response.data.next) {
                            return doRegisterLogin(path, response.data.next, sessionId, user_name, password, threepidCreds).then(
                                loginResponseFunc,
                                function(err) {
                                    deferred.reject(err);
                                }
                            );
                        }
                        else {
                            deferred.reject("Unknown continuation: "+JSON.stringify(response));
                        }
                    };
                    
                    // set the ball rolling
                    doRegisterLogin(path, firstRegType, undefined, user_name, password, threepidCreds).then(
                        loginResponseFunc,
                        function(err) {
                            deferred.reject(err);
                        }
                    );
                    
                },
                function(err) {
                    deferred.reject(err);
                }
            );
            
            return deferred.promise;
        },

        // Create a room
        create: function(room_alias, visibility) {
            // The REST path spec
            var path = "/createRoom";

            var req = {
                "visibility": visibility
            };
            if (room_alias) {
                req.room_alias_name = room_alias;
            }
            
            return doRequest("POST", path, undefined, req);
        },

        // Get the user's current state: his presence, the list of his rooms with
        // the last {limit} events
        initialSync: function(limit, feedback) {
            // The REST path spec

            var path = "/initialSync";

            var params = {};
            if (limit) {
                params.limit = limit;
{'fraction_non_alphanumeric': 0.09019784849168735, 'fraction_numerical': 0.0021815993379974423, 'mean_word_length': 1.3318716014734258, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '925424', 'n_tokens_mistral': 3320, 'n_tokens_neox': 3127, 'n_words': 972}