Esempio n. 1
0
def getRecommendations():
    myUser = happn.User(token)
    myUser.set_position(-19.937707, -43.935240)
    # Get recommendations
    recs = []
    for i in range(1):
        recs += myUser.get_recommendations(100, i * 100)
    recs = list(reversed(recs))

    crushes = []

    for rec in recs:
        happn_user_profile = rec['notifier']
        if happn_user_profile[u'is_accepted']:
            crushes.append(rec)

    for crushe in crushes:
        happn_user_profile = crushe['notifier']
        target_info = getTargetinfo(happn_user_profile['id'])
        social_sync = target_info['social_synchronization']
        instagram = social_sync['instagram']
        if instagram is not None:
            instagram_pictures = instagram['pictures']
            crushe.update({'instagram_pictures': instagram_pictures})
            crushe.update(
                {'instagram_number_of_pictures': len(instagram_pictures)})

    return crushes
Esempio n. 2
0
def main(args):
    # Create user object
    user = happn.User(args.token)

    # Set user position, start stopwatch
    user.set_device()
    try:
        user.set_position(42.3425227,-71.0885269)                         
    except happn.HTTP_MethodError as e:
        print 'Unable to change position due to HTTP method error: {}'.format(e.value)
        #return False
    start = datetime.now()  
    
    count = 0
    while True:
        # Set user position
        print "{} Attempts".format(count)
            
        try:
            user.set_device()
            time.sleep(10)
            user.set_position(20.3425227,-157.0885269)
        except happn.HTTP_MethodError as e: 
            time.sleep(60)
            count = count + 1
            continue
        break

    end = datetime.now()        

    print "Start Time: {}".format(start)
    print "End Time: {}".format(end)
Esempio n. 3
0
def main():
    # Create user object
    user = happn.User(args.token)

    # Set user device (uses my phone config :TODO offload to settings)
    user.setDevice()

    # Set user position
    try:
        user.set_position(args.lat, args.lon)
    except HTTP_MethodError:
        print 'Unable to change position due to HTTP method error: %s', HTTP_MethodError.value
Esempio n. 4
0
""" Test happn module """

import happn
import json
import pprint

token = 'CAAGm0PX4ZCpsBAEZCnObazwW05uWsgL1AduIn4KzdQcsuqfqVrcYb46MBsgZBgiVlqbRFdVe8IyFwGE1FleX5ue7tyRZBm1bp70O3lPjrPYcFosPmAzeEmY4sjDIQzShGvlUTpuiU0IZBrVjP5TKZAgwHZAnkDTs8L8HurFRKDWybXmZAhOtGE7Sn5L7htdnxnrRty3KZC4DGkl6PTJLangDR1HRjzFGVCqcZD'
user = happn.User(token)

