Changeset 02fbeb8


Ignore:
Timestamp:
Aug 31, 2015, 11:04:02 PM (11 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
master
Children:
d55ec21
Parents:
69c8290
Message:

Implmented and started testing of /stations/register

Location:
src/webservice
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • src/webservice/htdocs/index.php

    r69c8290 r02fbeb8  
    2828function stations(){
    2929        $stations = Array();
    30 //      $station = Array();
    31 //      $station["id"] = "123456";
    32 //      $station["name"] = "Station Name";
    33 //      $station["longitude"] = 52.320;
    34 //      $station["latitude"] = 48;
    35 //      $station["city"] = "Krefeld";
    36 //      $station["values"] = Array();
    37 //      $station["values"][] = "temperature";
    38 //      $station["values"][] = "humidity";
    39 //      $station["url"] = "stations/". $station["id"];
    40 //      $stations[] = $station;
     30
     31        $db = new SiWeather\Webservice\DatabaseHandler();
     32        if(!$db->connect()){
     33                echo json_encode
     34                (
     35                        [
     36                                "result" => "failed",
     37                                "message" => "Could not connect to the database",
     38                        ]
     39                );
     40                return;
     41        }
     42        $db->exec("BEGIN");
     43
     44        $sqlStatement = $db->prepare("SELECT stations.uuid as uuid, stations.name as name, X(stations.location) as longitude, Y(stations.location) as latitude, cities.name as city FROM stations, cities WHERE stations.city=cities.id");
     45        if(!$sqlStatement){
     46                $db->exec("ROLLBACK");
     47                echo json_encode
     48                (
     49                        [
     50                                "result" => "failed",
     51                                "message" => "Could not fetch stations from database",
     52                        ]
     53                );
     54                return;
     55        }
     56        $result = $sqlStatement->execute();
     57        while($row = $result->fetchArray()){
     58                $station = Array();
     59                $station["uuid"] = $row["uuid"];
     60                $station["name"] = $row["name"];
     61                $station["longitude"] = $row["longitude"];
     62                $station["latitude"] = $row["latitude"];
     63                $station["city"] = $row["city"];
     64//              $station["values"] = Array();
     65//              $station["values"][] = "temperature";
     66//              $station["values"][] = "humidity";
     67                $station["url"] = "stations/". $station["uuid"];
     68                $stations[] = $station;
     69        }
     70        $db->exec("COMMIT");
     71
    4172        echo json_encode($stations);
    4273}
    … …  
    4475/**
    4576  * @brief Registers a new weather station
     77  *
     78  * @note Call this function with a big timeout > 2seconds, because we use another webservice
     79  *       to fetch location data. This fetch runs already 2seconds.
     80        * @note Requires php-pecl-uuid
    4681  */
    4782function stationsRegister(){
     83        $geoLocationRadius = 5;
     84
    4885        try{
    4986                $app = \Slim\Slim::getInstance("siweather");
    … …  
    5390                $app->response()->header("Content-Type", "application/json");
    5491
    55                 $expectedKeys = array("city", "longitude", "latitude");
     92                $expectedKeys = array("name", "city", "longitude", "latitude", "email");
    5693                $missingKeys = array();
    5794                foreach($expectedKeys as $key){
    … …  
    70107                }
    71108
    72                 if(array_key_exists("locationchecked", $json) && $json["locationchecked"]){
    73                         // user has checked the location already and we add it now
    74                        
     109                if(!SiWeather\Webservice\Location::ValidLatitude($json["latitude"])){
     110                        echo json_encode
     111                        (
     112                                [
     113                                        "result" => "invalid latitude",
     114                                        "message" => "Your specified an invalid latitude: ". $json["latitude"],
     115                                ]
     116                        );
     117                        return;
     118                }
     119                if(!SiWeather\Webservice\Location::ValidLongitude($json["longitude"])){
     120                        echo json_encode
     121                        (
     122                                [
     123                                        "result" => "invalid longitude",
     124                                        "message" => "Your specified an invalid longitude: ". $json["longitude"],
     125                                ]
     126                        );
     127                        return;
     128                }
     129                if(empty($json["email"]) || !filter_var($json["email"], FILTER_VALIDATE_EMAIL)){
     130                        echo json_encode
     131                        (
     132                                [
     133                                        "result" => "invalid email",
     134                                        "message" => "Your specified an invalid email address: ". $json["email"],
     135                                ]
     136                        );
     137                        return;
    75138                }
    76139
    77140                $errorMessage = "";
    78                 $location = SiWeather\Webservice\IpGeoLocator::locate($app->request->getIp(), $errorMessage);
    79                 if(is_null($location)){
     141                $locations = SiWeather\Webservice\GeoLocator::locations($json["latitude"], $json["longitude"], $geoLocationRadius, $errorMessage);
     142                if(!$locations || count($locations) < 1){
    80143                        error_log($errorMessage);
    81144                        echo json_encode
    … …  
    83146                                [
    84147                                        "result" => "unprovenlocation",
    85                                         "message" => "Could not check the city (". $json["city"] .") and location (". $json["longitude"] .", ". $json["latitude"] .") you send with help of your ip address. Please make sure, your data is correct. If your data is correct, please resend your request with the keyword \"locationchecked = true\".",
    86                                 ]
    87                         );
    88                         return;
    89                 }
    90                 elseif($location->city() != $json["city"]){
    91                         echo json_encode
    92                         (
    93                                 [
    94                                         "result" => "unprovenlocation",
    95                                         "message" => "The city (". $json[city] .") and location (". $json["longitude"] .", ". $json["latitude"] .") you send, does not suit with your ip address associtated location (city: ". $location->city() ."; Location: ". $location->longitude() .", ". $location->latitude() ."). If your data is correct, please resend your request with the keyword \"locationchecked = true\".",
    96                                 ]
    97                         );
    98                         return;
    99                 }
    100 
    101                 echo json_encode($json);
     148                                        "message" => "Could not check the city (". $json["city"] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send with help of your city and geo coordinates. Please make sure, your data is correct.",
     149                                ]
     150                        );
     151                        return;
     152                }
     153                else{
     154                        $validatedLocation = false;
     155                        foreach($locations as $location){
     156                                if($location->city() == $json["city"]){
     157                                        $validatedLocation = $location;
     158                                }
     159                        }
     160                        if(!$validatedLocation){
     161                                $message  = "The city (". $json[city] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send, does not suite with locations we found at your given location (city, latitude, longitude):\n";
     162                                foreach($locations as $location){
     163                                        $message .= "    ". $location->city() .": ". $location->latitude() .", ". $location->longitude() ."\n";
     164                                }
     165                                $message .= " Please make sure, your data is correct.";
     166
     167                                echo json_encode
     168                                (
     169                                        [
     170                                                "result" => "unprovenlocation",
     171                                                "message" => $message,
     172                                        ]
     173                                );
     174                                return;
     175                        }
     176                }
     177
     178                $db = new SiWeather\Webservice\DatabaseHandler();
     179                if(!$db->connect()){
     180                        echo json_encode
     181                        (
     182                                [
     183                                        "result" => "failed",
     184                                        "message" => "Could not connect to the database",
     185                                ]
     186                        );
     187                        return;
     188                }
     189                $db->exec("BEGIN");
     190
     191                // find out, if the city is already there
     192                $cityId = -1;
     193                $sqlStatement = $db->prepare("SELECT id FROM cities WHERE name=:name AND location=:location");
     194                if(!$sqlStatement){
     195                        $db->exec("ROLLBACK");
     196                        echo json_encode
     197                        (
     198                                [
     199                                        "result" => "failed",
     200                                        "message" => "Could not fetch city from database",
     201                                ]
     202                        );
     203                        return;
     204                }
     205                $sqlStatement->bindValue(":name", $validatedLocation->city());
     206                $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
     207                $result = $sqlStatement->execute();
     208                if($result->numColumns() && $result->columnType(0) != SQLITE3_NULL){
     209                        error_log("not cool");
     210                        $row = $result->fetchArray();
     211                        $cityId = $row[0];
     212                        error_log($row[0]);
     213                }
     214                else{
     215                        $sqlStatement = $db->prepare("INSERT INTO cities (name, location) VALUES(:name, GeomFromText(:location, 4326))");
     216                        if(!$sqlStatement){
     217                                $db->exec("ROLLBACK");
     218                                echo json_encode
     219                                (
     220                                        [
     221                                                "result" => "failed",
     222                                                "message" => "Could insert city into the database",
     223                                        ]
     224                                );
     225                                return;
     226                        }
     227                        $sqlStatement->bindValue(":name", $validatedLocation->city());
     228                        $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
     229                        $sqlResult = $sqlStatement->execute();
     230                        if(!$sqlResult){
     231                                error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage());
     232                                $db->exec("ROLLBACK");
     233                                echo json_encode
     234                                (
     235                                        [
     236                                                "result" => "failed",
     237                                                "message" => "Could not add city to the database",
     238                                        ]
     239                                );
     240                                return;
     241                        }
     242                        $cityId = $db->lastInsertRowId();
     243                }
     244                if($cityId < 0){
     245                        error_log("Failed to select city from the database: ". $db->lastDatabaseErrorMessage());
     246                        $db->exec("ROLLBACK");
     247                        echo json_encode
     248                        (
     249                                [
     250                                        "result" => "failed",
     251                                        "message" => "Could not select city from the database",
     252                                ]
     253                        );
     254                        return;
     255                }
     256
     257                // insert station
     258                $uuid = uuid_create(4);
     259                $sqlStatement = $db->prepare("INSERT INTO stations (name, city, uuid, ownerMail, location) VALUES(:name, :city, :uuid, :ownerMail, GeomFromText(:location, 4326))");
     260                if(!$sqlStatement){
     261                        $db->exec("ROLLBACK");
     262                        echo json_encode
     263                        (
     264                                [
     265                                        "result" => "failed",
     266                                        "message" => "Could insert station into the database",
     267                                ]
     268                        );
     269                        return;
     270                }
     271                $sqlStatement->bindValue(":name", $json["name"]);
     272                $sqlStatement->bindValue(":city", $cityId);
     273                $sqlStatement->bindValue(":uuid", $uuid);
     274                $sqlStatement->bindValue(":ownerMail",$json["email"]);
     275                $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");
     276                $sqlResult = $sqlStatement->execute();
     277                if(!$sqlResult){
     278                        error_log("Failed to add station to the database: ". $db->lastDatabaseErrorMessage());
     279                        $db->query("ROLLBACK");
     280                        echo json_encode
     281                        (
     282                                [
     283                                        "result" => "failed",
     284                                        "message" => "Could not add station to the database",
     285                                ]
     286                        );
     287                        return;
     288                }
     289
     290                // finish transaction
     291                $db->exec("COMMIT");
     292
     293                echo json_encode
     294                (
     295                        [
     296                                "result" => "success",
     297                                "uuid" => $uuid,
     298                        ]
     299                );
    102300        }
    103301        catch(Exception $exception){
  • src/webservice/tests/StationsTest.php

    r69c8290 r02fbeb8  
    1919*/
    2020
     21/**
     22        * @todo Reset database before this test is run
     23        */
    2124class StationsTest extends PHPUnit_Framework_TestCase
    2225{
    … …  
    5255        }
    5356       
     57        public function testRegisterStationUnprovenLocation()
     58        {
     59                $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();
     60                $this->assertInternalType('string', $baseUrl, "baseUrl is not of type string: ". $baseUrl);
     61                $this->assertTrue(!empty($baseUrl), "baseUrl is empty: ". $baseUrl);
     62                $client = new GuzzleHttp\Client
     63                (
     64                        [
     65                                "base_uri" => $baseUrl,
     66                                "timeout" => 5.0,
     67                                "http_errors" => false,
     68                        ]
     69                );
     70
     71                // sending must failing register request, caused by unproven location
     72                $response = $client->post("index.php/stations/register",
     73                        [ "json" => ["name" => "Cool Station", "longitude" => 23.2, "latitude" => 90, "city" => "Nice town", "email" => "test@example.org"]]
     74                );
     75                $this->assertEquals($response->getStatusCode(), 200, $response->getReasonPhrase());
     76                $json = json_decode($response->getBody(), true);
     77                $this->assertTrue(array_key_exists("result", $json));
     78                $this->assertTrue(array_key_exists("message", $json));
     79                $this->assertEquals("unprovenlocation", $json["result"], $json["message"]);
     80        }
     81
    5482        public function testRegisterStation()
    5583        {
    … …  
    6189                        [
    6290                                "base_uri" => $baseUrl,
    63                                 "timeout" => 2.0,
     91                                "timeout" => 5.0,
    6492                                "http_errors" => false,
    6593                        ]
    … …  
    6896                // sending must failing register request, caused by unproven location
    6997                $response = $client->post("index.php/stations/register",
    70                         [ "json" => ["name" => "Cool Station", "longitude" => 23.2, "latitude" => 90, "city" => "Nice town"]]
     98                        [ "json" => ["name" => "My Weather Station", "city" => "Clausthal-Zellerfeld", "longitude" => 10.28152, "latitude" => 51.8281, "email" => "test@example.org"]]
    7199                );
    72100                $this->assertEquals($response->getStatusCode(), 200, $response->getReasonPhrase());
    73101                $json = json_decode($response->getBody(), true);
    74102                $this->assertTrue(array_key_exists("result", $json));
    75                 $this->assertTrue(array_key_exists("message", $json));
    76                 $this->assertEquals("unprovenlocation", $json["result"]);
    77                
    78                 // try again with set "locationchecked" to true
    79                 $response = $client->post("index.php/stations/register",
    80                         [ "json" => ["name" => "Cool Station", "longitude" => 23.2,
    81                                                                          "latitude" => 90, "city" => "Nice town", "locationchecked" => true]]
    82                 );
    83                 $this->assertEquals($response->getStatusCode(), 200, $response->getReasonPhrase());
    84                 $json = json_decode($response->getBody(), true);
    85                 $this->assertTrue(array_key_exists("result", $json));
     103                $this->assertEquals("success", $json["result"]);
    86104                $this->assertTrue(array_key_exists("uuid", $json));
    87                 $this->assertEquals("success", $json["result"]);
    88105                $this->assertTrue(!empty($json["uuid"]));
    89106
     107                $stations = $this->query("stations");
     108                $this->assertInternalType("array", $stations);
     109                $this->assertEquals(1, count($stations));
     110                $this->assertTrue(array_key_exists("uuid", $stations[0]));
     111                $this->assertEquals($json["uuid"], $stations[0]["uuid"]);
    90112        }
    91113       
Note: See TracChangeset for help on using the changeset viewer.