Example #1
0
def check_activity_cards(user_id, friends=[], fofs=[], access_token=None):
    """
    For a first time user, will check that the cards have activities from their friends & fofs populated
    """
    user = User.get_by_id(user_id)
    if (not friends) and access_token:
        graph = facebook.GraphAPI(access_token)
        friends = graph.get_connections("me", "friends").get('data')
        #We check straight away that the friend & network cards are there
        friends = [friend['id'] for friend in friends]
        
    now = datetime.datetime.now()
    created_min = now - datetime.timedelta(hours=24)
    activities = col_get(ACTIVITY_, {'suggester_id' : {'$in' : friends + fofs}, 'created_on' : {'$gte' : created_min}})
    match = {'user_id' : user.get('_id')}
    cs = col_get(CARDSTORE, match, find='one')
    cards = cs.get('cards', []) if cs else []
    aids = []
    for card in cards:
        id_ = card.get('id', '')
        if id_.startswith('a'):
            aids.append(id_)
    new_acts = []
    for activity in activities:
        act_id = activity.get('_id')
        s_id = activity.get('suggester_id')
        vis = activity.get('visibility')
        expiry = activity.get('expiry')
        keen_ids = [keen.get('user_id') for keen in activity.get('keens')]
        if (act_id not in aids) and (expiry >= now) and (user_id not in keen_ids):
            if (s_id in friends) or (s_id in fofs and vis == 'fof') or (vis == 'n' and user.get('network')==activity.get('network')):
                new_acts.append(activity)
                aids.append(act_id)
    for act in new_acts:
        activity_timeline_dict = {
            "suggester_id" : act.get('suggester_id'),   
#            "created_on" : activity['created_on'],
            "keyword" : act['keyword'],
            "id" : 'a'+str(act['_id']), #This has to be string to consistency
            "activity_hash" : act["hash"],
            "confirmed" : False,
            "visibility" : act.get('visibility'),
            "keen" : False,
            "expiry" : activity['expiry']
        }
        Activity._push_activity_to_userid(user.get('_id'), activity_timeline_dict)
Example #2
0
def add_keener_notification(user_id, aid, keener_id):
    aid = str(aid)
    user = col_get(USER_, {"_id" : user_id}, find='one')
    watch_notifs = user.get('watch_notifs', {})
    if aid in watch_notifs.keys():
        watch_notifs[aid]['k'] = watch_notifs[aid]['k'] + 1
    else:
        watch_notifs[aid] = {'c' : 0, 'k' : 1}
    col_update(USER_, {'_id' : user_id}, {'$set' : {'watch_notifs' : watch_notifs}})
Example #3
0
def add_comment_nofification(user_ids, aid):
    aid = str(aid)
    for user_id in user_ids:
        user = col_get(USER_, {"_id" : user_id}, find='one')
        watch_notifs = user.get('watch_notifs', {})
        if aid in watch_notifs.keys():
            watch_notifs[aid]['c'] = watch_notifs[aid]['c'] + 1
        else:
            watch_notifs[aid] = {'c' : 1, 'k' : 0}
        col_update(USER_, {'_id' : user_id}, {'$set' : {'watch_notifs' : watch_notifs}})
Example #4
0
def update_contacts(user_id, p_contacts):
    logger.warning('update_contacts user_id:%s numbers:%s' % (user_id, str(p_contacts)))
    u_ph = col_get(USERPHONE, {"user_id" : user_id}, find='one')
    if u_ph:
        logger.warning('update_contacts user_id:%s removing existing user store' % (user_id))
        col_remove(USERPHONE, {"user_id" : user_id})
    
    new_u_ph = {'user_id' : user_id, 'contacts' : p_contacts}
    logger.warning('update_contacts user_id:%s adding user store' % (user_id))
    nid = col_insert(USERPHONE, new_u_ph)
    return True
