Пример #1
0
app.get("/:rid", function( req, res ){
  // find request format, json or html?
  var path = req.params.rid.split(".json");
  var rid = path[0];

  var myRootRef = new Firebase("https://nodeknockout.firebaseIO.com/"+rid)
  myRootRef.once( "value", function( snapshot ){
    var info = snapshot.val();
    if( !info ){
      res.redirect('/');
      return
    }
    console.log( info );
    if( info.sid && info.sid.length > 3 ){
      console.log( "session id generated" );
      console.log( info.sid );
      returnRoomResponse( res, { rid: rid, sid: info.sid }, path[1]);
    }else{
      console.log(" no session id found ");
      OpenTokObject.createSession(function(sessionId){
        console.log( "sessionId generated" );
        console.log( sessionId );
        myRootRef.child( "sid" ).set( sessionId, function(){
          console.log( "set session id" );
          console.log( sessionId );
          returnRoomResponse( res, { rid: rid, sid: sessionId }, path[1]);
        });
      });
    }
  });
});
Пример #2
0
app.get('/', function(req, res) {
  var dataRef = new Firebase(firebaseUrl),
    url = req.query.url,
    reset = req.query.reset;

  if (reset) {
    var url = "";
    var dataRef = new Firebase(firebaseUrl);
    dataRef.set(url);

    res.redirect("/");
  } else {
    if (url) {
      if (isValidUrl(url)) {
        url = hasHttpPrefix(url) ? url : "http://" + url;
        console.log(url);

        var dataRef = new Firebase(firebaseUrl);
        dataRef.set(url);
      }

      res.redirect("/");
    } else {
      dataRef.once('value', function(data) {
        var url = data.val();

        res.render("index.html", {
          firebaseUrl: firebaseUrl,
          url: url
        });
      });
    }
  }
});
Пример #3
0
exports.getGroup = function(req, res) {
  var uid = req.params.uid;
  var groupRef = req.params.groupRef;

  var db = new Firebase('https://kiwidb.firebaseio.com/users/facebook:' + uid);
  db.auth('4sMMNGVsvzGbQgTcuTnpOmD7ZUb3JSFsjelHrhaj');
  db.once('value', function(snapshot) {
    var user = snapshot.val();
    if (user) {
      // either group doesn't exist or it's public attr is set to false
      if (!user.groups[groupRef] || !user.groups[groupRef].isPublic ) {
        res.send(404);
        // TODO: would this be needed to stop function?
        return;
      }
      var group = user.groups[groupRef];
      group.kiwis = [];
      var hashes = group.kiwiHashes;
      for(var i = 0; i < hashes.length; i++) {
        // data should be in sync b/t kiwis and groups but check anyway
        if (user.kiwis[hashes[i]]) {
          group.kiwis.push(user.kiwis[hashes[i]]);
        }
      }
      res.send(group);
    } else {
      // not a user
      res.send(404);
    }
  }, function(err) {
    console.log('Error processing request');
  });

};
Пример #4
0
exports.danger = function(req, res) {
  var userList = new Firebase("https://guardianangel.firebaseio.com/users");
  var id = req.params.id;
  var minLevel = req.params.level;
  var key;
  var inDangerUsers = [];

  userList.once('value', function(snapshot) {
    var users = snapshot.val();
    var user = snapshot.val()[id];
    for(key in users) {
      if (users.hasOwnProperty(key)) {
        if(key === id) {
          continue;
        }
        if(users[key].latitude - user.latitude < 1 &&
          users[key].longitude - user.longitude < 1) {
            if(users[key].dangerLevel >= minLevel) {
              inDangerUsers.push(users[key]);
            }
          }
    }
  }
  res.set('Content-Type', 'application/json');
  res.send(inDangerUsers);
  });
  
};
Пример #5
0
var adherenceJob = new cronJob( '1 4 * * *', function() { //FIXME date/time issue
  adherenceRef.once("value", function(snapshot) {
    console.log("Checking Adherence patterns: ");
    var adherenceDB = snapshot.val();

    for(var patientID in adherenceDB) {
      //If patient responded yesterday, reset adherence measures
      if(adherenceDB[patientID][textedHelpers.dateString(-1)] == '1') {
        console.log("Took meds yesterday.");
        textedHelpers.updateUser(usersRef, patientID, 'missedDoseCounter', 0, 'MISSED_DOSES_ALERT_MSG_FLAG', false);
        continue;
      }

      //Check to see if a missed dose flag message needs to be sent.
      else {
        console.log(patientID + " Didn't take meds yesterday");
        var maxMissed = textedHelpers.missedDoseAlertMsgDays[textedHelpers.missedDoseAlertMsgDays.length -1];
        console.log("Max missed is: " + maxMissed);
        if (textedHelpers.missedDoseAlertMsgDays.indexOf(usersDB[patientID].missedDoseCounter) != -1) { //Send out message on day 3 of missed dose
          if(usersDB[patientID].missedDoseCounter == maxMissed) {
            textedHelpers.updateUser(usersRef, patientID, 'FINAL_MISSED_DOSE_ALERT_MSG_FLAG', true);
          }
          else if (usersDB[patientID].missedDoseCounter > maxMissed) {
            textedHelpers.updateUser(usersRef, patientID, 'donotsend', true);
          }
          else textedHelpers.updateUser(usersRef, patientID, 'MISSED_DOSES_ALERT_MSG_FLAG', true);
        }
        textedHelpers.updateUser(usersRef, patientID, 'missedDoseCounter', usersDB[patientID].missedDoseCounter + 1);
      }
    }
  });
}, null, true);
Пример #6
0
 static getAllMotocycles(cb){
     var ref = new Firebase("https://smart-bike.firebaseio.com/motocycles");
     ref.once("value", function(data) {
        if(typeof cb == 'function')
             cb.call(null, data.val()); 
     });
 }
Пример #7
0
app.get("/:rid", function( req, res ){
  // find request format, json or html?
  var path = req.params.rid.split(".json");
  var rid = path[0];
  var roomRef = new Firebase("https://rtcdemo.firebaseIO.com/room/" + rid);

  // on incoming request, make sure we have presenceListener to remove the room if it is empty
  if( !presenceListener[rid] ){
    presenceListener[rid] = true
    var presenceRef = new Firebase("https://rtcdemo.firebaseIO.com/room/" + rid + "/users");
    presenceRef.on('value', function(dataSnapshot){
      if(dataSnapshot.numChildren() == 0){
        // remove room if there is no one in the room
        roomRef.remove();
      }
    });
  }

  // Generate sessionId if there are no existing session Id's
  roomRef.once('value', function(dataSnapshot){
    var sidSnapshot = dataSnapshot.child('sid');
    var sid = sidSnapshot.val();
    if(!sid){
      OpenTokObject.createSession(function(sessionId){
        sidSnapshot.ref().set( sessionId );
        returnRoomResponse( res, { rid: rid, sid: sessionId }, path[1]);
      });
    }else{
      returnRoomResponse( res, { rid: rid, sid: sid }, path[1]);
    }
  });
});
Пример #8
0
  constructor(props) {

    super(props);

    var categoryList = this;

    this.firebaseRef = new Firebase('https://reactnatodo.firebaseio.com/');

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    this.firebaseRef.once('value')
    .then(function(snapshot) {
      var data = snapshot.val();

      console.log('data from firebase', data);

      var clonedList = ds.cloneWithRows(data);

      categoryList.setState({
        categoryList: clonedList
      });
    })
    .catch(function(error) {
      console.log('Error:', error);
    });

    // Initialize empty datasource
    var clonedList = ds.cloneWithRows([]);

    this.state = {
      categoryList: clonedList
    };
  }
