<commit_before>library trails;

import "dart:io";
import "dart:async";
import "dart:convert";
import 'package:http_server/http_server.dart';
import "package:rikulo_security/plugin.dart";
import "package:rikulo_security/security.dart";
import "package:stream/stream.dart";
import "package:rikulo_commons/convert.dart" ;
import "package:gps_trace/gps_trace.dart";

import  "../web/shared/forms.dart";
import  "../web/client/renderers.dart";
import  "models.dart";
import  "persistence.dart";
import  "aaa.dart";

part "../web/rsp/login.rsp.dart";
part "../web/rsp/about.rsp.dart" ;
part "../web/rsp/register.rsp.dart";
part "../web/rsp/index.rsp.dart";
part "../web/rsp/traceAddFormView.rsp.dart" ;
part "../web/rsp/traceView.rsp.dart" ;
part "../web/rsp/traceFormatGpxView.rsp.dart" ;
part "../web/rsp/traceSearchView.rsp.dart" ;
part "../web/rsp/disclaimer.rsp.dart" ;
part "../web/rsp/templates/spaces.rsp.dart";
part "../web/rsp/templates/loading.rsp.dart";
part "../web/rsp/templates/menu.rsp.dart";
part "../web/rsp/templates/center.rsp.dart";
part "../web/rsp/templates/loginForm.rsp.dart";
part "../web/rsp/templates/traceGpxViewer.rsp.dart";
part "../web/rsp/templates/traceProfileViewer.rsp.dart";
part "../web/rsp/templates/traceStatisticsViewer.rsp.dart";
part "../web/rsp/templates/persistentMenu.rsp.dart";
part "../web/rsp/templates/searchForm.rsp.dart";
part "../web/rsp/templates/searchResults.rsp.dart";
part "../web/rsp/templates/searchResultsOnMap.rsp.dart";

class TraceController{
  
  PersistenceLayer _persistence ;
  Crypto _crypto ;
  Security _security ;
  String _appUri ;
  
  TraceController(this._persistence, this._crypto, this._appUri){

    final authenticator = new Authentication(_persistence,_crypto) ;
    final accessControl = new SimpleAccessControl({
      "/.*": ["user", "admin"]
    });
  
    _security = new Security(authenticator, accessControl);
    
  }
  
  Security get security => _security ;
  
  
  Future aRegister(HttpConnect connect) {
    
    return _decodePostedJson(connect.request,
                        new Map.from(connect.request.uri.queryParameters))
                             .then((Map params) {

      final RegisterForm form = new RegisterForm.fromMap(params );
      if ( !form.validate() ){
        return _writeFormIntoResponse(connect.response, form);
      }else{
        return  _persistence.getUserByLogin(form.login).then((user){
            if (user != null){
              
              form.setErrorLoginExists();
              return _writeFormIntoResponse(connect.response, form); 
              
            }else{   
              
              User user = new User.withLogin(form.login,_crypto.encryptPassword(form.password));
              print ("# Register user "+ user.toJson().toString());
              return _persistence.saveOrUpdateUser(user)
                .then((_){
                return _writeFormIntoResponse(connect.response, form);                        
              });
            }
          });
      }
    });
  }
  