settings = {
    "age": 83,
    "birth_date": "1922-01-01T00:00:00-0500",
    "credits": 40,
    "display_name": "ThroatpipeJackson",
    "first_name": "ThroatpipeJackson",
    "fb_id": 1346023834
}
test = user.set_settings(settings)
Esempio n. 5
0
def main(args):
    # Instantiate Logger
    logging.basicConfig(filename='log.log', level=logging.INFO)
    logging.info('--------------------Logger Initiated--------------------')

    # Load facebook tokens from a file
    fbtokens = None
    try:
        with open(args.fbTokenFile) as f:
            fbtokens = f.read().splitlines()
    except IOError:
        logging.warning('Unable to locate file provided')
        return
    if fbtokens is None:
        logging.warning('Token file void of tokens')
        return

    logging.info('%d Facebook tokens loaded from file', len(fbtokens))

    # Connect to database
    client = MongoClient('localhost', 27017)
    db = client.db
    db_users = db.userbase

    # Create a list of Sybils
    sybils = []
    for token in fbtokens:
        try:
            sybils.append(happn.User(token))
        except NameError:
            logging.warning(
                'Error creating sybil, moving on to next token (most likely invalid token)'
            )

    if sybils == []:
        logging.warning('No Sybils to work with, exiting')
        return

    logging.info('Completed sybil generation')

    # Each sybil will be seperated by 1000m (twice default radius) and proceed longitudinaly
    lConvFactor_km = 110.0  # Conversion fator to degrees lat/lon in km
    lConvFactor_m = 110000.0  # Conversion fator to degrees lat/lon in m
    r_m = 500
    r_l = r_m * 2 / lConvFactor_m  # Conversion to degrees lat/lon

    targetLat = args.width * lConvFactor_km
    targetLon = args.height * lConvFactor_km

    # Generate sybil positions
    x = [args.lat]
    y = args.lon
    for __ in range(1, len(sybils)):
        x.append(x[-1] + r_l)

        # Calculate time to completion
    s_mi = args.width * args.height
    s_km = s_mi * 2.58999

    m_to_completion = (s_km / len(sybils)) * 21
    h_to_completion = m_to_completion / 60
    d_to_completion = h_to_completion / 24

    print("\nWith {} sybils {} mi^2 will take:\n"
          "     {} minutes\n"
          "     {} hours\n"
          "     {} days\n\n".format(len(sybils), s_mi, m_to_completion,
                                    h_to_completion, d_to_completion))

    s_km_count = 0  # Progress counter
    while max(x) < targetLat:
        y = args.lon

        while y < targetLon:

            for idx, user in enumerate(sybils):

                # Command line progress updates (SE inspired)
                percent = s_km_count / s_km
                bar_length = 40
                hashes = '#' * int(round(percent * bar_length))
                spaces = ' ' * (bar_length - len(hashes))
                sys.stdout.write("\rPercent: [{0}] {1}%".format(
                    hashes + spaces, int(round(percent * 100))))
                sys.stdout.flush()

                # Try position change until it works
                while True:
                    try:
                        user.set_device()
                        user.set_position(x[idx], y)

                    # @TODO: Make exceptions handle differently depending on
                    # what they are
                    except:
                        time.sleep(_server_retry_rate)
                        continue
                    break
                s_km_count += 1

                # Get Recs and save to database
                recs = user.get_recommendations(limit=1000)
                logging.info('Got %d recs', len(recs))

                # Load database with new recs
                added_count = 0
                for doc in recs:
                    # add sector for later doing data analysis
                    doc['sector'] = (x[idx], y)

                    # Check if ID already in DB (prevent duplicates)
                    if not db_users.find_one({'id': str(doc['id'])}):
                        db_users.insert(doc)
                        added_count += 1

                logging.info('Added %d unique users to the db', added_count)

            y += r_l

        # This is ugly, do this properly with functional programming
        for idx in range(0, len(x)):
            x[idx] += len(x) * r_l

    logging.info('Completed area traversal.')
Esempio n. 6
0
  RETURN location.name', id=data['profile']['id'], date=data['location']['date'],
    location=newLocation, lat=newLocation['lat'], lon=newLocation['lon'])
    return result.single()[0]

def saveData(profile, location):
    print('Insert location for profile with id:', profile['id'])
    driver = GraphDatabase.driver(neo4jUrl, auth=(neo4jUser, neo4jPass))

    with driver.session() as session:
        session.write_transaction(updateProfile, profile)
        session.write_transaction(insertLocation, location)
        session.write_transaction(linkLocation, { 'profile': profile, 'location': location })
    return driver.close()


me = happn.User(token)
# Parse location area
move = 0.001 # 0,001 (~= 100m) move in 10s ~= 40km/h
if (area != None):
    splited = area.split(':')
    if (len(splited) != 2 and len(splited) != 3):
        print('Bad area description, must be <lat>:<lon>[:<distance in coord>]')
        exit(1)
    area = {
        'lat': float(splited[0]),
        'lon': float(splited[1]),
        'distance': (None if len(splited) == 2 or float(splited[2]) < move else float(splited[2]))
    }
    position = { 'lat': area['lat'], 'lon': area['lon'] }
    random.seed()
    me.set_device()
Esempio n. 7
0
def getTargetinfo(id):
    myUser = happn.User(token)
    # Target User Info
    return myUser.get_targetinfo(id)
Esempio n. 8
0
def likeUser(id):
    myUser = happn.User(token)
    # Like User
    myUser.like_user(id)
Esempio n. 9
0
def declineUser(id):
    myUser = happn.User(token)
    # Decline User
    myUser.decline_user(id)