Пример #9
0
Файл: event.js Проект: Johj/fapp
  queryData() {
    var myBlob = [];
    var self = this;

    // this section loads the postIDs into myBlob and pushes them to dataSource
    database.once("value", function(snapshot){
      var eventsSnapshot = snapshot.child("events");
      eventsSnapshot.forEach(function(eventSnapshot) {
        if (eventSnapshot.val().isPublic){
          myBlob.push(eventSnapshot);
        }
      });
      var usersEvents = snapshot.child("users/" + database.getAuth().uid + "/eventsList");
      usersEvents.forEach(function(eventIdSnapshot) {
        var eventToPush = snapshot.child("events/" + eventIdSnapshot.val().eventId);

        var isIn = false;
        for (var i = 0; i < myBlob.length; i++){
          if (myBlob[i].key() === eventToPush.key()){
            isIn = true;
          }
        }
        if (!isIn){
          myBlob.push(eventToPush);
        }
      });
      self.setState({dataSource: myBlob});
    });
  }
Пример #10
0
 function(accessToken, refreshToken, profile, done) {
   // asynchronous verification, for effect...
   
       //save provider, id, display
       var p = {
           "provider": profile.provider,
           "id": profile.id,
           "displayName": profile.displayName,
       }
       var user = new Firebase(fbURL + '/users/' + profile.id);
       user.once('value', function(snapshot){
           if(snapshot.val() == null){
               //create that user
               console.log('creating user...');
               var users = new Firebase(fbURL + '/users');
               users.child(p.id).set(p, function(e){
                   if(e){console.log('problem creating user', e);}
                   else{console.log('created user');}
               });
           }
       });
       console.log('logged in: ', p);
       return done(null, p);
   
 }
Пример #11
0
app.get('/messages', function(req, res) {
  ref.once("value", function(snapshot){
    var messages = snapshot.val();
    res.send(messages);
  })

});
Пример #12
0
 ref.remove(function(err) {
    expect(err).to.be.null;
    fb.once('value', function(snap) {
       expect(snap.val()).to.be.null;
       done();
    })
 })
Пример #13
0
  grabFulfillmentsBelongingToRequest(inputKey) {
    console.log('----------------------input request key -------------------')
    console.log(inputKey)
    console.log('----------------------input request key -------------------')
    var that = this;
    var ref = new Firebase("https://snapdrop.firebaseio.com/fulfillments");
    ref.once("value", function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        var requestKey = childSnapshot.val().requestKey;
            console.log('----------------------looping request key -------------------')
    console.log(requestKey)
    console.log('----------------------input request key -------------------')
        var childData = childSnapshot.val();
        if (requestKey === inputKey) {
          var fulfillment = {
            caption: childSnapshot.val().caption,
            image: childSnapshot.val().requestImage,
            fulfillerUID: childSnapshot.val().userUID
          }
          that.state.requestFulfillments.push(fulfillment);

          that.setState({
            dataSource: that.state.dataSource.cloneWithRows(that.state.requestFulfillments),
            loaded: true,
          });

        };
      });
    });
  }
Пример #14
0
(function testFireBase() {
    var myFirebase = new Firebase("https://node-test-jc.firebaseio.com/books");
    
    /*
    myFirebase.push({
        title: "Hello World!",
        author: "Firebase",
        location: {
            city: "San Francisco",
            state: "California",
        zip: 94103
        }
    });*/
    
    var count = 0;
    
    myFirebase.on("child_added", function(snap) {
      count++;
      console.log("added", snap.key());
    });
    
    myFirebase.once("value", function(snap) {
  console.log("initial data ("+ count +") loaded!", Object.keys(snap.val()).length === count);
});
    

    
})();
Пример #15
0
    FirebaseStore.prototype.reap = function(fn) {

        var sessionRef = new Firebase('https://' + this.host + '/sessions/');
        var count = 0;
        var now = +new Date;
        var removeList = [];

        sessionRef.once('value', function (snapshot) {
            if (snapshot && snapshot.val()) {
                snapshot.forEach(function(session) {
                    if (session.val().expires < now) {
                        removeList.push(session.key());
                    }
                });
            }

            if(removeList.length === 0 && fn) return fn(null, null);

            removeList.forEach(function(sessionId) {
                sessionRef.child(sessionId).remove(function() {
                    if(++count === removeList.length && fn) {
                        return fn(null, removeList);
                    }
                });
            });

        });


    };
