Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Handy = {}
- Handy.Locations = {
- /**
- * The database instance we'll be using.
- */
- database: false,
- /**
- * This function sets up the database, initialising it if needed, and then making it
- * available to the other methods.
- */
- init_database: function() {
- // Setup the database.
- this.database = Ti.Database.install('db/locations.sqlite3', 'portfolio.sqlite3');
- // Done here.
- return true;
- },
- search: function(lat, long) {
- Ti.API.info("Searching for " + lat + "/" + long);
- },
- /**
- * Retreives a location. First, it will try to retreive the data from the cache,
- * but will fall back to an API request if the information is old, or not yet cached.
- */
- get: function(id) {
- // Setup the database if necessary.
- if (!this.database) {
- this.init_database();
- }
- Ti.API.info("Locations: Retreiving " + id);
- // Try to get the location from the cache.
- var results = this.database.execute('SELECT * FROM "locations" WHERE id=?', id);
- // If we have the location in the cache...
- if (results.isValidRow()) {
- Ti.API.info("Locations: Got location from cache.")
- // Get the time the location was cached.
- var date = JSON.parse(results.fieldByName('date'));
- // Get the current time.
- var current_date = new Date;
- var unixtime = parseInt(current_date.getTime() / 1000);
- // Check if the record is over our expiry time...
- if ((date + Ti.App.Properties.getInt('cache_expiry')) < unixtime) {
- // Attempt to refresh the data...
- if (this.refresh(id)) {
- // Now re-run this method and return the data.
- return this.get(id);
- // ... if the refresh failed, just return the current data.
- } else {
- // Parse the data record.
- var data = JSON.parse(results.fieldByName('data'));
- // Mark the data as old.
- data.old = true;
- // Done.
- return data;
- }
- // ... if the record hasn't expired, just send it back.
- } else {
- return JSON.parse(results.fieldByName('data'));
- }
- }
- // If we don't get the result in the cache...
- if (!results.isValidRow()) {
- Ti.API.info("Locations: Requested location is not cached. Requesting from the web.");
- // If we don't have a network connection, we'll just bail out.
- if (!Ti.Network.online) {
- Ti.API.info("Locations: No network connection, refresh aborted.")
- return false;
- }
- Ti.API.info("Locations: Making an API request for newer data.")
- // Grab the username and password of the current user.
- var username = Ti.App.Properties.getString('auth_username');
- var password = Ti.App.Properties.getString('auth_password')
- // Create the HTTP request.
- var xhr = Titanium.Network.createHTTPClient();
- // Pass it the database.
- xhr.database = this.database;
- // Handle the event when the ULR has loaded.
- xhr.onload = function() {
- // Parse the response.
- var response = JSON.parse(this.responseText);
- // Grab the current unixtime.
- var current_date = new Date;
- var unixtime = parseInt(current_date.getTime() / 1000);
- Ti.API.info("Locations: Got location data. Storing data in cache.");
- // Generate our query, escaping any quotes in the JSON.
- var query = 'INSERT INTO "locations" (id, date, data) VALUES (' + id + ', ' + unixtime + ", '" + JSON.stringify(response.objects[0]).replace("'", "''") + "')";
- // Execute the query.
- this.database.execute(query);
- // We're done.
- return response.objects[0];
- };
- // Setup the URL for the HTTP request.
- xhr.open('GET', Ti.App.Properties.getString('location_uri') + id);
- // Encode the username/password and set the header.
- var auth_string = 'Basic ' + Ti.Utils.base64encode(username + ':' + password);
- xhr.setRequestHeader('Authorization', auth_string);
- // Perform the request.
- xhr.send();
- }
- results.close();
- },
- /**
- * Refreshes the cached version of a a location.
- */
- refresh: function(id) {
- Ti.API.info("Locations: Refreshing location " + id)
- // If we don't have a network connection, we'll just bail out.
- if (!Ti.Network.online) {
- Ti.API.info("Locations: No network connection, refresh aborted.")
- return false;
- }
- Ti.API.info("Locations: Making an API request for newer data.")
- // Grab the username and password of the current user.
- var username = Ti.App.Properties.getString('auth_username');
- var password = Ti.App.Properties.getString('auth_password')
- // Create the HTTP request.
- var xhr = Titanium.Network.createHTTPClient();
- // Pass it the database.
- xhr.database = this.database;
- // Handle the event when the ULR has loaded.
- xhr.onload = function() {
- // Parse the response.
- var response = JSON.parse(this.responseText);
- // Grab the current unixtime.
- var current_date = new Date;
- var unixtime = parseInt(current_date.getTime() / 1000);
- Ti.API.info("Locations: Got location data. Storing data in cache.");
- // Generate our query, escaping any quotes in the JSON.
- var query = 'UPDATE "locations" SET date=' + unixtime + ", data='" + JSON.stringify(response.objects[0]).replace("'", "''") + "' WHERE id=" + id;
- // Execute the query.
- this.database.execute(query);
- // We're done.
- return true;
- };
- // Setup the URL for the HTTP request.
- xhr.open('GET', Ti.App.Properties.getString('location_uri') + id);
- // Encode the username/password and set the header.
- var auth_string = 'Basic ' + Ti.Utils.base64encode(username + ':' + password);
- xhr.setRequestHeader('Authorization', auth_string);
- // Perform the request.
- xhr.send();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement