Example #1
0
/** Get all IDs */
function fetch_node_id_list() {
	var defer = q.defer();
	var query = [
		'START node=node(*)',
		'RETURN ID(node) AS id'
	].join('\n');
	var params = {};
	db.query(query, params, errors.catchfail(function (err, results) {
		if (err) {
			defer.reject(err);
			return;
		}
		
		var list = results.map(function (result) {
			return result.id;
		});
		
		defer.resolve(list);
	}));
	return defer.promise;
}
Example #2
0
User.prototype.countAllCheckins = function (facebookID) {
  var deferred = Q.defer();

  var query = [
    'MATCH (user:User {facebookID: {facebookID}})-[:hasCheckin]->(checkin:Checkin)',
    'RETURN count(checkin)'
  ].join('\n');

  var params = {
    facebookID: this.getProperty('facebookID')
  }

  db.query(query, params, function (err, results) {
    if (err) { deferred.reject(err); }
    else {
      deferred.resolve(results[0]['count(checkin)']);
    }
  });

  return deferred.promise;
};
Example #3
0
User.searchFolderContents = function (facebookID, folderName, searchQuery, page, skipAmount) {
  var deferred = Q.defer();

  var query = [
    'MATCH (user:User {facebookID: {facebookID}})-[:hasFolder]->(folder:Folder {name:{folderName}})-[contains:containsCheckin]->(checkin:Checkin)-[:hasPlace]->(place:Place)-[:hasCategory]->(category:Category)',
    'WHERE place.name =~ {searchQuery} OR place.city =~ {searchQuery} OR place.country =~ {searchQuery}',
    'RETURN user, folder, checkin, contains, place, category',
    'ORDER BY contains.createdAt',
    'SKIP { skipNum }', 
    'LIMIT { skipAmount }'
  ].join('\n');

  var params = {
    'facebookID': facebookID,
    'searchQuery': '(?i).*' + searchQuery + '.*',
    'folderName': folderName,
    'skipAmount': skipAmount,
    'skipNum': page ? page * skipAmount : 0
  };


  db.query(query, params, function (err, results) {
    if (err) { deferred.reject(err); }
    else {
      console.log(results);
      var parsedResults = _.map(results, function (item) {
        var singleResult = {
          "user": item.user.data,
          "folder": item.folder.data,
          "checkin": item.checkin.data,
          "place": item.place.data,
          "category": item.category.data
        }
        return singleResult;
      });
      deferred.resolve(parsedResults);
    }
  });
  return deferred.promise;
}
Example #4
0
User.findByInstagramID = function (instagramID) {

  var deferred = Q.defer();

  var query = [
    'MATCH (user:User {instagramID: {instagramID}})',
    'RETURN user',
  ].join('\n');

  var params = {
    instagramID: instagramID
  };

  db.query(query, params, function (err, results) {
    if (err) { deferred.reject(err); }
    else {
      deferred.resolve(new User(results[0]['user']));
    }
  });

  return deferred.promise;
};
  var addUpdatedCorpus = function(corpus) {

    corpus = JSON.stringify(corpus);

    var params = { 'corpus_data': corpus };

    var corpusQuery = [
      'MERGE (document:Corpus)',
      'ON CREATE SET document.corpus_data = {corpus_data}',
      'ON MATCH SET document.corpus_data = {corpus_data}',
      'RETURN document'
    ].join('\n');

    db.query(corpusQuery, params, function(error, results) {
      if ( error ) {
        console.log(error);
      } else {
        console.log('ADDED CORPUS', results);
      }
    }); 

  };