Example #5
0
def invite_numbers(user_id, numbers, aid, send_sms = True):
    logger.warning('invite_numbers user_id:%s numbers:%s aid:%s' % (user_id, str(numbers), str(aid)))
    user = col_get(USER_, {"_id" : user_id}, find='one')
    himher = 'him' if user.get('gender') == 'male' else 'her'
    invitees = []
    sms_details = []
    if aid:
        activity = col_get(ACTIVITY_, {'_id' : ObjectId(aid)}, find='one')
    else:
        aid = ''
    for number in numbers:
        hash_ = get_b64_hash(number)
        link = 'http://keen.to/invite/%s' % hash_
        if aid:
            msg = '%s has invited you to join %s for #%s, follow the link %s' % (user.get('first_name').title(), himher, activity.get('keyword'), link)
        else:
            msg = "%s has invited you to Keen! Join %s at %s" % (user.get('first_name').title(), himher, link)
        invitees.append({'hashid' : hash_, 'number' : number, 'click_link' : False, 'signup' : False, 'aid' : aid})
        sms_details.append((number, msg))
    
    existing_invite = col_get(INVITES, {"inviter_id" : user_id}, find='one')
    if existing_invite:
        col_update(INVITES, {"inviter_id" : user_id}, {"$pushAll" : { "invitees" : invitees }})
        db_op = 'update: pushAll %s' % str(invitees)
    else:
        new_invite = {'inviter_id' : user_id, 'invitees' : invitees}
        inv_id = col_insert(INVITES, new_invite)
        db_op = 'insert: %s new_invite:%s' % (str(inv_id), new_invite)
    logger.warning('invite_numbers user_id:%s db_op:%s' % (user_id, db_op))
    #Do the sending last, just to make sure everythings in place for the click response to be tracked
    if send_sms:
        for number, msg in sms_details:
            try:
                result = send_sms(number, msg)
                logger.warning('invite_numbers user_id:%s send_sms number:%s msg:%s result:%s' % (user_id, str(number), str(msg), str(result)))
            except Exception, e:
                logger.warning('invite_numbers user_id:%s send_sms number:%s msg:%s EXCEPTION:%s' % (user_id, str(number), str(msg), str(e)))
Example #6
0
def add_competition_entry(user_id, value):
    logger.warning('add_competition_entry user_id:%s value:%s' % (str(user_id), str(value)))
    u = col_get(USER_, {"_id" : user_id}, find='one')
    now = datetime.datetime.now()
    entry = {
        'value' : value,
        'when'  : now         
    }
    if u.get('network') != settings.OTAGO:
        logger.warning('add_competition_entry user_id:%s entry:%s u.network:%s is no UoOtago' % (str(user_id), str(entry), u.get('network')))
        return
    comp = col_get(COMPETITION, {"user_id" : user_id}, {}, 'one')
    if comp:
        #Push to comp
        logger.warning('add_competition_entry user_id:%s comp exists pushing entry' % str(user_id))
        col_update(COMPETITION, {"user_id" : user_id}, {'$push' : {'entries' : entry}})
    else:
        new_comp = {
            'user_id' : user_id,
            'entries' : [entry]
        }
        logger.warning('add_competition_entry user_id:%s new_comp:%s' % (str(user_id), str(new_comp)))
        c_id = col_insert(COMPETITION, new_comp)
    notification_tasks.send_admin_notification(user_id, "Score! You've got another entry to #partylikeaboss", 'One more chance to #partylikeaboss')