  Future aTraceSearch(HttpConnect connect) {
    return _decodePostedJson(connect.request,
        new Map.from(connect.request.uri.queryParameters))
        .then((Map params) {

          final SearchForm form = new SearchForm.fromMap(params );
            SearchFilters filters = new SearchFilters();
            filters.search = form.search;
            filters.creator = form.creator;
            filters.activities = form.activities;
                        
            filters.lengthGt = castToNum(form.lengthGt,1000) ;
            filters.upGt  = castToNum(form.upGt,1) ;
            filters.inclinationUpGt = castToNum(form.inclinationUpGt,1);
            filters.startPointElevetionGt = castToNum(form.startPointElevetionGt,1);
            filters.upperPointElevetionGt = castToNum(form.upperPointElevetionGt,1);
            filters.difficultyGt = castToNum(form.difficultyGt,1);
            filters.lengthLt = castToNum(form.lengthLt,1000);
            filters.upLt  = castToNum(form.upLt,1);
            filters.inclinationUpLt = castToNum(form.inclinationUpLt,1);
            filters.startPointElevetionLt = castToNum(form.startPointElevetionLt,1);
            filters.upperPointElevetionLt = castToNum(form.upperPointElevetionLt,1);
            filters.difficultyLt = castToNum(form.difficultyLt,1);
            
            filters.mapBoundNELat = form.mapBoundNELat ;
            filters.mapBoundNELong  = form.mapBoundNELong ;
            filters.mapBoundSWLat  = form.mapBoundSWLat ;
            filters.mapBoundSWLong  = form.mapBoundSWLong ;
            
            return  _persistence.getTracesByFilters(filters).then((traces){
              form.results = new List();
              if (traces != null){
                traces.forEach((trace){
                    LigthTraceRenderer traceLightRenderer = new LigthTraceRenderer(trace);
                    LightTrace  lightTrace = new   LightTrace(traceLightRenderer.key, traceLightRenderer.creator, traceLightRenderer.titleWithUrl, traceLightRenderer.activities, 
                        traceLightRenderer.length, traceLightRenderer.up, traceLightRenderer.upperPointElevetion, 
                        traceLightRenderer.inclinationUp, traceLightRenderer.difficulty,
                        traceLightRenderer.trace.startPointLatitude,traceLightRenderer.trace.startPointLongitude );
                    form.results.add(lightTrace) ;
                });
              }
              return _writeFormIntoResponse(connect.response, form); 
            });
          
        });
  }
  
  num castToNum(String value, int times){
    if (value == null){
      return null;
    }else{
      try{
        return double.parse(value)* times;
      }catch(e){
        return null;
      }
    }
  }
  
  Future<Map> _decodePostedJson(
      Stream<List<int>> request, [Map<String, String> parameters])
      => readAsString(request)
         .then((String data) {
          return JSON.decode(data); 
   });
  
  Future _writeFormIntoResponse(HttpResponse response, form){
    response
      ..headers.contentType = new ContentType("application", "json", charset: "utf-8");
      ..write( JSON.encode( form.toJson()) );  
    return new Future.value(); 
  }
  
  Future login(HttpConnect connect) {
    return _security.login(connect);
  }
  <commit_msg>Update controllers.dart<commit_after>library trails;

import "dart:io";
import "dart:async";
import "dart:convert";
import 'package:http_server/http_server.dart';
import "package:rikulo_security/plugin.dart";
import "package:rikulo_security/security.dart";
import "package:stream/stream.dart";
import "package:rikulo_commons/convert.dart" ;
import "package:gps_trace/gps_trace.dart";

import  "../web/shared/forms.dart";
import  "../web/client/renderers.dart";
import  "models.dart";
import  "persistence.dart";
import  "aaa.dart";

part "../web/rsp/login.rsp.dart";
part "../web/rsp/about.rsp.dart" ;
part "../web/rsp/register.rsp.dart";
part "../web/rsp/index.rsp.dart";
part "../web/rsp/traceAddFormView.rsp.dart" ;
part "../web/rsp/traceView.rsp.dart" ;
part "../web/rsp/traceFormatGpxView.rsp.dart" ;
part "../web/rsp/traceSearchView.rsp.dart" ;
part "../web/rsp/disclaimer.rsp.dart" ;
part "../web/rsp/templates/spaces.rsp.dart";
part "../web/rsp/templates/loading.rsp.dart";
part "../web/rsp/templates/menu.rsp.dart";
part "../web/rsp/templates/center.rsp.dart";
part "../web/rsp/templates/loginForm.rsp.dart";
part "../web/rsp/templates/traceGpxViewer.rsp.dart";
part "../web/rsp/templates/traceProfileViewer.rsp.dart";
part "../web/rsp/templates/traceStatisticsViewer.rsp.dart";
part "../web/rsp/templates/persistentMenu.rsp.dart";
part "../web/rsp/templates/searchForm.rsp.dart";
part "../web/rsp/templates/searchResults.rsp.dart";
part "../web/rsp/templates/searchResultsOnMap.rsp.dart";

class TraceController{
  
  PersistenceLayer _persistence ;
  Crypto _crypto ;
  Security _security ;
  String _appUri ;
  
  TraceController(this._persistence, this._crypto, this._appUri){

    final authenticator = new Authentication(_persistence,_crypto) ;
    final accessControl = new SimpleAccessControl({
      "/.*": ["user", "admin"]
    });
  
    _security = new Security(authenticator, accessControl);
    
  }
  