Example #6
0
User.prototype.getFriendsMovies = function (callback) {
  var query = [
    'MATCH (me:User)-[:FRIEND]-(f), (f)-[r:RATED]-(m:Movie)',
    'WHERE ID(me) = {userid} AND r.stars > 3 AND NOT (me)-[:RATED]->(m)', 
    'return distinct m AS movie, count(*) AS count',
    'Order BY count DESC',
    'LIMIT 10'
  ].join('\n');
  db.cypher({
    query: query,
    params: {
      userid: this.id
    },
  }, function (err, results) {
    if (err) return callback(err);

    var users = results.map(function (result) {
      return new User(result['movie']);
    });
    callback(null, users);
  });   
}
Example #7
0
    function checkAccountNickName(phone, account) {
        var query = [
            'MATCH (account:Account)',
            'WHERE account.nickName={nickName}',
            'RETURN account'
        ].join('\n');
        var params = {
            nickName: account.nickName
        };
        db.query(query, params, function (error, results) {
            if (error) {
                response.write(JSON.stringify({
                    "提示信息": "修改用户信息失败",
                    "失败原因": "数据异常"
                }));
                response.end();
                console.error(error);
                return;
            } else if (results.length == 0) {
                modifyAccountNode(phone, account);
//                response.write(JSON.stringify({
//                    "提示信息": "修改用户信息失败",
//                    "失败原因": "用户不存在"
//                }));
//                response.end();
            } else {
                var accountData = results.pop().account.data;
                if (accountData.phone == phone) {
                    modifyAccountNode(phone, account);
                } else {
                    response.write(JSON.stringify({
                        "提示信息": "修改用户信息失败",
                        "失败原因": "昵称已存在"
                    }));
                    response.end();
                }
            }
        });
    }
Example #8
0
      'RETURN w   LIMIT ' + params.limit, params, function(err, data) {
      if (err) console.log(err);
      var recommendations = utils.makeData(data, 'w');
      // console.log(recommendations)

      var recommendationsJSON = JSON.stringify({recommendations: recommendations});
      res.end(recommendationsJSON);

      // mark each recommendation as seen.
      for (var i = 0; i < recommendations.length; i++) {

        params = {username: req.body.username, url: recommendations[i].url};
        console.log('seen', params);

        cypher = "MATCH (w:Work {url: ({url}) }), (u:User {username: ({username}) }) MERGE u -[:SEEN {timestamp: timestamp()} ] ->  w return w.url limit 1";
        db.query(cypher, params, function(err, data){
          if(err) console.log(err);
          console.log('seen2 ', data);
        });
      }

    })