Example #7
0
def reminder(aid):
    """
    Send a reminder to people 30mins before the activity if it was scheduled more than 3 hrs from the confirm time
    """
    logger.info('Starting reminder: %s' % str(aid))    
    activity = Activity.objects.get(id = aid)
    confirmed = [keen.user_id for keen in activity.keens if keen.user_id != activity.suggester_id and keen.confirmed]
    logger.info('reminder aid:%s sending to %s' % (aid, str(confirmed)))
    suggester = User.objects.get(_id = activity.suggester_id)
    store_data = {
        'uid'    : activity.suggester_id,
        'aid'    : activity.id,
    }
    android_ids = []
    apple_ids = []
    badge_nums = []
    
    """
    Heads up, #jam with laxman in 30mins
    """
    message = [
        "Heads up, #",
        activity.keyword,
        " with "
        "@" + suggester.first_name,
        " in 30 mins",
    ]
    confirmed_u = col_get(USER_, {"_id" : {"$in" : confirmed }}, list_=True)
    logger.info('reminder aid:%s got these users: %s' % (aid, str(confirmed_u)))   
    for person in confirmed_u:
        android_ids.append(person.get('device_gcm_token'))
        apple_ids.append(person.get('device_pns_token'))
        badge_num = add_notification(person['_id'], settings.NOTIF_REMINDER, message, '', store_data)
        badge_nums.append(badge_num)
    data =  {
        'title'     : suggester.name,
        'msg'   : ''.join(message),
        'ticker'    : "#" + activity.keyword + ' with ' + suggester.first_name + ' in 30 mins',
        'uid'       : suggester._id,
        'type'      : settings.NOTIF_REMINDER,
    }
    logger.info('reminder aid:%s data:%s android_ids:%s, apple_ids:%s' % (str(activity.id), str(data), str(android_ids), str(apple_ids)))
    if confirmed_u:
        send(data, android_ids, apple_ids, badge_nums)
Example #8
0
def daily_user_update_connections():
    app_access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
    graph = facebook.GraphAPI(app_access_token)
    #Get active users
    actives = User.objects.filter(type=User.ACTIVE)
    errors = 0
    
    for active in actives:
        try:
            _id = active._id
            friends = graph.get_connections(_id, "friends").get('data')
            logger.warning("daily_user_update_connections user_id:%s 2" % _id)
            social.ensure_exists(_id, active.network)
            logger.warning("daily_user_update_connections user_id:%s 3" % _id)
            new_friends = {f['id'] : f for f in friends}
            r = update_friends_async(_id, [friend['id'] for friend in friends])
            logger.warning("daily_user_update_connections user_id:%s 4" % _id)
            #Get the people who are on keen around me and figure out their mutual relations
            users = col_get(USER_, {'network' : active.network})
            logger.warning("daily_user_update_connections user_id:%s 5" % _id)
            user_ids = [u.get('_id') for u in users]
            #make sure the update_friends has finished

            dr = DummyRequest()
            dr.session = {}
            user = User.get_by_id(_id)  
            rms = social.get_relation_mutuals_cache_v2(dr, user, user_ids, force_reload=True, check_cache_only=False)
            logger.warning("daily_user_update_connections user_id:%s 6" % _id)

        #try to get friends then run check_friends alg
#        try:
#            friends = graph.get_connections(active._id, "friends").get('data')
##            print friends['data']
#            new_friends = {}
#            for friend in friends:
#                id_ = friend['id']
#                f = {'name' : friend.get('name', ''), 'id' : id_, 'city_id' : '', 'city_name' : ''}
#                new_friends[id_] = f
#            new_friend_ids = active.check_friends(new_friends)          
        except facebook.GraphAPIError:
            #Maybe the user has uninstalled us frorm fb
            errors += 1
    return "Completed daily user update connections for %s users, with %s facebook graph errors" % (str(len(actives)), str(errors))
