Пример #1
0
function clearData(auctionSite) {
  ref = new Firebase(firebase_url + auctionSite);
  console.log("time to clear");
  ref.remove();

  auctionStarted = false;
}
Пример #2
0
var contactClient = function(parameters) {

  if (auctionStarted === false) {
    // resp = 'Auction has not yet started. So your request will not be' + 
    // 'considered";
    myFirebaseRef.remove(); // Just clear data if present from yesterday's auc.
    // return resp;
  }

  tagRef = myFirebaseRef.child(auctionSite).child(parameters.tagID);
  requestID = parameters.mobileNumber + parameters.tagID;
  var off;
  cReqs[requestID] = tagRef.on("value", function(snapshot) {
    if (snapshot.exists()) {
      console.log(snapshot.val());
      console.log("hi");
      
      console.log("some ..");
      off = true;
      // This callback is called twice if the data already exists at this
      // location(even after calling off). So, I'm using the variable off
      // and calling off after this callback and it seems to be working..
      // If you find a better method, change it.
      sms.sendSMS(snapshot, parameters);
      tagRef.off("value", cReqs[requestID]);
    }
  });
  if(off)
    tagRef.off("value", cReqs[requestID]);
  
  return "SUCCESS";
};
Пример #3
0
function clearSessions(done) {
  sessions.remove(function(error) {
    if(!error) {
      done();
    }
  });
}
Пример #4
0
    FirebaseStore.prototype.destroy = function (sid, fn) {

        sid = this.cleanSid(sid);
        var sessionRef = new Firebase('https://' + this.host + '/sessions/' + sid);
        sessionRef.remove(fn);

    };
Пример #5
0
router.delete('/delete/:id', function(req, res, next){
    var id = req.params.id;
    var genreRef = new Firebase('https://musicmanager.firebaseio.com/genres/' + id);
    genreRef.remove();
    
	req.flash('success_msg','Genre Deleted');
	res.send(200);
});
Пример #6
0
 }, function(result) {
     if (result[0].status === 'sent' || result[0].status === 'queued') {
         optinRef.remove(function(error) {
             if (error) {
                 //ravenClient.captureError(error);
             }
         });
     }
 });
Пример #7
0
 stripeFire.customers('https://stripe-fire.firebaseio.com/customers/test-3', function (err) {
   if (err) {
     done(err);
   } else if (this.action === 'create') {
     var ref = new Firebase('https://stripe-fire.firebaseio.com/customers/test-3/' + this.childSnapshot.key());
     ref.remove();
   } else if (this.action === 'delete') {
     done();
   }
 });
Пример #8
0
    deleteCard: function() {
        var firebaseCardsRef = new Firebase('http://mutombo-cards.firebaseio.com/' + this.props.cardId);

        var pr =  prompt('Razon para borrar la card? (Pagado, Error en los datos, etc)', 'Pagado');

        if (pr) {
            firebaseCardsRef.remove();
            this.logDeletion(pr);
        }
    },
Пример #9
0
 stripeFire.plans('https://stripe-fire.firebaseio.com/plans/test-3', function (err) {
     if (err) {
         done(err);
     } else if (this.action === 'create') {
         var ref = new Firebase('https://stripe-fire.firebaseio.com/plans/test-3/' + this.childSnapshot.name());
         ref.remove();
     } else if (this.action === 'delete') {
         done();
     }
 }, null, function (plan) {
Пример #10
0
ref.auth(SECRET, function(err) {
  if (err) {
    console.error("Firebase authentication failed!", err);
  } else {
    console.log('Firebase login');
    ref.remove(function() {
        getFeedFromURL();
    });
  }
});
Пример #11
0
  beforeEach(function(done) {
    shallowRenderer = ReactTestUtils.createRenderer();

    firebaseRef = new Firebase(demoFirebaseUrl);
    firebaseRef.remove(function(error) {
      if (error) {
        done(error);
      } else {
        firebaseRef = firebaseRef.child(TH.generateRandomString());
        done();
      }
    });
  });
Пример #12
0
function clear() {
    // TODO: remove all people from the Firebase
    var ref = new Firebase('https://hello-jtresman.firebaseio.com/users')
    var onComplete = function(error) {
        if (error) {
            console.log('Clear Synchronization failed');
        } else {
            console.log('Clear Synchronization succeeded');
        }
    };

    ref.remove(onComplete)
}
Пример #13
0
app.delete('/nominees', function(request,response){
	var nominee = request.query.nominee;
	var delRef = new Firebase("https://votr-dev.firebaseio.com/nominees/" + nominee );
	var onComplete = function(error){
		if(error){
			response.send(error);
		}
		else{
			response.send("success");
		}
	}

	delRef.remove(onComplete);
})
Пример #14
0
            }, function(error, userData) {
                if (error) {
                    optinRef.remove(function(error) {
                        if (error) {
                            console.log(error);
                        }
                    });
                } else {
                    firebaseRef.child('users').child(userData.uid).set({
                        email: optinData.email,
                        role: 'customer',
                        registered: false
                    }, function(error) {
                        if(!error) {
                            var email = {
                                to: [{
                                    email: optinData.email
                                }],
                                merge_language: 'handlebars',
                                'global_merge_vars': [{
                                    name: 'email',
                                    content: optinData.email
                                }, {
                                    name: 'password',
                                    content: newPassword
                                }]

                            };
                        }

                        emailClient.messages.sendTemplate({
                            template_name: conf.mandrill.template,
                            template_content: {},
                            message: email,
                            async: false
                        }, function(result) {
                            if (result[0].status === 'sent' || result[0].status === 'queued') {
                                optinRef.remove(function(error) {
                                    if (error) {
                                        //ravenClient.captureError(error);
                                    }
                                });
                            }
                        });

                    });

                }
            });
Пример #15
0
  beforeEach(function (done) {
    // Navigate to the chat app
    browser.get('chat/chat.html');

    // Clear the Firebase before the first test and sleep until it's finished
    if (!firebaseCleared) {
      firebaseRef.remove(function() {
        firebaseCleared = true;
        done();
      });
    }
    else {
      ptor.sleep(500);
      done();
    }
  });
Пример #16
0
flashCardMethod.deleteCard = function(req, res) {
  var cardId = req.params.id;

  var flashcardRef = new Firebase(process.env.FIREBASE_ADDRESS + '/flashcards/' + cardId);

  var onComplete = function(error) {
    if (error) {
      console.log('Synchronization failed');
      res.status(400).send(error);
    } else {
      //console.log('Synchronization succeeded');
      res.sendStatus(200);
    }
  };
  flashcardRef.remove(onComplete);
};
Пример #17
0
function init(cb){
	//clean the database and resinsert the test data
	test_ref.remove(function(){
		var counter = testData.length;
		allIds = new(Array)();
		testData.forEach(function(item){
			var item_ref = test_ref.push(item,function(){
				counter--;
				if (counter === 0 ) {
					cb();
				}
			});
			allIds.push(item_ref.name());
		});
	});
}
Пример #18
0
publicChallengeRef.on("child_changed", function(snapshot){
  var challenge = snapshot.val();
  var challengeId = snapshot.key();
  console.log("challenge progress of challenge: " + challengeId + " has been updated")
  
  
  var progress = challenge.progress;
  var challengeCompleted = false;
  
  // check challenge update with challenge completed condition
  // also need to record who is the winner(do this maybe later)
  Object.keys(progress).forEach(function(key){
    var userProgress = progress[key];
    if (userProgress >= challenge.completedCondition) {
      challengeCompleted = true;
    }
  });
  
  // if completed... move challenge from active to completed table for both host and member
  if (challengeCompleted) {
    var hostUserId = challenge.createdBy
  
    // remove from live
    var hostLiveChallengeRef = new Firebase(config.firebase.url + "/live_challenges/" + hostUserId + "/active/" + challengeId);
    hostLiveChallengeRef.remove()
    
    // add to completed
    var hostDeadChallengeRef = new Firebase(config.firebase.url + "/dead_challenges/" + hostUserId + "/completed/" + challengeId);
    hostDeadChallengeRef.set(true);
    
    // TO DO: remove challenge from member live_challenges
    
    // TO DO: add challenge to member dead_challenges
    
    // change public challenge status to completed
    var publicChallengeRef = new Firebase(config.firebase.url + "/public_challenges/" + challengeId);
    publicChallengeRef.update({status: 'Completed'});
  }
  
  
  
});
Пример #19
0
app.delete('/nominees', function(request,response){

	if(request.user == null){
		response.status(400).send("Error: Not Authorized");
	} else {
		var nominee = request.query.nominee;
		var delRef = new Firebase("https://votr-dev.firebaseio.com/nominees/" + nominee );
		var onComplete = function(error){
			if(error){
				response.send(error);
			}
			else{
				response.send("success");
			}
		}

		delRef.remove(onComplete);
	}
	
})
Пример #20
0
var sendData = function(cars_info) {

  if (auctionStarted === false) {

    // auctionSite = request.body.mac_address.split('"').join("");
    myFirebaseRef.remove();
    // If this is the first time, a reader is sending data, it
    // probably means the auction has started. So delete all the
    // data sent by this reader after 8 hrs.
    readerId = myFirebaseRef.child(auctionSite);
    setTimeout(clearData, 8*60*60*1000, auctionSite);

    myFirebaseRef.child('StartTimes').child(auctionSite).set(
      Date.now() 
    );
    
    auctionStarted = true;
  }

  for (var eachCar in cars_info) {
    // eachCar will be in the form of"antenna_id,"epc",ts,RSSI"
    carInfo = cars_info[eachCar].split(",");
    carID = carInfo[epc].split('"').join("");
    
    carID = carID.replace(/^[0]+/g, "");
    console.log("see:", carID);

    // check if the tagID/carID is actually from a car in our database
    if(!vehfire.confirmTag(carID, carInfo[antenna_id], tagSnapshot.hasChild(carID)))
      continue;

    readerId.child(carID).set({
      'Antennaid': carInfo[antenna_id],
      // divide the ts received by 1000 in order to work with Date()
      // (Not sure if this is the best way to do but for now ...)
      'First_seen_time': moment(Number(carInfo[first_seen_time]
)/1000).tz(timeZone).format('h:mm A'),
      'RSSI': carInfo[RSSI]
    });
  }
};
Пример #21
0
  fn: function (inputs, exits) {

    // Require the Firebase SDK
    var Firebase = require('firebase');

    // Get the data path reference
    var ref = new Firebase(inputs.firebaseURL);

    // Attempt to read from the data path
    ref.remove(function(error) {

      // Handle errors
      if (error) {
        return exits.error(error);
      }

      // Return through the success exit
      return exits.success();
    });

  },
Пример #22
0
            snap.forEach(function (childSnap) {
                var key = childSnap.key();
                var dat = childSnap.val();
                workQueue++;

                if (dat.dateNum < timeConsideredOld) {
                    var rmKey = pathToData + '/' + key;
                    var refDel = new fb(rmKey);
                    var logMsg;
                    workQueue++;
                    logMsg = 'Del Queue:key=' + key;
                    qLog(logMsg);
                    refDel.remove(function (error) {
                        workQueue--;
                        logMsg = 'key=' + key;
                        if (error) {
                            qLog('Del Fail' + logMsg);
                        } else {
                            qLog('Del Okay:' + logMsg);
                        }
                    });
                }
                workQueue--;
            });
Пример #23
0
ListActions.removeNote.listen(function(data) {
	var deletefRef = new Firebase(fUrl+data.id);
	deletefRef.remove()
		   .then( (response) => {this.completed(data);})
           .catch( (error) => { this.failed(error)});;
});
Пример #24
0
 before(function (done) {
     var ref = new Firebase('https://stripe-fire.firebaseio.com');
     ref.remove(done);
 });
Пример #25
0
 before(function(done) {
   firebaseRef.remove(function() {
     done();
   });
 });
Пример #26
0
 remove(fn) {
     return this.ref.remove(fn)
 }
Пример #27
0
  } // End loadDrivers()



  /**
   * Sets up individual devices
   */
   function devicesInit (networkDevices) {

    // Clear all currently connected devices
    deviceFirebase.remove();

    APIStatus.update({ status: "Pairing Devices with Drivers" });

    // Push all devices to the "connected_devices" firebase object...
    for(var n in networkDevices) {
      if(!Devices[networkDevices[n].mac]) {
        deviceFirebase.child(networkDevices[n].mac).set({
          name: networkDevices[n].name,
          address: networkDevices[n].address,
          mac: networkDevices[n].mac,
          supported: false,
          driver: "none"
        }); // End set()
      }
    }

    var supportedDevices = 0;

    for(var i in drivers) { // Loop through all the device drivers that have loaded

      // If the driver implements it's own discover method, use it rather than using keywords:
      if(drivers[i].discoverable == true && drivers[i].discover && (drivers[i].discover instanceof Function)) {
        
        // Execute the driver's discover function with the following callback:
        drivers[i].discover(drivers[i], function (discoveredDriver, discovered) {

          if(discovered) { // Find the MAC address for the device at the discovered address:

            var discoveredMAC = undefined;

            // Loop through the networkDevices until we find a device with the same address as this device:
            for(var k in networkDevices) if(discovered.address == networkDevices[k].address) discoveredMAC = networkDevices[k].mac;

            if(discoveredMAC && !Devices[discoveredMAC]) { // Instantiate the new device
              Devices[discoveredMAC] = new drivers[getDriverID(discoveredDriver.driverDetails.make, discoveredDriver.driverDetails.model, discoveredDriver.driverDetails.version)](discovered.name.toLowerCase().replace(/\s+/ig, '_'), discovered.address, discoveredMAC, discovered.port);
              console.warn("Found *New* Supported " + Devices[discoveredMAC].toString());

              // Add the device to firebase
              deviceFirebase.child(discoveredMAC).set({
                name: discovered.name,
                address: discovered.address,
                mac: discoveredMAC,
                port: discovered.port,
                supported: true,
                driver: {
                  make    : discoveredDriver.driverDetails.make,
                  type    : discoveredDriver.driverDetails.type,
                  model   : discoveredDriver.driverDetails.model,
                  version : discoveredDriver.driverDetails.version
                }
              }); // End set()
              
              // Emit the "instantiated" event
              Devices[discoveredMAC].emit("instantiated");
              supportedDevices++;
            }
            else if(Devices[discoveredMAC]) { // Device has already been instantiated on a previous scan...
              console.warn("Found Supported " + Devices[discoveredMAC].toString());
              supportedDevices++;

              // Add the device to firebase
              deviceFirebase.child(Devices[discoveredMAC].mac).set({
                name: Devices[discoveredMAC].name,
                address: Devices[discoveredMAC].address,
                mac: Devices[discoveredMAC].mac,
                port: Devices[discoveredMAC].port,
                supported: true,
                driver: {
                  make    : drivers[i].driverDetails.make,
                  type    : drivers[i].driverDetails.type,
                  model   : drivers[i].driverDetails.model,
                  version : drivers[i].driverDetails.version
                }
              }); // End set()
            }
            else if(!Devices[discoveredMAC]) { // Print an error
              console.error("Unable to pair driver (" + discoveredDriver.driverDetails.make + ":" + discoveredDriver.driverDetails.model + ":" + discoveredDriver.driverDetails.version + ") discovered device with correct MAC address for device @ " + discovered.address);
            }
            else {
              // End if block
              supportedDevices++;
            }

          } // End inner if block
        
        }); // End drivers[i].discover()

      }
      else { // The device driver doesn't support discovery use **archaic** keyword method

        for(var n in networkDevices) { // Loop through all the network devices

          for(var k in drivers[i].driverKeywords) { // Loop through the device keywords

            if(!Devices[networkDevices[n].mac] && networkDevices[n].name.match(RegExp(drivers[i].driverKeywords[k], 'ig'))) { // If the device's name matche's a keyword:

              // Instantiate the device
              Devices[networkDevices[n].mac] = new drivers[getDriverID(drivers[i].driverDetails.make, drivers[i].driverDetails.model, drivers[i].driverDetails.version)](networkDevices[n].name, networkDevices[n].address, networkDevices[n].mac);
              console.warn("Found *New* Supported " + Devices[networkDevices[n].mac].toString());
              
              // Add the device to firebase
              deviceFirebase.child(networkDevices[n].mac).set({
                name: networkDevices[n].name,
                address: networkDevices[n].address,
                mac: networkDevices[n].mac,
                port: (networkDevices[n].port ? networkDevices[n].port : 0),
                supported: true,
                driver: {
                  make    : drivers[i].driverDetails.make,
                  type    : drivers[i].driverDetails.type,
                  model   : drivers[i].driverDetails.model,
                  version : drivers[i].driverDetails.version,
                }
              }); // End set()
              
              // Emit the "instantiated" event
              Devices[networkDevices[n].mac].emit("instantiated");
              if(Devices[networkDevices[n].mac]) supportedDevices++;

              // We found a driver via keyword, break the keyword search loop
              break;

            }
            else if(Devices[networkDevices[n].mac]) { // Device has already been instantiated on a previous scan...
              supportedDevices++;
              console.warn("Found Supported " + Devices[networkDevices[n].mac].toString());

              // Add the device to firebase
              deviceFirebase.child(Devices[networkDevices[n].mac]).set({
                name: Devices[networkDevices[n].mac].name,
                address: Devices[networkDevices[n].mac].address,
                mac: Devices[networkDevices[n].mac].mac,
                port: Devices[networkDevices[n].mac].port,
                supported: true,
                driver: {
                  make    : drivers[i].driverDetails.make,
                  type    : drivers[i].driverDetails.type,
                  model   : drivers[i].driverDetails.model,
                  version : drivers[i].driverDetails.version
                }
              }); // End set()

            }

          } // End for(var k in drivers[i].driverKeywords)

        } // End for(var n in networkDevices)

      } // End if(drivers[i].discoverable && drivers[i].discover && (drivers[i].discover instanceof Function))/else

    } // End if/else block

    // Check to see that supported devices exits
    var devCheckInterval = setInterval(function () {

      if((Date.now() - scan.lastScan > APIConfig.devices.deviceDiscoverTimeout)) { 

        if(supportedDevices <= 0) { // Warn the user that no supported devices were found:
            console.warn("No supported devices were found!\nNext network discovery scan will occur again in: " + APIConfig.devices.scanInterval + " ms.");
        }

        APIStatus.update({ status: "API Ready", last_startup_status: 0 });

        // Clear this interval to stop checking
        clearInterval(devCheckInterval);

      } // End if block

    }, 60); // End timeout

   } // End devicesInit()
Пример #28
0
var SmartHome = function() {

  // So we can reference this from within callbacks:
  var self = this;

  // Overwrite the global console, so we can control formatting...
  var console = APIUtil.console;

  // Clear the front-end log in Firebase
  var feLog = new Firebase(APIConfig.general.firebaseRootURI + "/front-end-log");
  if(feLog && feLog.remove instanceof Function) feLog.remove();

  // Write the restart to the log file.
  fs.writeFile(APIConfig.general.logPath, "\n-------------- SMART HOME API BOOT --------------\n\n", {
    flag: 'a',
    encoding: 'utf-8'
  }, function (err) {
    if (err) {
      APIConfig.lastError = '"Unable to write to the the SmartHome API Log.\nPlease run this process as an administration (e.g. sudo)."';
      APIConfig.exitWithError = true;
      process.kill(process.pid, "SIGINT");
    }
  });

  // Clear the console.
  console.clear();


  /**
   * Perform back-end shutdown operations...
   * Remove all connected devices, etc.
   *
   */
  var shuttingDown = false;
  var shutdown = function () {

    if(shuttingDown == false) { // So we don't accumulate a crap ton of data in the DB if a program refuses to shutdown... like before. :(

      shuttingDown = true;

      // Clear the "connected_devices" Firebase object:
      if (deviceFirebase) deviceFirebase.remove();
      APIStatus.update({reachable: false, last_shutdown_status: 0, last_shutdown: Date.now(), locked: 0, code: -1 }, function () {

        (APIConfig.exitWithError) ?
            console.error("Smart Home API Server v" + APIConfig.general.version + " Shutting Down with Error:\n\n" + APIConfig.lastError + "\n") :
            console.warn("Smart Home API Server v" + APIConfig.general.version + " Shutting Down...");

        // Exit the program...
        process.exit(0);

      });

    }
    else {

      // Hard kill
      if(APIConfig.lastError) console.error("Smart Home API Server v" + APIConfig.general.version + " Shutting Down, Last Known Error:\n\n" + APIConfig.lastError + "\n");
      process.kill(process.pid, "SIGKILL");
    }

  }; // End shutdown()


  /**
   * Shutdown API's per request
   */
  // The APIStatus Object in Firebase
  var APIStatus = new Firebase(APIConfig.general.firebaseRootURI + "/" + APIConfig.general.firebaseAPIStatus);

  // Shutdown this instance of the API on request...
  APIStatus.child("kill").on("value", function (data) {
    if(data.val() == process.pid) {
      console.error("This process has been been shutdown by another instance of the SmartHome API.");
      shutdown();
    }
  });


  /**
   * Check to see if another instance of the SmartHome API with this key is running, if so stop it...
   */
  var unableToShutdown;
  APIStatus.once("value", function (data) {

    // If the API is locked (1), it means the API is in use by a SmartHome API process,
    // 0 == not in use, -1 means shutdown the running process.
    var status = data.val();
    if(status.locked == 1) {

      console.warn("Another instance of the SmartHome API using the key " + APIConfig.general.APIKey + "\nis already running...\n\nAttempting to forcefully shut it down.\n");
      APIStatus.child("kill").set(status.pid, function (error) { // Tell the other process to shutdown

        if(error) { // There was an error updating the value...
          console.error("Unable to shutdown previous SmartHome API instance, this instance cannot continue.");
          process.exit();
        }

        unableToShutdown = setTimeout(function () {
          APIStatus.child("locked").once("value", function () {
            if(data.val() != 0) console.error("Unable to shutdown previous process.\nThis instance cannot continue....\n\nIf necessary, you must unlock the API manually by setting the database 'lock' value to 0.\n");
            process.exit();
          });
        }, 10000); // 10 Seconds

      }); // End APIStatus.child("locked").update(-1)

    } // End if(status.locked == 1)

    // Start this instance, if we get an unlock code...
    APIStatus.on("value", function (data) {
      if(data.val().locked == 0 && shuttingDown == false) {
        APIStatus.update({ last_startup: Date.now(), reachable: true, status: "startup pending", locked: 1, pid: process.pid, kill: 0, code: 0 });
        self.emit("process singular");
      }
    })

  }); // End APIStatus.child("locked").once("value")


  /**
   * Call the shutdown() function when the "SIGINT" signal is sent to the terminal.
   */
  process.on("SIGINT", shutdown);


  /**
   * On Unhandled Exceptions
   */
  process.on("uncaughtException", function (e) {
    APIConfig.exitWithError = true;
    APIConfig.lastError = "An uncaught exception has occurred..." + "\n\nMessage: \"" + e.message + "\".\n\nStacktrace: " + e.stack;
    process.kill(process.pid, "SIGINT");
  });


  // <!------------------------- PRIVATE CLASS VARIABLES -------------------------!>

  // Holds all the drivers:
  var drivers = {};

  // Holds all the interfaces:
  var interfaces = {};

  // For file loading verification:
  var fileCount = 0;
  var numFiles = 0;
  var fileCountI = 0;
  var numFilesI = 0;

  var DriverIDs = -1;
  var nextDriverID = function () { return '0x' + ((++DriverIDs).toString(16)); }

  var Devices = require("./Devices.js");

  // The firebase location for all devices **connected** to the network...
  var deviceFirebase = new Firebase(APIConfig.general.firebaseRootURI + '/' + APIConfig.general.firebaseAllDevicesPath);

  // All network devices
  var networkDevices = undefined;


  // <!------------------------- PUBLIC CLASS VARIABLES -------------------------!>

  Object.defineProperty(this, "Devices", // The Devices object, so other modules can use it...
    {
      get: function () { return Devices; },
      configurable: false,
      enumerable: true
    }
  );

  // <!---------------------------- BEGIN PROGRAM FLOW ----------------------------!>

  self.once("process singular", function () { // Dont's start until we know this is the only running instance...

    clearTimeout(unableToShutdown);

    // #1 --> So we can ping the backend from the front-end.
    APIStatus.child("sessions").once("value", function (data) {

      var sessions = data.val();

      for (var i in sessions) {

        if (sessions[i].last != undefined && Date.now() - sessions[i].last > 300000) { // 5 Mins, Delete old sessions...
          APIStatus.child("sessions").child(i).remove();
        }

      } // End for loop

    }); // End APIStatus.child("sessions").on("value")

    APIStatus.child("sessions").on("child_changed", marcoPolo);
    APIStatus.child("sessions").on("child_added", marcoPolo);

    function marcoPolo(child) {

      var session = child.val();

      if (session.ping && session.ping == "marco") {
        APIStatus.child("sessions").child(child.name()).update({
          ping: "polo",
          last: Date.now()
        });
      }
    }

    // #2 ---> Clean up configuration values...
    (function () {

      // Append a '/' to APIConfig.devices.driverDirectory if it doesn't have a trailing slash
      if (APIConfig.devices.driverDirectory.charAt(APIConfig.devices.driverDirectory.length - 1) != '/')
        APIConfig.devices.driverDirectory += '/';

      // Append a '/' to APIConfig.devices.driverInterfaces if it doesn't have a trailing slash
      if (APIConfig.devices.interfaceDirectory.charAt(APIConfig.devices.interfaceDirectory.length - 1) != '/')
        APIConfig.devices.interfaceDirectory += '/';

    })();

    // #3 ---> Show msg that Smart Home API Server is starting...
    console.warn("Smart Home API Server v" + APIConfig.general.version + " Booting on '" + os.platform() + "'...");

    // #4 ---> Load the device interfaces
    loadInterfaces();

    // #5 ---> Once the interfaces are loaded, load the device drivers:
    self.on("interfaces loaded", loadDrivers);

    // #6 ---> Setup the devices, based on the network devices connected:
    self.on("drivers loaded", function () {

      // Get the network's WAN IP...
      WANIP(function (err, ip) {

        if (err) {
          console.error("WAN IP Retrieval Failed!");
          return;
        }

        // Update the firebase "api_status" object...
        APIStatus.update({wan_ip: ip, status: "Got Network WAN IPv4" });
      });

      scanNetwork.call();

      // Once the network scan is complete load rules and schedules...
      self.once("network scan complete", function () {
        var Schedules = require("./Schedules"); // The SmartHome Schedules Module
        var Rules = require("./Rules");     // The SmartHome Rules Module
        console.notice("SmartHome API Ready!", false, 118);
      });

    }); // End self.on("drivers loaded")

    // Set an interval to continuously re-scan the network:
    setInterval(scanNetwork, APIConfig.devices.scanInterval);

  }); // End self.on("process singular");

  
  // <!----------------------------- END PROGRAM FLOW -----------------------------!>

  /**
   * Scans the network for all connected devices by using nmap and ping commands (works on win and unix)
   */
  var scan;
  function scanNetwork() {

    APIStatus.update({ status: "Scanning Network for Connected Devices", });

    // Notify the user we are scanning the network...
    console.warn("Scanning network for connected devices. Please wait...");

    // Call the NetworkDiscover module,
    scan = new NetworkDiscover.scan();

    // When the discovery is complete, perform the anon-function:
    scan.on("discovery complete", function (dev) {

      var devString = [];
      for(var i in dev) devString.push('    - ' + dev[i].name);
      
      // Tell the user that the scan is complete, and show a list of the devices:
      console.notice("Network scan complete, " + Object.keys(dev).length + " devices found:\n" + devString.join("\n"));

      // Init all devices
      devicesInit(dev);

      self.emit("network scan complete");

    });
  }


  /**
   * Loads the interfaces (as modules) which mitigates the functions each driver must implement.
   */
  function loadInterfaces () {

    // Tell the user we are loading the interfaces...
    console.notice("Loading Device Interfaces...");

    // Read the interface directory...
    fs.readdir(APIConfig.devices.interfaceDirectory, function (error, files) {

      // Silently print the error to the console.
      if(error) { console.error(error); return; }

      // Set numFilesI to the number of files in the interface directory...
      numFilesI = files.length;

      // Loop through each individual file
      files.forEach(function (f) {

        // Get file information for each file
        fs.stat(APIConfig.devices.interfaceDirectory + f, function (error, stat) {

          // Silently print the error to the console.
          if(error) { console.error(error); return; }

          // Split the filename into an array by the delimiter: '.'
          var fnTokens = f.split('.');
          
          // If the file is a file and not a directory and its extension is ".js" (javascript):
          if(stat.isFile() && fnTokens[fnTokens.length - 1] == "js") {

            var driverInterface = require(process.cwd() + "/" + APIConfig.devices.interfaceDirectory + f);

            (driverInterface.type) ?
              interfaces[driverInterface.type.toLowerCase()] = driverInterface :
              console.error("Interface with filename '" + f + "' doesn't declare a type!\nThis interface will not be loaded.");

            console.notice("Interface for '" + driverInterface.type.toLowerCase() + "' devices loaded!");

          } // End if stat.isFile()... block
          
          // Increment the fileCount
          fileCountI++;

        }); // End fs.stat()

      }); // End files.forEach()

    }); // End fs.readdir()
  
    var intervalSumI = 10;
    var intervalI = setInterval(function () {

      if(intervalSumI > APIConfig.general.deviceLoadTimeout) { // Took too long to load interfaces, something's wrong...
        console.error("Unable to load device interfaces. SmartHome API cannot continue.");
        process.exit(1); // POSIX Failure Code
      }
      else if(fileCount >= numFiles) {
        console.notice("Interface Loading Complete...");
        self.emit("interfaces loaded", interfaces);
        clearInterval(intervalI);
      }

      intervalSumI += 10;

    }, 10); // End interval

  } // End loadInterfaces



  /**
   * Load the device drivers (as modules) which communicate with each individual Wi-Fi device:
   */
  function loadDrivers () {

    // Notify the user we are loading the drivers:
    console.notice("Loading Device Drivers...");

    // Read the files in the driver's directory.
    fs.readdir(APIConfig.devices.driverDirectory, function (error, files) {

      // Silently print the error to the console.
      if(error) { console.error(error); return; }

      // Set numFiles equal to the number of files in the driver directory.
      // We need this to check if all have loaded successfully.
      numFiles = files.length;

      // Loop through each file
      files.forEach(function (f) {

        // Get file information for each file
        fs.stat(APIConfig.devices.driverDirectory + f, function (error, stat) {

          // Silently print the error to the console.
          if(error) { console.error(error); return; }

          // Split the filename into an array by the delimiter: '.'
          var fnTokens = f.split('.');
          
          // If the file is a file and not a directory and its extension is ".js" (javascript):
          if(stat.isFile() && fnTokens[fnTokens.length - 1] == "js") {

            var deviceDriver = undefined;

            try { // Try to load the device driver into memory as a node module:

              deviceDriver = require(process.cwd() + "/" + APIConfig.devices.driverDirectory + f);

              if(!validateDeviceDriver(deviceDriver, f)) {
                
                // If driver validation fails, show a message and goto the next driver, fail "silently."
                console.error("Device Driver '" + f + "' has failed validation.\nThis driver will not load, and supported devices will be unable to use this driver.");

              }
              else { // The driver passed validation.

                // Notify the user and add the driver to the driver's array.
                deviceDriver.driverDetails.driverID = nextDriverID();
                console.notice("Device Driver for device '" + deviceDriver.driverDetails.make + " " + deviceDriver.driverDetails.model + "' (v" + deviceDriver.driverDetails.version + ", id:" + deviceDriver.driverDetails.driverID + ") loaded!");
                drivers[deviceDriver.driverDetails.driverID] = deviceDriver;

              } // End if/else block

            }
            catch(e) { // We couldn't "require" the device driver module...

              console.error("Device Driver '" + f + " failed to compile with message:\n" + e.message + "\nThis driver will not load, and supported devices will be unable to use this driver.");

            } // End try/catch block

          } // End if stat.isFile()... block
          
          // Increment the fileCount
          fileCount++;

        }); // End fs.stat()

      }); // End files.forEach()

    }); // End fs.readdir()
  
    // Set an interval to check for device driver loading completion.
    var intervalSum = 10;
    var interval = setInterval(function () {

      if(intervalSum > APIConfig.general.deviceLoadTimeout) { // Took too long to load drivers, something's wrong...
        console.error("Unable to load device drivers. SmartHome API cannot continue.");
        process.exit(1); // POSIX Failure Code
      }
      else if(fileCount >= numFiles) {
        console.notice("Driver Loading Complete...");
        self.emit("drivers loaded", drivers);
        clearInterval(interval);
      }

      intervalSum += 10;

    }, 10); // End interval

  } // End loadDrivers()



  /**
   * Sets up individual devices
   */
   function devicesInit (networkDevices) {

    // Clear all currently connected devices
    deviceFirebase.remove();

    APIStatus.update({ status: "Pairing Devices with Drivers" });

    // Push all devices to the "connected_devices" firebase object...
    for(var n in networkDevices) {
      if(!Devices[networkDevices[n].mac]) {
        deviceFirebase.child(networkDevices[n].mac).set({
          name: networkDevices[n].name,
          address: networkDevices[n].address,
          mac: networkDevices[n].mac,
          supported: false,
          driver: "none"
        }); // End set()
      }
    }

    var supportedDevices = 0;

    for(var i in drivers) { // Loop through all the device drivers that have loaded

      // If the driver implements it's own discover method, use it rather than using keywords:
      if(drivers[i].discoverable == true && drivers[i].discover && (drivers[i].discover instanceof Function)) {
        
        // Execute the driver's discover function with the following callback:
        drivers[i].discover(drivers[i], function (discoveredDriver, discovered) {

          if(discovered) { // Find the MAC address for the device at the discovered address:

            var discoveredMAC = undefined;

            // Loop through the networkDevices until we find a device with the same address as this device:
            for(var k in networkDevices) if(discovered.address == networkDevices[k].address) discoveredMAC = networkDevices[k].mac;

            if(discoveredMAC && !Devices[discoveredMAC]) { // Instantiate the new device
              Devices[discoveredMAC] = new drivers[getDriverID(discoveredDriver.driverDetails.make, discoveredDriver.driverDetails.model, discoveredDriver.driverDetails.version)](discovered.name.toLowerCase().replace(/\s+/ig, '_'), discovered.address, discoveredMAC, discovered.port);
              console.warn("Found *New* Supported " + Devices[discoveredMAC].toString());

              // Add the device to firebase
              deviceFirebase.child(discoveredMAC).set({
                name: discovered.name,
                address: discovered.address,
                mac: discoveredMAC,
                port: discovered.port,
                supported: true,
                driver: {
                  make    : discoveredDriver.driverDetails.make,
                  type    : discoveredDriver.driverDetails.type,
                  model   : discoveredDriver.driverDetails.model,
                  version : discoveredDriver.driverDetails.version
                }
              }); // End set()
              
              // Emit the "instantiated" event
              Devices[discoveredMAC].emit("instantiated");
              supportedDevices++;
            }
            else if(Devices[discoveredMAC]) { // Device has already been instantiated on a previous scan...
              console.warn("Found Supported " + Devices[discoveredMAC].toString());
              supportedDevices++;

              // Add the device to firebase
              deviceFirebase.child(Devices[discoveredMAC].mac).set({
                name: Devices[discoveredMAC].name,
                address: Devices[discoveredMAC].address,
                mac: Devices[discoveredMAC].mac,
                port: Devices[discoveredMAC].port,
                supported: true,
                driver: {
                  make    : drivers[i].driverDetails.make,
                  type    : drivers[i].driverDetails.type,
                  model   : drivers[i].driverDetails.model,
                  version : drivers[i].driverDetails.version
                }
              }); // End set()
            }
            else if(!Devices[discoveredMAC]) { // Print an error
              console.error("Unable to pair driver (" + discoveredDriver.driverDetails.make + ":" + discoveredDriver.driverDetails.model + ":" + discoveredDriver.driverDetails.version + ") discovered device with correct MAC address for device @ " + discovered.address);
            }
            else {
              // End if block
              supportedDevices++;
            }

          } // End inner if block
        
        }); // End drivers[i].discover()

      }
      else { // The device driver doesn't support discovery use **archaic** keyword method

        for(var n in networkDevices) { // Loop through all the network devices

          for(var k in drivers[i].driverKeywords) { // Loop through the device keywords

            if(!Devices[networkDevices[n].mac] && networkDevices[n].name.match(RegExp(drivers[i].driverKeywords[k], 'ig'))) { // If the device's name matche's a keyword:

              // Instantiate the device
              Devices[networkDevices[n].mac] = new drivers[getDriverID(drivers[i].driverDetails.make, drivers[i].driverDetails.model, drivers[i].driverDetails.version)](networkDevices[n].name, networkDevices[n].address, networkDevices[n].mac);
              console.warn("Found *New* Supported " + Devices[networkDevices[n].mac].toString());
              
              // Add the device to firebase
              deviceFirebase.child(networkDevices[n].mac).set({
                name: networkDevices[n].name,
                address: networkDevices[n].address,
                mac: networkDevices[n].mac,
                port: (networkDevices[n].port ? networkDevices[n].port : 0),
                supported: true,
                driver: {
                  make    : drivers[i].driverDetails.make,
                  type    : drivers[i].driverDetails.type,
                  model   : drivers[i].driverDetails.model,
                  version : drivers[i].driverDetails.version,
                }
              }); // End set()
              
              // Emit the "instantiated" event
              Devices[networkDevices[n].mac].emit("instantiated");
              if(Devices[networkDevices[n].mac]) supportedDevices++;

              // We found a driver via keyword, break the keyword search loop
              break;

            }
            else if(Devices[networkDevices[n].mac]) { // Device has already been instantiated on a previous scan...
              supportedDevices++;
              console.warn("Found Supported " + Devices[networkDevices[n].mac].toString());

              // Add the device to firebase
              deviceFirebase.child(Devices[networkDevices[n].mac]).set({
                name: Devices[networkDevices[n].mac].name,
                address: Devices[networkDevices[n].mac].address,
                mac: Devices[networkDevices[n].mac].mac,
                port: Devices[networkDevices[n].mac].port,
                supported: true,
                driver: {
                  make    : drivers[i].driverDetails.make,
                  type    : drivers[i].driverDetails.type,
                  model   : drivers[i].driverDetails.model,
                  version : drivers[i].driverDetails.version
                }
              }); // End set()

            }

          } // End for(var k in drivers[i].driverKeywords)

        } // End for(var n in networkDevices)

      } // End if(drivers[i].discoverable && drivers[i].discover && (drivers[i].discover instanceof Function))/else

    } // End if/else block

    // Check to see that supported devices exits
    var devCheckInterval = setInterval(function () {

      if((Date.now() - scan.lastScan > APIConfig.devices.deviceDiscoverTimeout)) { 

        if(supportedDevices <= 0) { // Warn the user that no supported devices were found:
            console.warn("No supported devices were found!\nNext network discovery scan will occur again in: " + APIConfig.devices.scanInterval + " ms.");
        }

        APIStatus.update({ status: "API Ready", last_startup_status: 0 });

        // Clear this interval to stop checking
        clearInterval(devCheckInterval);

      } // End if block

    }, 60); // End timeout

   } // End devicesInit()


  /**
   * Utility function to validate a specific device driver.
   * @param c - The device driver as a node module
   * @param f - The device driver's filename
   */
  function validateDeviceDriver (c, f) {

    if(Object.keys(c).length == 0) { // If the device driver required is empty:
      console.error("Device Driver '" + f + "' is empty!\nDid you forget to export your driver object?");
      return false;
    }

    // Make sure the device implements the 'onFirebaseData' function:
    if(!c.prototype.onFirebaseData && !(c.prototype.onFirebaseData instanceof Function)) {
      console.error("Device Driver '" + f + "' does not implement the 'onFirebaseData' method.");
      return false;
    }


    // Make sure the device defines some widgets
    if(!c.prototype.setWidgets && !(c.prototype.setWidgets instanceof Function)) {
      console.error("Device Driver '" + f + "' does not implement the 'setWidgets' method.");
      return false;
    }

    // Make sure the we implement the device details...
    if(!c.driverDetails) {
      console.error("Device Driver '" + f + "' does not define it's driver details (property 'driverDetails').");
      return false;
    }

    // Make sure the we define the keywords for the driver...
    if(!c.driverKeywords) {
      console.warn("Device Driver '" + f + "' does not define any driver keywords (property 'driverKeywords').\nIt will be unable to be paired to any network deivces.");
    }


    // Make sure the driver implements its type
    var doesImplement = c.prototype.implements(interfaces[c.driverDetails.type.toLowerCase()]);

    if(!interfaces[c.driverDetails.type.toLowerCase()] || doesImplement !== true) {
      console.error("Device Driver '" + f + "' does not fully impletment the '" + c.driverDetails.type.toLowerCase() + "' interface:");
      for(var n in doesImplement) console.error("                          - Missing method '" + doesImplement[n] + "'", true);
      return false;
    }

    return true;

  } // End validateDeviceDriver


  /**
   * Get a driver by it's make, model and version:
   */
  function getDriverID (make, model, version) {

    for(var i in drivers) {
      if(drivers[i].driverDetails.make.toLowerCase()    == make.toLowerCase() &&
         drivers[i].driverDetails.model.toLowerCase()   == model.toLowerCase() && 
         drivers[i].driverDetails.version.toLowerCase() == version.toString().toLowerCase())
          return i;
    }

    return undefined;

  } // End getDriverID()

} // --------------------------> End SmartHome Object Function
 delBook: (day) => {
   const ref = new Firebase(`https://602calendar.firebaseio.com/booked/${DateService.activeYear}/${DateService.activeMonthNum}/${day}`);
   ref.remove();
 },
Пример #30
0
    FirebaseStore.prototype.clear = function (fn) {

        var sessionRef = new Firebase('https://' + this.host + '/sessions');
        sessionRef.remove(fn);

    };