Example #9
0
module.exports = function (req, res) {

    // The actual cypher query used to get the node and its children
    var query = `
        MATCH (b:Node) - [:HAS_PARENT*0..] -> (r:Node)
        WHERE r.id = {id}
        OPTIONAL MATCH (a:Node) - [:HAS_PARENT] -> (b)
        OPTIONAL MATCH (b:Node) - [:HAS_VALUE] -> (v)
        RETURN b AS node, collect(a.id) AS children, head(collect(v)) AS value`;

    // Execute the query and return the response
    db.cypher({
        query: query,
        params: {
            id: req.params.id
        }
    }, function (err, results) {

        // Something went wrong
        if (err) throw err;

        // Node does not exist
        if(!results.length) {
            res.status(404);
            return res.send('Node not found');
        }

        // Found a node with children, create a tree out of it.
        var node = tree.makeTree(results, req.params.id);

        // Just for presentation purposes, format the output
        // Can be stripped out for less overhead.
        var json = JSON.stringify(node, null, 4);

        return res.send(json);
    });


}
Example #10
0
db.authenticateUser = function( userInfo, callback){
  console.log('inside authenticateUser')
  var params = {
      username: userInfo.body.username,
      password: userInfo.body.password
    }
  db.query('MATCH (n:User {username: ({username})}) RETURN n',params, function(err,data) {
    if(err) {console.log('OptionalMatch error: ',err)};
    // if the user exists
    if (data.length) {
      var node = data[0].n.data;
      var username = node.username;
      var password = node.password;
      console.log('thepassword: ',password);
      // hash the password and check if it matches
      bcrypt.compare(params.password,password, function(err,match){
        // if the password matches
        if(match){
          console.log('matchh')
          var token = jwt.encode(username, 'secret');
          var expires = moment().add(7, 'days').valueOf();
          console.log('token in routes js = ', token, 'expires', expires)
          var tokenData = {}
          tokenData.token = token;
          tokenData.expires = expires;
          tokenData = JSON.stringify(tokenData)
          console.log('tokenData :',tokenData)
          callback('sendToken',tokenData);
          // res.json({token: token, expires: expires});
        } else {
          // if the password doesn't match
          console.log('Wrong password')
          callback('wrong password')
          // res.send('Wrong password');
        }
      })
    }
  })
}
Example #11
0
router.get('/categories', function(req, res, next) {
  console.log('search call')
  console.log('req.query from search:', req.query )
  console.log('req.body from search:', req.body )
  console.log('req.headers from search:', req.headers )
  var searchTarget = req.headers.target || req.query.target|| req.body.searchTarget
  // var searchTarget = req.query.target;
  var query = [
   'MATCH (m:Movie {category: {searchTarget}}) RETURN m'
  ].join('\n');
  var params = {
    searchTarget: searchTarget
  };
  db.cypher({
    query: query,
    params: params
  }, 
    function(err, movies){
      if (err) throw err;
      res.status(200).send(movies);
  });
});
User.addUserRelationship = function(relation, userId, otherId, callback) {
	switch (relation) {
		case 'follow':
			var qp = {
				query: [
					'MATCH (user:User),(other:User)',
					'WHERE ID(user) = {userId} AND ID(other) = {otherId}',
					'MERGE (user)-[rel:follows]->(other)',
					'ON CREATE SET rel.timestamp = timestamp()',
					'RETURN rel'
				].join('\n'),
				params: {
					userId: userId,
					otherId: otherId,
				}
			}
		break;
		case 'unfollow':
			var qp = {
				query: [
					'MATCH (user:User) -[rel:follows]-> (other:User)',
					'WHERE ID(user) = {userId} AND ID(other) = {otherId}',
					'DELETE rel'
				].join('\n'),
				params: {
					userId: userId,
					otherId: otherId,
				}
			}
		break;
	}

	db.cypher(qp, function (err, result) {
		console.log(err);
		console.log('result');
		console.log(result);
		callback(err);
	});
}
Example #13
0
User.prototype.getFollowingAndOthers = function (callback) {
    // Query all users and whether we follow each one or not:
    var query = [
        'MATCH (user:User {username: {thisUsername}})',
        'MATCH (other:User)',
        'OPTIONAL MATCH (user) -[rel:follows]-> (other)',
        'RETURN other, COUNT(rel)', // COUNT(rel) is a hack for 1 or 0
    ].join('\n')

    var params = {
        thisUsername: this.username,
    };

    var user = this;
    db.cypher({
        query: query,
        params: params,
    }, function (err, results) {
        if (err) return callback(err);

        var following = [];
        var others = [];

        for (var i = 0; i < results.length; i++) {
            var other = new User(results[i]['other']);
            var follows = results[i]['COUNT(rel)'];

            if (user.username === other.username) {
                continue;
            } else if (follows) {
                following.push(other);
            } else {
                others.push(other);
            }
        }

        callback(null, following, others);
    });
};
Individual.getById = function(id, callback) {
  var query = [
    'START person=node:INDEX_NAME(INDEX_KEY="INDEX_VAL")',
    'WHERE person.Id="PERSON_ID"',
    'RETURN person',
    'LIMIT 1'
  ].join('\n')
    .replace('INDEX_NAME', INDEX_NAME)
    .replace('INDEX_KEY', INDEX_KEY)
    .replace('INDEX_VAL', INDEX_VAL)
    .replace('PERSON_ID', id);

  //TODO: Figure out why the params are being ignored
  var params = { personId: id };

  db.query(query, params, function(err, results) {
    if (err) return callback(err);

    var person = results[0] && results[0]['person'];
    callback(null, new Individual(person));
  });
};
Example #15
0
User.prototype.del = function (callback) {
    // use a Cypher query to delete both this user and his/her following
    // relationships in one transaction and one network request:
    // (note that this'll still fail if there are any relationships attached
    // of any other types, which is good because we don't expect any.)
    var query = [
        'MATCH (user:User)',
        'WHERE ID(user) = {userId}',
        'DELETE user',
        'WITH user',
        'MATCH (user) -[rel:follows]- (other)',
        'DELETE rel',
    ].join('\n')

    var params = {
        userId: this.id
    };

    db.query(query, params, function (err) {
        callback(err);
    });
};
Example #16
0
Agent.createEvent = function (a, b, amount, relType, dateTime, callback){
    var query = [
      'MATCH (a:Agent), (b:Agent)',
      'WHERE a.name = {aName} AND b.name = {bName}',
      'CREATE (a)-[r:'+relType+' {amount: {amount}, dateTime: {dateTime}}]->(b)',
      'return r'
    ].join('\n');

    var params = {
      aName: a.name,
      bName: b.name,
      amount: amount,
      dateTime: dateTime
    };

    db.query(query, params, function (err, results) {
        if (err){
          return callback(err, null);
        }
        callback(null, null);
    });
}
Example #17
0
Location.create = function (data, callback) {
    // construct a new instance of our class with the data, so it can
    // validate and extend it, etc., if we choose to do that in the future:

    // but we do the actual persisting with a Cypher query, so we can also
    // apply a label at the same time. (the save() method doesn't support
    // that, since it uses Neo4j's REST API, which doesn't support that.)
    var query = [
        'CREATE (location:Location {data})',
        'RETURN location',
    ].join('\n');

    var params = {
        data: data
    };

    db.query(query, params, function (err, results) {
        if (err) return callback(err);
        var location = new Location(results[0]['location']);
        callback(null, location);
    });
};
Example #18
0
exports.main = function(req, res) {
  db.getNodeById(req.session.userId, function (err, user) {
    req.session.user = user;
    if(req.session.labels === 'Minion') {
      var params = {job: req.session.user.data.job, complement: 'Lord'};
      } else {
      var params = {job: req.session.user.data.job, complement: 'Minion'};
      };
    db.query('MATCH (n:'+params.complement+')\nWHERE n.job = ({job})\nRETURN n',params, function ( err, sameJob) {
    if(err) {
      console.log(err);
      res.redirect('/');
    } else {
        res.render('home', {
          user: req.session.user,
          others: sameJob,
          otherstatus: params.complement
        })
      }
    })
  })
};
Example #19
0
Checkin.getComments = function (checkinID){
  var deferred = Q.defer();

  var query = [
  'MATCH (user)-[:madeComment]->(comment:Comment)-[:gotComment]->(checkin:Checkin {checkinID: {checkinID}})',
  'RETURN user, comment'
  ].join('\n');

  var params = {
    'checkinID': checkinID
  }

  db.query(query, params, function (err, results){
    if (err) { deferred.reject(err) }
    else {
      console.log("comments query: ", results)
      deferred.resolve(results)
    }
  });

  return deferred.promise;
};
Example #20
0
Checkin.getHypes = function (checkinID) {
  var deferred = Q.defer();

  var query = [
  'MATCH (user)-[connection:hasBucket]->(checkin:Checkin {checkinID: {checkinID}})',
  'RETURN user, connection'
  ].join('\n');

  var params = {
    'checkinID': checkinID
  };

  db.query(query, params, function (err, results)  {
    if (err) { deferred.reject(err); }
    else {
      console.log(results);
      deferred.resolve(results);
    }
  });

  return deferred.promise;
};
Example #21
0
Program.prototype.getPastPrograms = function (callback) {
    var query = [
        'START program=node({programId}), other=node:nodes(type="program")',
        'MATCH p = program -[*..15]-> other',
        'RETURN p, other'
    ].join('\n')
        .replace('INDEX_NAME', INDEX_NAME)
        .replace('INDEX_KEY', INDEX_KEY)
        .replace('INDEX_VAL', INDEX_VAL)
        .replace('FOLLOWS_REL', FOLLOWS_REL);

    var params = {
        programId: this.id,
    };

    var program = this;
    db.query(query, params, function (err, results) {
        if (err) return callback(err);
        
        callback(null, results);
    });
};
Example #22
0
  var retrieveCorpus = function() {

    var getQuery = [
      'MATCH (document:Corpus)',
      'RETURN document'
    ].join('\n');

    db.query(getQuery, {}, function(error, results) {
      if ( error ) {
        console.log(error);
      } else {
        var existing = {};
        if ( results.length !== 0 ) {
          existing = results[0].document._data.data.corpus_data; //Extra data here
          existing = JSON.parse(existing);
        }

        editCorpus(existing);
      }
    });

  };