  Security get security => _security ;
  
  
  Future aRegister(HttpConnect connect) {
    
    return _decodePostedJson(connect.request,
                        new Map.from(connect.request.uri.queryParameters))
                             .then((Map params) {

      final RegisterForm form = new RegisterForm.fromMap(params );
      if ( !form.validate() ){
        return _writeFormIntoResponse(connect.response, form);
      }else{
        return  _persistence.getUserByLogin(form.login).then((user){
            if (user != null){
              
              form.setErrorLoginExists();
              return _writeFormIntoResponse(connect.response, form); 
              
            }else{   
              
              User user = new User.withLogin(form.login,_crypto.encryptPassword(form.password));
              print ("# Register user "+ user.toJson().toString());
              return _persistence.saveOrUpdateUser(user)
                .then((_){
                return _writeFormIntoResponse(connect.response, form);                        
              });
            }
          });
      }
    });
  }
  
  Future aTraceSearch(HttpConnect connect) {
    return _decodePostedJson(connect.request,
        new Map.from(connect.request.uri.queryParameters))
        .then((Map params) {

          final SearchForm form = new SearchForm.fromMap(params );
            SearchFilters filters = new SearchFilters();
            filters.search = form.search;
            filters.creator = form.creator;
            filters.activities = form.activities;
                        
            filters.lengthGt = castToNum(form.lengthGt,1000) ;
            filters.upGt  = castToNum(form.upGt,1) ;
            filters.inclinationUpGt = castToNum(form.inclinationUpGt,1);
            filters.startPointElevetionGt = castToNum(form.startPointElevetionGt,1);
            filters.upperPointElevetionGt = castToNum(form.upperPointElevetionGt,1);
            filters.difficultyGt = castToNum(form.difficultyGt,1);
            filters.lengthLt = castToNum(form.lengthLt,1000);
            filters.upLt  = castToNum(form.upLt,1);
            filters.inclinationUpLt = castToNum(form.inclinationUpLt,1);
            filters.startPointElevetionLt = castToNum(form.startPointElevetionLt,1);
            filters.upperPointElevetionLt = castToNum(form.upperPointElevetionLt,1);
            filters.difficultyLt = castToNum(form.difficultyLt,1);
            
            filters.mapBoundNELat = form.mapBoundNELat ;
            filters.mapBoundNELong  = form.mapBoundNELong ;
            filters.mapBoundSWLat  = form.mapBoundSWLat ;
            filters.mapBoundSWLong  = form.mapBoundSWLong ;
            
            return  _persistence.getTracesByFilters(filters).then((traces){
              form.results = new List();
              if (traces != null){
                traces.forEach((trace){
                    LigthTraceRenderer traceLightRenderer = new LigthTraceRenderer(trace);
                    LightTrace  lightTrace = new   LightTrace(traceLightRenderer.key, traceLightRenderer.creator, traceLightRenderer.titleWithUrl, traceLightRenderer.activities, 
                        traceLightRenderer.length, traceLightRenderer.up, traceLightRenderer.upperPointElevetion, 
                        traceLightRenderer.inclinationUp, traceLightRenderer.difficulty,
                        traceLightRenderer.trace.startPointLatitude,traceLightRenderer.trace.startPointLongitude );
                    form.results.add(lightTrace) ;
                });
              }
              return _writeFormIntoResponse(connect.response, form); 
            });
          
        });
  }
  
  num castToNum(String value, int times){
    if (value == null){
      return null;
    }else{
      try{
        return double.parse(value)* times;
      }catch(e){
        return null;
      }
    }
  }
  
  Future<Map> _decodePostedJson(
      Stream<List<int>> request, [Map<String, String> parameters])
      => readAsString(request)
         .then((String data) {
          return JSON.decode(data); 
   });
  
  Future _writeFormIntoResponse(HttpResponse response, form){
    response
      ..headers.contentType = new ContentType("application", "json", charset: "utf-8")
      ..write( JSON.encode( form.toJson()) );  
    return new Future.value(); 
  }
  
  Future login(HttpConnect connect) {
    return _security.login(connect);
  }
  
{'fraction_non_alphanumeric': 0.12200298718654194, 'fraction_numerical': 0.002987186541938527, 'mean_word_length': 2.476906258540585, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5962683', 'n_tokens_mistral': 3786, 'n_tokens_neox': 3812, 'n_words': 571}