Example #9
0
def no_confirms(aid):
    
    """
    Called to notify the activity keeners who havent been confirmed
    """
    #Currently we just send a notification to the active friends of the suggester
    logger.info('Starting no_confirms %s' % str(aid))    
    activity = Activity.objects.get(id = aid)
    not_confirmed = [keen.user_id for keen in activity.keens if keen.user_id != activity.suggester_id and not keen.confirmed]
    logger.info('no_confirms aid:%s sending to %s' % (aid, str(not_confirmed)))
    suggester = User.objects.get(_id = activity.suggester_id)
    store_data = {
        'uid'    : activity.suggester_id,
        'aid'    : activity.id,
    }
    android_ids = []
    apple_ids = []
    badge_nums = []
    message = [
        "Oh barnacles! ",
        "@" + suggester.name,
        " hasn't  confirmed you for #",
        activity.keyword,
    ]
    not_confirmed_u = col_get(USER_, {"_id" : {"$in" : not_confirmed }}, list_=True)
    logger.info('no_confirms aid:%s got these users: %s' % (aid, str(not_confirmed_u)))   
    for person in not_confirmed_u:
        android_ids.append(person.get('device_gcm_token'))
        apple_ids.append(person.get('device_pns_token'))
        badge_num = add_notification(person['_id'], settings.NOTIF_NOT_CONFIRMED, message, '', store_data)
        badge_nums.append(badge_num)
    data =  {
        'title'     : suggester.name,
        'msg'   : ''.join(message),
        'ticker'    : suggester.name + "hasn't confirmed you",
        'uid'       : suggester._id,
        'type'      : settings.NOTIF_NOT_CONFIRMED,
    }
    logger.info('no_confirms aid:%s data:%s android_ids:%s, apple_ids:%s' % (str(activity.id), str(data), str(android_ids), str(apple_ids)))
    if not_confirmed_u:
        send(data, android_ids, apple_ids, badge_nums)
Example #10
0
def schedule_master_activity(sid):
    logger.warning('schedule_master_activity sid:%s' % str(sid))
    s_act = col_get(SCHEDULEDACTIVITY_, {"_id" : ObjectId(sid)}, {}, 'one')
    if not s_act:
        logger.warning('Scheduled activity %s doesnt exist, exiting' % str(s_act))
        return
    logger.warning('schedule_master_activity  creating activity %s' % str(s_act))
    activity = Activity.create_activity(suggester=None, text=s_act.get('text'), expiry = s_act.get('expiry'), visibility='n', status=Activity.MASTER, confirm_msg = s_act.get('details'), where = s_act.get('where'), when = s_act.get('when'), network = s_act.get('network'))
    logger.warning('schedule_master_activity sid:%s aid:%s, removing scheduled act' % (str(sid), str(activity.get('_id'))))
    col_remove(SCHEDULEDACTIVITY_, {"_id" : ObjectId(sid)})
    logger.warning('schedule_master_activity sid:%s aid:%s pushing to: %s' % (str(sid), str(activity.get('_id')), s_act.get('network')))
    Activity.push_activity(activity['_id'])
    pull_default_hrs = get_eta(hours=settings.DEFAULT_USER_PULL_HOURS)
    pull_confirmed_hours = get_eta(hours=settings.CONFIRMED_USER_PULL_AFTER_WHEN_HOURS)
    logger.warning('schedule_master_activity sid:%s expire_activity_default:%s pull_default:%s pull_confirmed_activity_default:%s' % (str(sid), s_act.get('expiry').strftime('%Y-%m-%d %H:%M'), pull_default_hrs.strftime('%Y-%m-%d %H:%M'), pull_confirmed_hours.strftime('%Y-%m-%d %H:%M')))
    expire_activity_default.apply_async(args=[activity["_id"]], eta=s_act.get('expiry'))
    pull_default.apply_async(args=[activity["_id"]], eta=pull_default_hrs)
#    pull_confirmed_activity_default.apply_async(args=[activity["_id"]], eta=pull_confirmed_hours)
    
    #Then we kick off the normal notifications
    notification_tasks.new_activity(activity["_id"])
Example #11
0
def push_gc(uids):
    logger.info('push_gc uids:%s' % str(uids))
    users = col_get(USER_, {"_id" : {"$in" : uids }}, list_=True)
    android_ids = []
    apple_ids = []
    badge_nums = []
    for user in users:
        
        if user.get('device_gcm_token'):
            android_ids.append(user.get('device_gcm_token'))
#        if user.get('device_pns_token'):
#            apple_ids.append(user.get('device_pns_token'))
#            try:
#                ns = NotificationStore.objects.get(user_id = user.get('_id'))
#                badge_nums.append(ns.badge_num)
#            except:
#                badge_nums.append(0)
    
    data =  {
        'type'      : settings.NOTIF_UPDATE_GET_CONTENT,
    }
    
    send(data, android_ids, apple_ids, badge_nums)