Example #23
0
Actor.prototype.getMoviesAndOthers = function (callback) {
    // query all actors and whether we follow each one or not:
    var query = [
        'START actor=node({actorId}), other=node:INDEX_NAME(INDEX_KEY="INDEX_VAL")',
        'MATCH (actor) -[rel?:_REL]-> (other)',
        'RETURN other, COUNT(rel)'  // COUNT(rel) is a hack for 1 or 0
    ].join('\n')
        .replace('INDEX_NAME', INDEX_NAME)
        .replace('INDEX_KEY', INDEX_KEY)
        .replace('INDEX_VAL', INDEX_VAL_MOVIE)
        .replace('_REL', _REL);

    var params = {
        actorId: this.id,
    };

    var actor = this;
    db.query(query, params, function (err, results) {
        if (err) return callback(err);

        var movies = [];
        var others = [];

        for (var i = 0; i < results.length; i++) {
            var other = new Movie(results[i]['other']);
            var acts = results[i]['COUNT(rel)'];

            if (actor.id === other.id) {
                continue;
            } else if (acts) {
                movies.push(other);
            } else {
                others.push(other);
            }
        }

        callback(null, movies, others);
    });
};
Example #24
0
User.prototype.del = function (callback) {
    // Use a Cypher query to delete both this user and his/her following
    // relationships in one query and one network request:
    // (Note that this'll still fail if there are any relationships attached
    // of any other types, which is good because we don't expect any.)
    var query = [
        'MATCH (user:User {username: {username}})',
        'OPTIONAL MATCH (user) -[rel:follows]- (other)',
        'DELETE user, rel',
    ].join('\n')

    var params = {
        username: this.username,
    };

    db.cypher({
        query: query,
        params: params,
    }, function (err) {
        callback(err);
    });
};
Example #25
0
exports.addNewContent = function (request, reply){

    var genUUID = uuid.v4();
    
    //query for creating the content and relationships to tagged terms
    var query = [
        "CREATE (contentNode:content:testContent:testtest {contentParams})-[r:HAS_META {languageCode: {lang} }]->(metaNode:contentMeta {metaParams}) ",
        "WITH contentNode MATCH (termNode:term) ",
        "WHERE termNode.UUID IN {taggedTermsUUID} ",
        "CREATE (contentNode)-[:TAGGED_WITH]->(termNode)"
    ].join('\n');

    var params = {
        contentParams: {
            UUID: genUUID,
            dateAdded: new Date(),
            languageAddedIn: request.payload.language,
            displayType: request.payload.displayType,
            fileSystemID: request.payload.fileSystemID, 
            embedSrc: request.payload.embedSrc, 
            webURL: request.payload.webURL,
            savedAs: request.payload.savedAs, 
        },
        taggedTermsUUID: [],
        lang: request.payload.language,
        metaParams: request.payload.meta
    };

    //populate term UUID array
    for (var i = 0; i < request.payload.assignedTerms.length; i++) {
        params.taggedTermsUUID.push(request.payload.assignedTerms[i].UUID);
    }

    db.query(query, params, function (err, results) {
        if (err) {console.log("neo4j error: " + err);}
        reply({UUID:genUUID}); 
    });

};
Example #26
0
User.prototype.getFollowingAndOthers = function (callback) {
    // query all users and whether we follow each one or not:
    var query = [
        'START user=node({userId}), other=node:INDEX_NAME(INDEX_KEY="INDEX_VAL")',
        'OPTIONAL MATCH (user) -[rel:FOLLOWS_REL]-> (other)',
        'RETURN other, COUNT(rel)'  // COUNT(rel) is a hack for 1 or 0
    ].join('\n')
        .replace('INDEX_NAME', INDEX_NAME)
        .replace('INDEX_KEY', INDEX_KEY)
        .replace('INDEX_VAL', INDEX_VAL)
        .replace('FOLLOWS_REL', FOLLOWS_REL);

    var params = {
        userId: this.id,
    };

    var user = this;
    db.query(query, params, function (err, results) {
        if (err) return callback(err);

        var following = [];
        var others = [];

        for (var i = 0; i < results.length; i++) {
            var other = new User(results[i]['other']);
            var follows = results[i]['COUNT(rel)'];

            if (user.id === other.id) {
                continue;
            } else if (follows) {
                following.push(other);
            } else {
                others.push(other);
            }
        }

        callback(null, following, others);
    });
};
Example #27
0
	findNode: function(contains,socket)
	{
		var socket = socket;
		socket.emit('test');
		var tRetourne = [];
		db.cypher(
		{
			query: "MATCH (n:mot) WHERE n.label =~ {label} RETURN n.label;",
			params:
			{
				label: '(?i)'+contains+'.*',
			},
		},

		function (err, results)
		{
			if(err) throw err;
			for(i = 0; i<results.length;i++)
	    	{
			    if (!results[i])
			    {
			        console.log('Mot inexistant dans la base');
			    }
			    else
			    {
			    	//console.log(results[i]['n.label']);
			    	tRetourne.push(results[i]['n.label']);
			    	//console.log(tRetourne[i]);
			    }
	    	}
	    	tRetourne.forEach(function(mot)
	    	{
	    		console.log(mot);
	    	});
	    	socket.emit('nodeFound',tRetourne);
	    	return tRetourne;
		});
	},