Пример #16
0
    FirebaseStore.prototype.get = function (sid, fn) {

        var self = this;
        sid = this.cleanSid(sid);
        var now = +new Date;
        var sessionRef = new Firebase('https://' + this.host + '/sessions/' + sid);

        sessionRef.once('value', function (snapshot) {
            try {
                if (!snapshot || snapshot.val() === null) {
                    return fn(null, null);
                } else {
                    if (!snapshot.val()) return fn(null, null);
                    else if (snapshot.val().expires && now >= snapshot.val().expires) {
                        self.destroy(sid, fn);
                    } else {
                        var sess = snapshot.val().sess.toString();
                        sess = JSON.parse(sess);
                        return fn(null, sess);
                    }
                }
            } catch (err) {
                fn(err);
            }
        });

    };
Пример #17
0
  queryData() {
    var myBlob = [];
    var self = this;

    database.once("value", function(snapshot) {
      // user
      var usersnapshot = snapshot.child("users/" + self.props.state);
      var proPic = usersnapshot.val().profilePic.uri;

      // posts
      var userPostsSnapshot = usersnapshot.child("postList");
      userPostsSnapshot.forEach(function(userPostSnapshot) {
        var postSnapshot = snapshot.child("posts/" + userPostSnapshot.val().postId);
        myBlob.push(postSnapshot);
      });

      myBlob.sort((a, b) => {
        return b.val().date - a.val().date;
      });

      self.setState({
        items: myBlob,
        name: usersnapshot.val().firstName + " " + usersnapshot.val().lastName,
        profilePic: proPic,
      });
    });
  }
Пример #18
0
 function loadContacts() {
     /*This is the Firebase request for data*/
     var fb = new Firebase('https://tiycontactapp.firebaseio.com/contacts/');
     fb.once('value', function (hedgehog) {
         var fbContacts = hedgehog.val();
         var fbArray = Object.keys(fbContacts);
         console.log('fbArray is: ');
         console.log(fbArray);
         for (var i = 0; i < fbArray.length; i++) {
             var contactData = template({
                 id: fbContacts[fbArray[i]].id,
                 name: fbContacts[fbArray[i]].name,
                 phone: fbContacts[fbArray[i]].phone,
                 email: fbContacts[fbArray[i]].email,
                 relation: fbContacts[fbArray[i]].relation,
                 invited: fbContacts[fbArray[i]].invited,
             });
             var contact = document.createElement('div');
             contact.classList.add('contacts');
             //Set the ID for this element.
             contact.setAttribute('id', 'contact-' + fbContacts[fbArray[i]].id);
             contact.innerHTML = contactData;
             var parent = document.getElementById('contact-display');
             parent.appendChild(contact);
         } /*End of for loop. Include this when commenting out the for Loop*/
         $('.contacts').draggable({
             helper: 'clone',
             opacity: 0.50,
             scroll: false,
             revert: true,
         });
     });
 } /*End of the loadContacts function*/
Пример #19
0
app.use((req, res, next)=> {

    var url = req.originalUrl;
    var store = {
        ArticleStore: {
            articles: [],
            articlesLoading: true
        }
    };

    if (url === '/') {
        let fbRef = new Firebase('https://chicagowepapp.firebaseio.com/articles');
        fbRef.once('value', (data)=> {
            var articles = data.val();
            store.ArticleStore.articles = articles;
            store.ArticleStore.articlesLoading = false;
            res.locals.data = JSON.stringify(store);
            next()
        });
    } else {

        res.locals.data = JSON.stringify(store);
        next();
    }
});
Пример #20
0
app.get('/', function(req, res) {
  ref.once("value", function(snapshot){
    var info = snapshot.val();
    res.send(info);
  })

});
Пример #21
0
activitiesRef.on("child_added", function(snapshot){
  var activity = snapshot.val();
  var activityId = snapshot.key();
  
  // get userId from activity.
  var userId = activity.userId;
  console.log("activity id " + snapshot.key());
  
  // get live challenges from user
  var liveChallengeRef = new Firebase(config.firebase.url + "/live_challenges/" + userId + "/active");
  liveChallengeRef.once("value").then(function(liveChallenges){
    // go through all live active challenges
    liveChallenges.forEach(function(challenge) {
      console.log("live challenge id " + challenge.key());
      
      // get info of the challenge
      var publicChallengeRef = new Firebase(config.firebase.url + "/public_challenges/" + challenge.key());
      publicChallengeRef.once("value", function(snapshot){
        var challenge = snapshot.val();
        console.log("challenge found");
         // compare activity with challenge
         
        // activity startDate > challenge startDate
        console.log("activity start date: " + activity.startDate);
        console.log("challenge start date: " + challenge.startDate);
        
        if (activity.startDate > challenge.startDate) {
          console.log("activity date counts");
          // decides if challenge progress should be updated with the activity distance or pace
          var progress = challenge.progress
          
          // 1v1
          if (challenge.type == "OneVOne"){
            switch(challenge.mode){
              case "Distance":
                  progress[userId] = activity.distance
                  
                break
              case "Speed":
                break
              case "Streak":
                break
            }
          }
          // coop
          else if (challenge.type == "Coop"){}
          
          // update challenge
          challenge.progress = progress;
          publicChallengeRef.update(challenge);
          
          // update public activity
          var publicActivityRef = new Firebase(config.firebase.url + "/public_activities/" + activityId);
          publicActivityRef.update({isNew: 'false'});
        }
      });
    });
  });
});
Пример #22
0
 componentDidMount() {
   this.db.once('value', (data) => {
     this.setState({
       loaded: true,
       data: data.val()
     }, this.printList);
   });
 }
Пример #23
0
router.get('/edit/:id', function(req, res, next) {
    var id = req.params.id;
    var genreRef = new Firebase('https://musicmanager.firebaseio.com/genres/' + id);
    genreRef.once('value', function(snapshot){
        var genre = snapshot.val();
        res.render('genres/edit', {genre: genre, id: id});
    });
});
Пример #24
0
        getDirectionsByName: function (slotName, callback) {
            var addressName = slotName;
            console.log(addressName);
            var myOrigin = {};
            var addresses = {};
            var path;
            originRef.once("value", function(originSnapshot) {
                myOrigin = originSnapshot.val();

                destinationRef.once("value", function(destinationSnapshot){
                    addresses = destinationSnapshot.val();
                    if(addressName in addresses){
                        var addressString = addresses[addressName].replace(new RegExp(' ', 'g'), "+");

                        path = "/maps/api/directions/json?" 
                        + "origin=" + myOrigin.lat + "," + myOrigin.lng
                        + "&destination=" + addressString
                        + "&key=" + googleMapsDirectionKey;

                        var options = {
                            host: 'maps.googleapis.com',
                            path: path,
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        };

                        console.log(options.host + options.path);

                        var req = https.request(options, function(res) {
                            var output = '';
                            res.setEncoding('utf8');

                            res.on('data', function (chunk) {
                                output += chunk;
                            });

                            res.on('end', function() {
                                var responseObject = JSON.parse(output);
                                var responseString = "Navigating to: " + addresses[addressName] + ". Step one: " + responseObject.routes[0].legs[0].steps[0].html_instructions.replace(new RegExp('<[^>]*>', 'g'), " ");
                                parseAndUploadSteps(responseObject);
                                callback(responseString);
                            });
                        });
                        req.end();

                        req.on('error', function(err) {
                            console.log('error fetching');
                            callback("Error connecting to server")
                        });
                    } else {
                        console.log('cannot find address');
                        callback("Cannot find address for " + addressName);
                    }
                });
            });
        },
Пример #25
0
exports.postNewRoom = function(req, res){
  req.assert('roomName', 'Name cannot be blank').notEmpty();

  var name = req.body.roomName.toLowerCase();
  var adminPass = req.body.adminPass || null;
  var creator = req.body.creator || "Anonymous";
  var creatorId = req.body.creatorId;
  var orphan = (creator == "Anonymous");

  var description = req.body.roomDescription;
  var publicCanSeeCreator = (req.body.publicCanSeeCreator == "on") || false;
  var publicCanAdd = req.body.publicCanAdd == "on";
  var publicCanDelete = req.body.publicCanDelete == "on";
  var publicShowcase = req.body.showRoomPublicly == "on";

  var roomsRef = new Firebase('https://ourtube.firebaseIO.com/rooms/' + name);
  roomsRef.auth(secrets.firebaseSecret);
  //listen to see if room already exists
  roomsRef.once('value', function(data){
    console.log('pong off firebase');
    if(data.val() == null){
      roomsRef.set(
//        {orphan: orphan, adminPass: adminPass, creator:creator, permission:{} description: description, publicCanSeeCreator:publicCanSeeCreator, publicCanAdd: publicCanAdd, publicCanDelete: publicCanDelete,  date: (new Date).toDateString(), time: (new Date).toTimeString()},
        function(error) {
          var roomList = new Firebase('https://ourtube.firebaseIO.com/roomList');
          if(publicShowcase){
            roomList.child('public').push(name);
          }else{
            roomList.child('private').push(name);
          }
        }
      );
    }else{
      console.log('room already exists');
      req.assert('', 'Room already exists, please pick a different name').notEmpty();
    }

    var errors = req.validationErrors();

    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/newRoom');
    }

    return res.redirect('/room/'+name);

  }, function(err){
    req.assert('', 'There was a problem connecting and the room was not created. Our deepest apologies, please try again later').notEmpty();

    var errors = req.validationErrors();

    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/newRoom');
    }
  });
};
Пример #26
0
 userRef.auth(firebaseAuthToken, function (err, result) {
   if (err) {
     deferredUser.reject(err);
   } else {
     userRef.once('value', function (snapshot) {
       deferredUser.resolve(snapshot.val())
     });
   }
 });
Пример #27
0
/**
 * Increment the Firebase list that tracks the total count of the tag.
 *
 * @example
 *     // Increase the tag `nodejs`'s count number'
 *     addToTagCount('nodejs');
 *
 * @param {String} tag  The name of the tag to increment, without the `@`
 * @api private
 */
function addToTagCount(tag) {
  var tagRef = new Firebase(config.firebaseV2 + '/tag_count/' + tag);

  authenticate();

  tagRef.once('value', function(snap) {
    tagRef.set((snap.val() || 0) + 1);
  });
}
Пример #28
0
app.get('/ratio5', function(req, res){
	ref.once("value", function(snapshot) {
		  console.log(snapshot.val());
		  res.json({result: snapshot.val()});
	}, function (errorObject) {
		  console.log("The read failed: " + errorObject.code);
	});

});
Пример #29
0
 ref.update({'b': { fruit: 'bangarang', legume: 'beans beans beans', veggie: 'broccolaaay' }}, function(err) {
    expect(err).to.be.null;
    fb.once('value', function(snap) {
       var data = snap.val();
       expect(data['fruit']['b']).to.equal('bangarang');
       expect(data['legume']['b']).to.equal('beans beans beans');
       expect(data['veggie']['b']).to.equal('broccolaaay');
       done();
    });
 })
Пример #30
0
  function generateAndStoreUserJWT(newUserData, reply){
    var token;
    userRef.once("value", function(snapshot){
      token = tokenGenerator.createToken(
        {uid: Object.keys(newUserData)[0], tel: newUserData.tel}
      );
      return reply("/user/restList").state('firebase_token', token, {encoding: 'none'}) ;
    });

  }