Example #12
0
def update_user_connections(user_id, access_token):
    logger.warning('update_user_connections user_id:%s access_token:%s' % (user_id, access_token))
    graph = facebook.GraphAPI(access_token)
    try:
        user = User.get_by_id(user_id)
        friends = graph.get_connections("me", "friends").get('data')
        #We check straight away that the friend & network cards are there
        f_ids = [friend['id'] for friend in friends]
        check_friends.apply_async((user_id, friends), countdown=10)
#        if _id in settings.GOD_IDS:
        #Get neo up to date
        
        logger.warning("update_user_connections user_id:%s 2" % user_id)
        b=social.ensure_exists(user_id, user.get('network'))
        logger.warning("update_user_connections user_id:%s 3" % user_id)
        new_friends = {f['id'] : f for f in friends}
        r = update_friends_async(user_id, [friend['id'] for friend in friends])
        logger.warning("update_user_connections user_id:%s 4" % user_id)
        #Get the people who are on keen around me and figure out their mutual relations
        users = col_get(USER_, {'network' : user.get('network')})
        logger.warning("update_user_connections user_id:%s 5" % user_id)
        user_ids = [u.get('_id') for u in users]
        #make sure the update_friends has finished
        dr = DummyRequest()
        dr.session = {}
        rms = social.get_relation_mutuals_cache_v2(dr, user, user_ids, force_reload=True, check_cache_only=False)
        logger.warning("update_user_connections user_id:%s 6" % user_id)
#        set_friends_cache(request, new_friends)
        logger.warning("update_user_connections user_id:%s 7" % user_id)
#        request.session['fb_friends'] = new_friends
        return {'result' : True, 'data' : rms}
    except facebook.GraphAPIError, e:
        logger.warning("update_user_connections _id:%s ERROR:facebook:%s" % (user_id, str(e)))
        response_data = {
            'result' : False,
            'data'   : 'Facebook friend request failed'
        }
Example #13
0
def new_activity(aid):
    try:
        activity = Activity.objects.get(id = aid)
        if activity.is_cancelled():
            return
    except Activity.DoesNotExist:
        return
    
    not_master = activity.status != Activity.MASTER
    
    interests_to_notify = activity.interest_notified
    follower_ids_to_notify = activity.followers_notified
    add_activity_notification(follower_ids_to_notify, aid)
    logger.info('new_activity aid:%s status:%s interests_to_notify:%s' % (str(activity.id), activity.status, str(interests_to_notify)))
    logger.info('new_activity aid:%s status:%s followers_to_notify:%s' % (str(activity.id), activity.status, str(follower_ids_to_notify)))
    
    if not_master:
        suggester = User.objects.get(_id = activity.suggester_id)
        logger.info('new_activity aid:%s suggester:%s' % (str(activity.id), str(suggester)))
#        suggester_friend_store = suggester.get_friend_store()
#        following_ids = suggester.following_me
#        friend_ids = suggester_friend_store.get_friend_ids()
#        fof_ids = FriendOfFriendStore.get_fof_ids_raw(suggester._id) if activity.visibility == 'fof' else []
#        interests_to_notify = col_get(USER_, {"_id" : {"$in" : fof_ids + friend_ids }, "interest" : activity.keyword, "network" : suggester.network}, list_=True)
#        followers_to_notify = col_get(USER_, {"_id" : {"$in" : following_ids }, "network" : suggester.network}, list_=True)
        pic_url = get_fb_profile_pic_link(suggester._id)
#        logger.info('new_activity aid:%s %s interests to notify from friends:%s fofs:%s' % (str(activity.id), str(len(interests_to_notify)), str(friend_ids), str(fof_ids)))
#        logger.info('new_activity aid:%s followers:%s' % (str(activity.id), str(followers_to_notify)))
        message = [
            '@' + suggester.name,
            ' is keen to #',
            activity.keyword,
            '. Join ',
            '@' + suggester.name
        ]
        
    else:
#        logger.info('new_activity aid:%s status==master' % str(activity.id))
#        interests_to_notify = []
#        followers_to_notify = col_get(USER_, {"interest" : activity.keyword}, list_=True)
#        logger.info('new_activity aid:%s followers:%s' % (str(activity.id), str(followers_to_notify)))
        message = [
            'Join #',
            activity.keyword,
            ' : "',
            activity.text,
            '"'
        ]
        pic_url = ''
    interests_to_notify = col_get(USER_, {"_id" : {"$in" : interests_to_notify }}, list_=True)
    followers_to_notify = col_get(USER_, {"_id" : {"$in" : follower_ids_to_notify }}, list_=True)
    
    store_data = {
        'uid'    : suggester._id if not_master else '',
        'aid'    : activity.id,
        'pic'    : pic_url 
    }
    logger.info('new_activity aid:%s status:%s message:%s' % (str(activity.id), activity.status, str(message)))
    android_ids = []
    apple_ids = []
    badge_nums = []
 
    for follower in followers_to_notify:
        android_ids.append(follower.get('device_gcm_token'))
        apple_ids.append(follower.get('device_pns_token'))
        badge_num = add_notification(follower['_id'], settings.NOTIF_ACTIVITY_NEW, message, pic_url, store_data)
        badge_nums.append(badge_num)
        Activity.add_to_set(activity.id, 'followers_notified', follower['_id'])
    data =  {
        'title'     : suggester.name if not_master else 'Join #' + activity.keyword,
        'msg'       : activity.text,
        'aid'       : activity.id,
        'ticker'    : 'New activity',
        'uid'       : suggester._id if not_master else '',
#        'type'      : settings.NOTIF_FOLLOWING_POST,
        'type'      : settings.NOTIF_ACTIVITY_NEW,
    }
    i_data = {
        'msg'  : suggester.name + ' posted: "' + activity.text + '"' if not_master else 'Join #' + activity.keyword,
        'aid'  : activity.id,
        'uid'  : suggester._id,
        'type' : settings.NOTIF_ACTIVITY_NEW,
    }
    follower_androids = set(android_ids)
    follower_apples = set(apple_ids)
    logger.info('new_activity aid:%s sending to followers data:%s, android_ids:%s, apple_ids:%s' % (str(activity.id), str(data), str(android_ids), str(apple_ids)))
    send(data, android_ids, apple_ids, badge_nums, i_data=i_data)
    
#    android_ids = set()
#    apple_ids = set()
#    badge_nums = []
#    
#    if not_master:
#        message = [
#            '@' + suggester.name,
#            ' posted a snip with #',
#            activity.keyword,
#            '. Join ',
#            '@' + suggester.name
#        ]
#    
#    for interested in interests_to_notify:
#        android_ids.add(interested.get('device_gcm_token'))
#        apple_ids.add(interested.get('device_pns_token'))
#        badge_num = add_notification(interested['_id'], settings.NOTIF_INTEREST_POST, message, pic_url, store_data)
#        badge_nums.append(badge_num)
#        Activity.add_to_set(activity.id, 'interest_notified', interested['_id'])
#    android_ids = list(android_ids - follower_androids)
#    apple_ids = list(apple_ids - follower_apples)
#    
#    data =  {
#        'title'     : '#' + activity.keyword + ' posted by ' + suggester.name if not_master else 'Join #' + activity.keyword,
#        'msg'   : activity.text,
#        'ticker'    : 'New activity',
#        'aid'       : activity.id,
#        'uid'       : suggester._id if not_master else '',
#        'type'      : settings.NOTIF_INTEREST_POST,
#    }
#    logger.info('new_activity aid:%s data:%s android_ids:%s apple_ids:%s' % (str(activity.id), str(data), str(android_ids), str(apple_ids)))
#    send(data, android_ids, apple_ids, badge_nums)
    logger.info('new_activity aid:%s finished' % str(activity.id))