Example #28
0
User.fetchSuggestedByFriendsContents = function (facebookID, page, skipAmount) {
  var deferred = Q.defer();

  var query = [
    'MATCH (user:User{facebookID:{facebookID}})<-[:receivedSuggestion]-(suggestion:Suggestion)<-[:gaveSuggestion]-(suggester:User)',
    'MATCH (suggestion)-[:beenSuggested]-(checkin:Checkin)-[:hasPlace]->(place:Place)',
    'MATCH (suggestionSource:User)-[:hasCheckin]->(checkin)',
    'RETURN user, suggester, suggestionSource, checkin, place',
    'ORDER BY suggestion.time DESC',
    'SKIP { skipNum }', 
    'LIMIT { skipAmount }'
  ].join('\n');

  var params = {
    'facebookID': facebookID,
    'skipAmount': skipAmount,
    'skipNum': page ? page * skipAmount : 0
  };

  db.query(query, params, function (err, results) {
    if (err) { deferred.reject(err); }
    else {
      console.log(results);
      var parsedResults = _.map(results, function (item) {
        var singleResult = {
          "user": item.suggestionSource.data,
          "suggester": item.suggester.data,
          "checkin": item.checkin.data,
          "place": item.place.data
        }
        return singleResult;
      });
      deferred.resolve(parsedResults);
    }
  });

  return deferred.promise;
}
Example #29
0
    node.save(function (err, node) {        
        if (n > 1) {
            if (err) {
                console.error('Error saving new node to database:', err);
            } else {
                console.log('Node saved to database with id:', node.id);
            }
           var oldBlockId = node.id - 1;               
           db.getNodeById(oldBlockId, function (err, oldBlock) {
                node.createRelationshipFrom(oldBlock, "Block", {}, function (err, relationship) {
                   console.log(relationship.toString());
                   n = n + 1;
                   startingUrl = "https://blockchain.info/rawblock/" + n;            
                   crawlBlockchain(startingUrl); 
	            });
            });
        } else {
            saveNode(node);
            n = n + 1;
            startingUrl = "https://blockchain.info/rawblock/" + n;            
            crawlBlockchain(startingUrl);
        };
    });
Example #30
0
		ref.authWithPassword(req.body, function(error, authData) {
			if (error) {
    			res.status(400).send(error);
  			} else {
  				neodb.cypher({
  					query: "MATCH (u:User {username: {username}}) RETURN u",
  					params: {
  						username: authData.password.email
  					}
  				}, function(err, results) {
  					if (err) {
  						console.log("Neo4j error: " + err);
  					}
  					else {
  						var result = results[0];
  						if (!result) {
  							addUser(authData.password.email);
  						}
  					}
  				});
  				res.cookie("currentUser", authData.password.email).send("set current user");
  			}
		});