Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Handy = {}
  2.  
  3. Handy.Locations = {
  4.    
  5.     /**
  6.      * The database instance we'll be using.
  7.      */
  8.     database: false,
  9.    
  10.     /**
  11.      * This function sets up the database, initialising it if needed, and then making it
  12.      * available to the other methods.
  13.      */
  14.     init_database: function() {
  15.        
  16.         // Setup the database.
  17.         this.database = Ti.Database.install('db/locations.sqlite3', 'portfolio.sqlite3');
  18.        
  19.         // Done here.
  20.         return true;
  21.        
  22.     },
  23.    
  24.     search: function(lat, long) {
  25.    
  26.         Ti.API.info("Searching for " + lat + "/" + long);
  27.        
  28.     },
  29.    
  30.     /**
  31.      * Retreives a location. First, it will try to retreive the data from the cache,
  32.      * but will fall back to an API request if the information is old, or not yet cached.
  33.      */
  34.     get: function(id) {
  35.  
  36.         // Setup the database if necessary.
  37.         if (!this.database) {
  38.             this.init_database();
  39.         }
  40.        
  41.         Ti.API.info("Locations: Retreiving " + id);
  42.  
  43.         // Try to get the location from the cache.
  44.         var results = this.database.execute('SELECT * FROM "locations" WHERE id=?', id);
  45.  
  46.         // If we have the location in the cache...
  47.         if (results.isValidRow()) {
  48.            
  49.             Ti.API.info("Locations: Got location from cache.")
  50.  
  51.             // Get the time the location was cached.
  52.             var date = JSON.parse(results.fieldByName('date'));
  53.            
  54.             // Get the current time.
  55.             var current_date = new Date;
  56.             var unixtime = parseInt(current_date.getTime() / 1000);
  57.            
  58.             // Check if the record is over our expiry time...
  59.             if ((date + Ti.App.Properties.getInt('cache_expiry')) < unixtime) {
  60.  
  61.                 // Attempt to refresh the data...
  62.                 if (this.refresh(id)) {
  63.                    
  64.                     // Now re-run this method and return the data.
  65.                     return this.get(id);
  66.                    
  67.                 // ... if the refresh failed, just return the current data.
  68.                 } else {
  69.                    
  70.                     // Parse the data record.
  71.                     var data = JSON.parse(results.fieldByName('data'));
  72.                    
  73.                     // Mark the data as old.
  74.                     data.old = true;
  75.                    
  76.                     // Done.
  77.                     return data;
  78.                 }
  79.        
  80.             // ... if the record hasn't expired, just send it back.
  81.             } else {
  82.                
  83.                 return JSON.parse(results.fieldByName('data'));
  84.                
  85.             }
  86.        
  87.         }
  88.        
  89.         // If we don't get the result in the cache...
  90.         if (!results.isValidRow()) {
  91.            
  92.             Ti.API.info("Locations: Requested location is not cached. Requesting from the web.");
  93.            
  94.             // If we don't have a network connection, we'll just bail out.
  95.             if (!Ti.Network.online) {
  96.  
  97.                 Ti.API.info("Locations: No network connection, refresh aborted.")
  98.  
  99.                 return false;
  100.             }
  101.  
  102.             Ti.API.info("Locations: Making an API request for newer data.")
  103.  
  104.             // Grab the username and password of the current user.
  105.             var username = Ti.App.Properties.getString('auth_username');
  106.             var password = Ti.App.Properties.getString('auth_password')
  107.  
  108.             // Create the HTTP request.
  109.             var xhr = Titanium.Network.createHTTPClient();
  110.  
  111.             // Pass it the database.
  112.             xhr.database = this.database;
  113.  
  114.             // Handle the event when the ULR has loaded.
  115.             xhr.onload = function() {
  116.  
  117.                 // Parse the response.
  118.                 var response = JSON.parse(this.responseText);
  119.  
  120.                 // Grab the current unixtime.
  121.                 var current_date = new Date;
  122.                 var unixtime = parseInt(current_date.getTime() / 1000);
  123.  
  124.                 Ti.API.info("Locations: Got location data. Storing data in cache.");
  125.  
  126.                 // Generate our query, escaping any quotes in the JSON.
  127.                 var query = 'INSERT INTO "locations" (id, date, data) VALUES (' + id + ', ' + unixtime + ", '" + JSON.stringify(response.objects[0]).replace("'", "''") + "')";
  128.  
  129.                 // Execute the query.
  130.                 this.database.execute(query);
  131.  
  132.                 // We're done.
  133.                 return response.objects[0];
  134.  
  135.             };  
  136.  
  137.             // Setup the URL for the HTTP request.
  138.             xhr.open('GET', Ti.App.Properties.getString('location_uri') + id);  
  139.  
  140.             // Encode the username/password and set the header.
  141.             var auth_string = 'Basic ' + Ti.Utils.base64encode(username + ':' + password);  
  142.             xhr.setRequestHeader('Authorization', auth_string);  
  143.  
  144.             // Perform the request.
  145.             xhr.send();
  146.         }
  147.    
  148.         results.close();
  149.     },
  150.    
  151.     /**
  152.      * Refreshes the cached version of a a location.
  153.      */
  154.     refresh: function(id) {
  155.        
  156.         Ti.API.info("Locations: Refreshing location " + id)
  157.        
  158.         // If we don't have a network connection, we'll just bail out.
  159.         if (!Ti.Network.online) {
  160.            
  161.             Ti.API.info("Locations: No network connection, refresh aborted.")
  162.            
  163.             return false;
  164.         }
  165.        
  166.         Ti.API.info("Locations: Making an API request for newer data.")
  167.        
  168.         // Grab the username and password of the current user.
  169.         var username = Ti.App.Properties.getString('auth_username');
  170.         var password = Ti.App.Properties.getString('auth_password')
  171.        
  172.         // Create the HTTP request.
  173.         var xhr = Titanium.Network.createHTTPClient();
  174.        
  175.         // Pass it the database.
  176.         xhr.database = this.database;
  177.        
  178.         // Handle the event when the ULR has loaded.
  179.         xhr.onload = function() {
  180.            
  181.             // Parse the response.
  182.             var response = JSON.parse(this.responseText);
  183.            
  184.             // Grab the current unixtime.
  185.             var current_date = new Date;
  186.             var unixtime = parseInt(current_date.getTime() / 1000);
  187.            
  188.             Ti.API.info("Locations: Got location data. Storing data in cache.");
  189.            
  190.             // Generate our query, escaping any quotes in the JSON.
  191.             var query = 'UPDATE "locations" SET date=' + unixtime + ", data='" + JSON.stringify(response.objects[0]).replace("'", "''") + "' WHERE id=" + id;
  192.            
  193.             // Execute the query.
  194.             this.database.execute(query);
  195.            
  196.             // We're done.
  197.             return true;
  198.         };  
  199.        
  200.         // Setup the URL for the HTTP request.
  201.         xhr.open('GET', Ti.App.Properties.getString('location_uri') + id);  
  202.        
  203.         // Encode the username/password and set the header.
  204.         var auth_string = 'Basic ' + Ti.Utils.base64encode(username + ':' + password);  
  205.         xhr.setRequestHeader('Authorization', auth_string);  
  206.        
  207.         // Perform the request.
  208.         xhr.send();
  209.    
  210.     }
  211.    
  212. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement