コード例 #1
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def home(request):
    parameters = {}
    user_profile_obj = UserProfile()
    userprofile = user_profile_obj.get_profile_by_id(request.user.id)
    parameters['userprofile'] = UserProfile
    parameters['user'] = request.user
    parameters['total_food_count'] = 2
    parameters['food'] = [{
        'name': 'Cauliflowers',
        'tagcount': 7
    }, {
        'name': 'Mutton',
        'tagcount': 5
    }]
    parameters['total_business_count'] = 2
    parameters['business'] = [{
        'name': 'FoodSupply Pvt. Ltd.',
        'tagcount': 7
    }, {
        'name': 'Nina and Hager Meat Industry',
        'tagcount': 5
    }]
    parameters['total_organization_count'] = 2
    parameters['organization'] = [{
        'name': 'Onion Export',
        'tagcount': 7
    }, {
        'name': 'Bajeko Sekuwa',
        'tagcount': 5
    }]
    return render_to_response('index.html', parameters)
コード例 #2
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def trends(request):
    parameters = {}
    t_feed_obj = TweetFeed()

    if request.method == 'GET':
        start_time = datetime.date.today() - datetime.timedelta(7)
        end_time = datetime.date.today()

    else:
        if request.POST['start_time'] != '':
            start_time = datetime.datetime.strptime(request.POST['start_time'],
                                                    '%Y-%m-%d')
        else:
            start_time = datetime.date.today() - datetime.timedelta(7)
        if request.POST['end_time'] != '':
            end_time = datetime.datetime.strptime(request.POST['end_time'],
                                                  '%Y-%m-%d')
        else:
            end_time = datetime.date.today()

    start_time = time.mktime(start_time.timetuple())
    end_time = time.mktime(end_time.timetuple())
    results = t_feed_obj.get_trending_hashtags(start_time, end_time)
    new_results = []
    for sub in results:
        sub['value'] = int(sub['value'])
        new_results.append(sub)

    parameters['results'] = new_results[0:20]
    parameters.update(csrf(request))

    if request.user.is_authenticated():
        user_id = request.user.id
        user_profile_obj = UserProfile()
        user_profile = user_profile_obj.get_profile_by_id(str(user_id))
        user_info = UserInfo(user_id)
        parameters['userinfo'] = user_info
        parameters['user_id'] = request.user.id

        user_profile_obj = UserProfile()
        userprofile = user_profile_obj.get_profile_by_id(request.user.id)
        parameters['userprofile'] = UserProfile

    return render_to_response('trends.html',
                              parameters,
                              context_instance=RequestContext(request))
コード例 #3
0
def tweets(request):
    parameters = {}
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')
    parameters['user'] = request.user
    user_id = request.user.id
    # print user_id
    st = SocialToken.objects.get(account__user__id=user_id)
    access_token = st.token
    access_token_secret = st.token_secret
    twitter = Twython(
        app_key = consumer_key,
        app_secret = consumer_secret,
        oauth_token = access_token,
        oauth_token_secret = access_token_secret
    )
    # uid = SocialAccount.objects.get(user__id=user_id).uid
    admin_twitter = Twython(
        app_key = consumer_key,
        app_secret = consumer_secret,
        oauth_token = admin_access_token,
        oauth_token_secret = admin_access_token_secret
        )
    max_id = MaxTweetId.objects.all()[0]
    max_tweet_id = int(max_id.max_tweet_id)
    # print type(max_tweet_id), max_tweet_id
    mentions = admin_twitter.get_mentions_timeline(count = 200, contributer_details = True, since_id = max_tweet_id)
    # print len(mentions)
    tweet_list = []
    tweet_feed = TweetFeed()
    for tweet in mentions:
        try:
            usr = SocialAccount.objects.get(uid = tweet['user']['id'])
            pic_url_list = []
            if tweet['entities'].get('media')!= None:
                for each in tweet['entities'].get('media'):
                    pic_url_list.append(each['media_url'])
            data = {'tweet_id': tweet['id'],
                    'parent_tweet_id': 0 if tweet['in_reply_to_status_id'] == None else tweet['in_reply_to_status_id'],
                    'tweet_message': tweet['text'],
                    'picture': pic_url_list
            }
            tweet_list.append(tweet['id'])
            tweet_feed.insert_tweet(data)
        except:
            text = "@" + tweet['user']['screen_name'] + " Thanks! Please confirm your post by clicking this link [link]. You'll only have to do this once."
            try:
                admin_twitter.update_status(status = text)
            except:
                pass
    max_id.max_tweet_id = max(tweet_list)
    max_id.save()

    parameters['tweet_list'] = mentions
    user_profile_obj = UserProfile()
    userprofile = user_profile_obj.get_profile_by_id(user_id)
    parameters['userprofile'] = UserProfile
    return render_to_response('home.html', parameters)
コード例 #4
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def unclaimed_profiles(request):
    parameters = {}
    tags = Tags()
    parameters['all_tags'] = tags.get_tags()
    if request.user.is_authenticated():
        user_id = request.user.id
        user_info = UserInfo(user_id)
        user_profile_obj = UserProfile()
        userprofile = user_profile_obj.get_profile_by_id(user_id)
        parameters['userprofile'] = UserProfile
        parameters['userinfo'] = user_info
    else:
        return HttpResponseRedirect('/')

    if request.method == 'GET':
        if request.GET.get('page') == None:
            page_num = 1
            edit_value = 0
        else:
            page_num = int(request.GET['page'])
            edit_value = int(request.GET['edit'])
        if page_num <= 0:
            page_num = 1

        user_profile_obj = UserProfile()
        unclaimed_profiles = user_profile_obj.get_unclaimed_profile_paginated(
            page_num, edit_value)
        parameters['unclaimed_profiles'] = unclaimed_profiles
        parameters['edit_value'] = edit_value
        parameters[
            'unedited_count'] = user_profile_obj.get_unclaimed_unedited_profile_count(
            )
        parameters[
            'edited_count'] = user_profile_obj.get_unclaimed_edited_profile_count(
            )

        parameters['unclaimed_profiles_json'] = json.dumps(unclaimed_profiles)
        parameters['page_number'] = page_num

    return render_to_response('unclaimed.html',
                              parameters,
                              context_instance=RequestContext(request))
コード例 #5
0
def food_tags(request):
    parameters = {}
    fix_new_foods()
    if request.user.is_authenticated():
        # parameters['user'] = request.user
        user_id = request.user.id
       
        user_info = UserInfo(user_id)

        user_profile_obj = UserProfile()
        userprofile = user_profile_obj.get_profile_by_id(user_id)
        parameters['userprofile'] = UserProfile

        parameters['userinfo'] = user_info
        newfoo = UnapprovedFood()
        new_foods = newfoo.get_all_new_foods()
        parameters['unapproved_foods'] = new_foods

        # aggregate pipeline to display all tags of all foods
        results = food_pipeline()
        processed_results = []

        approved_tags = ApprovedFoodTags()
        all_approved = approved_tags.get_all_approved_foods()

        for each in results:
            mytags = {}
            for e in each['results']:
                t_list = e['food_tags'].split(',')
                app_tags = approved_tags.get_food_by_name(each['uid'])
                app_tags = app_tags['tags'].split(',') if app_tags!=None else []
                # app_tags = e.get('approved_food_tags').split(',') if e.get('approved_food_tags')!=None else False
                # if app_tags!=None:
                #     if Counter(t_list)==Counter(app_tags):
                #         continue
                for eachtts in t_list:
                    if app_tags!=None:
                        if eachtts not in app_tags:
                            if eachtts not in mytags.keys():
                                mytags[eachtts] = 'unapproved'
                        else:
                            mytags[eachtts] ='approved'
                    else:
                        if eachtts not in mytags.keys():
                            mytags[eachtts] = 'unapproved'

            processed_results.append({'food_name': each['uid'], 'results': mytags}) if mytags!={} else False
        parameters['tags_and_foods'] = processed_results

    foods = AdminFoods()
    tags = foods.get_tags()
    parameters['tags'] = json.dumps(tags)

    return render_to_response('food-tags.html', parameters, context_instance=RequestContext(request))
コード例 #6
0
ファイル: kpi.py プロジェクト: eddowding/foodtrade
def stats(request):
    parameters = {}
    user_prof = UserProfile()
    stats = KPIStats()
    parameters['user_count'] = stats.user_count()
    parameters['total_connections'] = stats.total_connections()
    parameters['connections_per_business'] = stats.avg_conn_per_business()
    parameters['total_activity'] = stats.activity_count()
    parameters['total_replies'] = stats.replies_count()
    kpi_obj = KPI()
    kpi_obj.create_kpi(parameters)
    return render_to_response('kpi.html',
                              parameters,
                              context_instance=RequestContext(request))
コード例 #7
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def transport_mailchimp(request, username):
    if request.user.is_authenticated():
        user_profile_obj = UserProfile()

        user = user_profile_obj.get_profile_by_username(str(username))
        # try:
        if user['email'] == '':
            return HttpResponse(json.dumps({'email': 'empty'}))
        m = MailChimpClass()
        m.subscribe(user)
        # except:
        #     pass
        #     mail_excep_obj = MailChimpException()
        #     mail_excep_obj.save_mailchimp_exception(user)
        return HttpResponse(json.dumps({'message': 'registered successfully'}))
コード例 #8
0
ファイル: forms.py プロジェクト: eddowding/foodtrade
    def __init__(self, *args, **kwargs):
        # self.request = request
        self.request = kwargs.pop('request', None)
        super(SignupForm, self).__init__(*args, **kwargs)
        try:
            username = self.sociallogin.account.extra_data['screen_name']
            user_prof_obj = UserProfile()
            user = user_prof_obj.get_profile_by_username(str(username))
            self.fields['email'].widget.attrs['value'] = user['email']
            self.fields['address'].widget.attrs['value'] = user['address']

        except:
            pass
        # self.fields['username'].widget.attrs['readonly'] = True
        self.fields['email'].widget.attrs['class'] = 'form-control'
コード例 #9
0
def admin_tags(request):
    parameters = {}
    if request.user.is_authenticated():
        user_id = request.user.id
        user_info = UserInfo(user_id)
        user_profile_obj = UserProfile()
        userprofile = user_profile_obj.get_profile_by_id(user_id)
        parameters['userprofile'] = UserProfile
        parameters['userinfo'] = user_info
        
    mytag = Tags()
    tags = mytag.get_tags()
    parameters['tags'] = json.dumps(tags)

    return render_to_response('admin_tags.html', parameters, context_instance=RequestContext(request))
コード例 #10
0
ファイル: merge_data.py プロジェクト: eddowding/foodtrade
def update_image(request):
    img_url = request.POST.get('img')
    img_url = img_url.replace("bigger", "normal")
    img_url = img_url.replace("/web_retina", "")
    up = UserProfile()
    try:
        user_details = up.get_profile_by_profile_img(img_url)
        bot_twitter = get_twitter_obj(settings.BOT_ACCESS_TOKEN,
                                      settings.BOT_ACCESS_TOKEN_SECRET)
        details = bot_twitter.show_user(screen_name=user_details['username'])
        image_desc = {'profile_img': details['profile_image_url']}
        up.update_profile_fields({"useruid": user_details['useruid']},
                                 image_desc)
        return HttpResponse(
            json.dumps({
                "status": "ok",
                "src": details['profile_image_url']
            }))

    except:
        try:
            user_details = up.get_profile_by_profile_banner_url(img_url)
            bot_twitter = get_twitter_obj(settings.BOT_ACCESS_TOKEN,
                                          settings.BOT_ACCESS_TOKEN_SECRET)
            details = bot_twitter.show_user(
                screen_name=user_details['username'])
            image_desc = {
                'profile_banner_url':
                details.get("profile_background_image_url_https", "")
            }

            up.update_profile_fields({"useruid": user_details['useruid']},
                                     image_desc)
            return HttpResponse(
                json.dumps({
                    "status":
                    "ok",
                    "src":
                    details.get("profile_background_image_url_https", "")
                }))
        except:
            pass

    return HttpResponse(
        json.dumps({
            "status": "error",
            "message": "No image was found"
        }))
コード例 #11
0
def home(request):
    parameters = {}
    parameters.update(csrf(request))
    from mainapp.classes.TweetFeed import UserProfile, KPI
    from mainapp.classes.KpiClass import KPIStats
    user_prof = UserProfile()
    stats = KPIStats()
    parameters['user_count'] = stats.user_count()
    parameters['total_connections'] = stats.total_connections()
    parameters['connections_per_business'] = stats.avg_conn_per_business()
    parameters['total_activity'] = stats.activity_count()
    parameters['total_replies'] = stats.replies_count() 
   
    
    if request.user.is_authenticated():
        return HttpResponseRedirect('/activity/')
    return render_to_response('front.html',parameters,context_instance=RequestContext(request))
コード例 #12
0
def all_users(request):
    parameters = {}
    all_users = User.objects.all().order_by('-date_joined')
    final_list = []
    user_prof = UserProfile()
    for each in all_users:
        try:
            usr_pro = user_prof.get_profile_by_username(str(each.username))
            final_list.append({
                'date_joined': each.date_joined,
                'username': each.username,
                'sign_up_as': usr_pro['sign_up_as']
                })
        except:
            continue
    parameters['all_users'] = final_list
    return render_to_response('all_users.html', parameters, context_instance=RequestContext(request))
    # return render_to_response('all_users.html', parameters)
コード例 #13
0
    def process_response(self, request, response):
        # Avoid unnecessary work
        try:
            if request.user.is_authenticated() and "/accounts/twitter/login/callback/" in request.path:
                social_account = SocialAccount.objects.get(user__id = request.user.id)
                extra_data = social_account.extra_data
                image_desc = {'profile_img': extra_data['profile_image_url']}
                up = UserProfile()                
                up.update_profile_fields({"useruid":request.user.id}, image_desc)
        except:
            pass


        if response.has_header('Access-Control-Allow-Origin'):
            return response
 
        response['Access-Control-Allow-Origin']  = XS_SHARING_ALLOWED_ORIGINS 
        response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
        return response
コード例 #14
0
def search_result(
        request):  #TODO: change result div name, change hard coded url.
    query = request.GET.get('query')
    profile_type_filter = request.GET.get('profile_type_filter')
    lat = float(request.GET.get('lat')) if request.GET.get('lat') else None
    lng = float(request.GET.get('lng')) if request.GET.get('lng') else None
    distance = request.GET.get('distance')
    if request.user.is_authenticated():
        user_profile_obj = UserProfile()
        user_profile = user_profile_obj.get_profile_by_id(str(request.user.id))
        if user_profile.get('latlng') and user_profile.get('latlng').get(
                'coordinates'):
            lat = user_profile.get('latlng').get('coordinates')[1]
            lng = user_profile.get('latlng').get('coordinates')[0]
            distance = '500km'
    sqs = S().indexes(
        settings.ES_INDEX).query(_all__fuzzy=query).facet('sign_up_as')
    if lat and lng:
        sqs = sqs.filter(latlng__distance=(distance, lat, lng))
    if profile_type_filter:
        sqs = sqs.filter(sign_up_as=profile_type_filter)
    sqs = sqs[:50]
    html = render_to_string('_partials/search_result.html', {'sqs': sqs},
                            context_instance=RequestContext(request))
    objs = list(
        sqs.values_dict('id', 'name', 'profile_img', 'description', 'latlng',
                        'username'))
    facets = {}  #TODO: check why this iteration is required
    for k, v in sqs.facet_counts().items():
        facets[k] = {'total': v['total'], 'terms': v['terms']}
    return HttpResponse(
        json.dumps({
            'html': html,
            'objs': objs,
            'facets': facets
        }))
コード例 #15
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def invite(request):
    if request.GET.get('page') == None:
        page_num = 1
    else:
        page_num = int(request.GET.get('page'))

    parameters = {}
    parameters['current_page_number'] = page_num

    tweetfeed_obj = TweetFeed()
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    if request.user.is_authenticated():
        user_id = request.user.id
        user_profile_obj = UserProfile()
        user_profile = user_profile_obj.get_profile_by_id(str(user_id))
        user_info = UserInfo(user_id)
        parameters['userinfo'] = user_info
        parameters['user_id'] = request.user.id

    if request.method == 'GET':
        friends_obj = Friends()
        friends_count = friends_obj.get_friends(request.user.username)
        if len(friends_count) > 0:
            twitter_err_obj = TwitterError()
            twitter_error = twitter_err_obj.get_error(request.user.username)
            twitter_err_obj.change_error_status(request.user.username)
            # print twitter_error
            if len(twitter_error) > 0:
                # print "Inside use case 1"
                try:
                    next_cursor = twitter_error[0]['next_cursor_str']
                    # print next_cursor
                    friends = tweetfeed_obj.get_friends(
                        request.user.id, next_cursor)
                    count = 0
                    while (next_cursor != '0'):
                        # print "Inside use case 1 while loop"
                        next_cursor = friends['next_cursor_str']
                        friends_obj = Friends()
                        count = count + 1
                        for eachFriend in friends['users']:
                            friends_obj.save_friends({
                                'username': request.user.username,
                                'friends': eachFriend
                            })
                        if next_cursor != 0:
                            friends = tweetfeed_obj.get_friends(
                                request.user.id, next_cursor)
                except:
                    # print "Inside use case 1 exception"
                    twitter_err_obj.save_error({
                        'username': request.user.username,
                        'next_cursor_str': next_cursor,
                        'error_solve_stat': 'false'
                    })
                # print "Inside use case 1 get values"
                friends = friends_obj.get_paginated_friends(
                    request.user.username, page_num)
                friend_count = friends_obj.get_friends_count(
                    request.user.username)
            else:
                # print "Inside use case 1 else"
                friends = friends_obj.get_paginated_friends(
                    request.user.username, page_num)
                friend_count = friends_obj.get_friends_count(
                    request.user.username)
        else:
            # print "Inside use case 2"
            next_cursor = -1
            friends = tweetfeed_obj.get_friends(request.user.id, next_cursor)
            count = 0
            try:
                while (next_cursor != 0):
                    # print "Inside use case 1 while loop"
                    next_cursor = friends['next_cursor_str']
                    friends_obj = Friends()
                    count = count + 1
                    for eachFriend in friends['users']:
                        friends_obj.save_friends({
                            'username': request.user.username,
                            'friends': eachFriend
                        })
                    if next_cursor != 0:
                        friends = tweetfeed_obj.get_friends(
                            request.user.id, next_cursor)
            except:
                # print "Inside use case 2 exception"
                twitter_err_obj = TwitterError()
                twitter_err_obj.save_error({
                    'username': request.user.username,
                    'next_cursor_str': next_cursor,
                    'error_solve_stat': 'false'
                })
            #print "Inside use case 2 get friends"
            friends = friends_obj.get_paginated_friends(
                request.user.username, page_num)
            friend_count = friends_obj.get_friends_count(request.user.username)
    friend_list = []

    for eachFriend in friends:
        invites_obj = Invites()
        my_name = request.user.username
        if invites_obj.check_invited(eachFriend['friends']['screen_name'],
                                     my_name) == False:
            friend_list.append({
                'friends': {
                    'screen_name': eachFriend['friends']['screen_name'],
                    'name': eachFriend['friends']['name'],
                    'profile_image_url':
                    eachFriend['friends']['profile_image_url']
                }
            })

    page_count = int(friend_count / 15) + 1
    while (len(friend_list) == 0 and page_num <= page_count):
        page_num = page_num + 1
        friends = friends_obj.get_paginated_friends(request.user.username,
                                                    page_num)
        for eachFriend in friends:
            invites_obj = Invites()
            my_name = request.user.username
            if invites_obj.check_invited(eachFriend['friends']['screen_name'],
                                         my_name) == False:
                friend_list.append({
                    'friends': {
                        'screen_name':
                        eachFriend['friends']['screen_name'],
                        'name':
                        eachFriend['friends']['name'],
                        'profile_image_url':
                        eachFriend['friends']['profile_image_url']
                    }
                })

    parameters['friend'] = friend_list
    parameters['page_count'] = page_count
    parameters['friend_count'] = len(friend_list)

    user_profile_obj = UserProfile()
    userprofile = user_profile_obj.get_profile_by_id(request.user.id)
    parameters['userprofile'] = userprofile

    invites_obj = InviteId()
    invite_id = invites_obj.get_unused_id(request.user.id)

    invite_tweet = construct_invite_tweet(request, invite_id)
    parameters['invite_id'] = invite_id['uid']['id']
    parameters['invite_tweet'] = invite_tweet
    return render_to_response('invites.html',
                              parameters,
                              context_instance=RequestContext(request))
コード例 #16
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def notifications(request):
    parameters = {}

    if request.user.is_authenticated():
        user_id = request.user.id
        user_profile_obj = UserProfile()
        user_profile = user_profile_obj.get_profile_by_id(str(user_id))
        user_info = UserInfo(user_id)
        parameters['userinfo'] = user_info
        parameters['user_id'] = request.user.id

        user_profile_obj = UserProfile()
        userprofile = user_profile_obj.get_profile_by_id(request.user.id)
        parameters['userprofile'] = userprofile
    else:
        return HttpResponseRedirect('/')

    user_name = request.user.username
    user_email = request.user.email

    notices = Notification()
    my_notifications = notices.get_notification(user_name,
                                                page_number=1,
                                                n_type='all')
    parameters['archived_notification_count'] = my_notifications[
        'archived_notification_count']
    parameters['all_notification_count'] = my_notifications[
        'all_notification_count']
    parameters['unread_notification_count'] = my_notifications[
        'unread_notification_count']
    parameters['email'] = user_email
    parameters['screen_name'] = SocialAccount.objects.get(
        user__id=user_id).extra_data['screen_name']

    myNotice = []
    for eachNotification in my_notifications['notifications']:
        if eachNotification['notification_archived_status'] == 'true':
            continue
        processed_notice = {}
        user_profile_obj = UserProfile()
        notifying_user_profile = user_profile_obj.get_profile_by_username(
            eachNotification['notifying_user'])
        try:
            if (notifying_user_profile['email'] != ''):
                processed_notice[
                    'notifying_user_email'] = notifying_user_profile['email']
        except:
            user = User.objects.get(
                username=eachNotification['notifying_user'])
            # print eachNotification
            processed_notice['notifying_user_email'] = user.email
        try:
            if (notifying_user_profile['screen_name'] != ''):
                processed_notice[
                    'notifying_user_screenname'] = notifying_user_profile[
                        'screen_name']
        except:
            processed_notice[
                'notifying_user_screenname'] = account = SocialAccount.objects.get(
                    user__id=request.user.id).extra_data['screen_name']
        processed_notice['notification_id'] = eachNotification['uid']['id']
        processed_notice['notifying_user'] = eachNotification['notifying_user']
        processed_notice['notification_message'] = eachNotification[
            'notification_message'][0:50] + '....'
        processed_notice['notification_message_full'] = eachNotification[
            'notification_message']
        processed_notice['time_elapsed'] = calculate_time_ago(
            eachNotification['notification_time'])
        processed_notice['notifying_user_profile'] = notifying_user_profile
        processed_notice['notification_view_status'] = eachNotification[
            'notification_view_status']
        myNotice.append(processed_notice)
    parameters['notifications'] = myNotice
    return render_to_response('notice.html',
                              parameters,
                              context_instance=RequestContext(request))
コード例 #17
0
ファイル: DataConnector.py プロジェクト: eddowding/foodtrade
    def __init__(self, user_id):
        self.user_id = user_id
        try:
            usr = User.objects.get(id=user_id)
            self.is_superuser = usr.is_superuser
        except:
            self.is_superuser = False

        user_profile = UserProfile()
        userprof = user_profile.get_profile_by_id(user_id)
        self.email = userprof['email']
        self.twitter_user = userprof['screen_name']
        self.lon = userprof['latlng']['coordinates'][0]
        self.lat = userprof['latlng']['coordinates'][1]

        # print self.lon
        # print self.lat
        self.user_type = userprof['sign_up_as']
        self.zip_code = userprof.get('zip_code')
        self.address = userprof['address']
        self.type = userprof['type_user']

        self.post_count = user_profile.get_post_count(user_id)

        try:
            self.country = userprof['address'].split(',')[
                len(userprof['address'].split(',')) - 1]
        except:
            self.country = ''
        try:
            self.facebook_page = userprof['facebook_page']
        except:
            self.facebook_page = ''

        try:
            self.webiste_url = userprof['webiste_url']
        except:
            self.webiste_url = ''
        try:
            self.company_num = userprof['company_num']
        except:
            self.facebook_page = ''
        try:
            self.deliverables = userprof['deliverables']
        except:
            self.deliverables = ''
        try:
            self.business_org_name = userprof['business_org_name']
        except:
            self.business_org_name = ''

        self.email_registration = 0
        try:
            self.email_registration = userprof['email_registration']
        except:
            pass

        user_connection = UserConnections(user_id)
        if userprof.get('business_org_name') != None:
            self.full_name= userprof.get('business_org_name') if (userprof['sign_up_as'] == 'Business' or userprof['sign_up_as'] == 'Organisation') \
            and userprof.get('business_org_name')!='' else userprof['name']
        else:
            self.full_name = userprof['name']
        # parameters['name'] = userprof['name']
        # self.full_name = userprof.get('business_org_name') if (userprof['sign_up_as'] == 'Business' or userprof['sign_up_as'] == 'Organisation') \
        # and  userprof.get('business_org_name')!='' else userprof['name']

        self.username = userprof['username']
        self.description = userprof['description']
        self.profileimg = userprof['profile_img']
        b_conn_len, c_conn_len = user_connection.get_trade_connection_no()
        self.trade_connections_no = b_conn_len + c_conn_len
        self.b_conn_no = b_conn_len
        self.c_conn_no = c_conn_len
        self.food_no = user_connection.get_food_connection_no()
        self.nearby_businesses_no = user_connection.get_nearby_businesses_no(
            self.lon, self.lat)
        self.nearby_individuals_no = user_connection.get_nearby_individuals_no(
            self.lon, self.lat)
        self.organisation_connection_no = user_connection.get_organisation_connection_no(
        )
        self.award_no = user_connection.get_award_no()
        '''Trends'''
        trends_this_week = TrendsThisWeek(host='localhost',
                                          port=27017,
                                          db_name='foodtrade',
                                          username='******',
                                          password='******')
        trends_all_time = TrendsAllTime(host='localhost',
                                        port=27017,
                                        db_name='foodtrade',
                                        username='******',
                                        password='******')
        self.hashtagsthis = trends_this_week.get_trends_this_week()
        self.hashtagsall = trends_all_time.get_trends_all_time()

        notification_obj = Notification()
        self.notification_count = notification_obj.get_notification_count(
            self.username)

        self.subscribed = True
        try:
            usr = User.objects.get(id=user_id)
            customer, created = Customer.get_or_create(usr)
            if created:
                self.subscribed = False

            if not customer.has_active_subscription():
                self.subscribed = False
        except:
            self.subscribed = False
コード例 #18
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def sms_receiver(request):
    body = request.GET.get('Body', "")
    cell_no = request.GET.get('From', '')
    msg_from = cell_no.replace('+', "")

    user_profile = UserProfile()
    http_response = ""
    try:
        usr = user_profile.get_profile_by_username(msg_from)
        username = usr['username']

        h = HTMLParser.HTMLParser()

        tweet_id = str(uuid.uuid4())
        parent_tweet_id = 0
        tweet_feed = TweetFeed()
        data = {
            'tweet_id': str(tweet_id),
            'parent_tweet_id': str(parent_tweet_id),
            'status': h.unescape(body),
            'picture': [],
        }
        tweet_feed.insert_tweet_by_username(msg_from, data)
        http_response = http_response + "appended new tweet"
    except:
        str_text = body

        if "#join" in str_text:
            str_text = str_text.lower()
            str_text = str_text.strip()
            str_text = str_text.strip()
            str_text = str_text.replace("#join", "")
            str_text = str_text.strip()
            import re

            regex = re.compile(
                ("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
                 "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
                 "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))

            user_emails = re.findall(regex, str_text)

            if len(user_emails) > 0:
                user_email = user_emails[0][0]
                str_text = str_text.replace(user_email, "")
                location = str_text.strip()

                signup_data = {}
                try:
                    location_res = Geocoder.geocode(location)
                    latlng = {
                        "type":
                        "Point",
                        "coordinates": [
                            float(location_res.longitude),
                            float(location_res.latitude)
                        ]
                    }
                    user_address = location
                    postal_code = location_res.postal_code
                except:
                    try:
                        location_res = Geocoder.geocode(
                            data['user']['location'])
                        lat, lon, addr, postal_code = location_res.latitude, location_res.longitude, location_res.postal_code
                        latlng = {
                            "type": "Point",
                            "coordinates": [float(lon), float(lat)]
                        }
                        signup_data['location_default_on_error'] = 'true'
                        user_address = data['user']['location']

                    except:
                        text = "We cannot recognise your location please try again with a postal code or from http://foodtrade.com"
                        send_sms(cell_no, text)
                        return

                user_profile_obj = UserProfile()
                min_user_id = int(
                    user_profile_obj.get_minimum_id_of_user()[0]['minId']) - 1

                signup_data = {
                    'is_unknown_profile': 'false',
                    'from_mentions': 'true',
                    'address': user_address,
                    'latlng': latlng,
                    'email': user_email,
                    'zip_code': str(postal_code),
                    'description': "",
                    'foods': [],
                    'name': msg_from,
                    'phone_number': cell_no,
                    'profile_img':
                    "http://pbs.twimg.com/profile_images/378800000141996074/6a363e3c4f2a84a956c3cb27c50b2ca0_normal.png",
                    'sign_up_as': 'Individual',
                    'type_user': [],
                    'updates': [],
                    'screen_name': msg_from,
                    'Organisations': [],
                    'useruid': min_user_id,
                    'username': msg_from,
                    'subscribed': 0,
                    'newsletter_freq': 'Weekly'
                }

                join_time = datetime.datetime.now()
                join_time = time.mktime(join_time.timetuple())
                signup_data['join_time'] = int(join_time)
                user_profile_obj.create_profile(signup_data)
                '''Send Email to confirm Account SignUp via SMS'''
                email_object = Email()
                template_content = str(
                    render_to_response(
                        'notice-mail.html', {
                            'data': signup_data,
                            'register_request_type': 'SMS',
                            'phone': cell_no
                        }))
                template_content = template_content.replace(
                    'Content-Type: text/html; charset=utf-8', '')
                email_object.send_mail('Please confirm your account',
                                       template_content=[{
                                           'name':
                                           'main',
                                           'content':
                                           template_content
                                       }],
                                       to=[{
                                           'email': email
                                       }])

                try:
                    '''Transport the user to MailChimp'''
                    mailchimp_obj = MailChimpClass()
                    mailchimp_obj.subscribe(signup_data)
                except:
                    pass

                try:
                    mailchimp_obj_new = MailChimpClass(list_id='eeea3ac4c6')
                    mailchimp_obj_new.subscribe(data)
                except:
                    pass
                '''Send Confirmation SMS'''
                send_sms(
                    cell_no,
                    'You have successfully joined FoodTrade. Please visit http://foodtrade.com ASAP! Thanks!'
                )

                http_response = http_response + "appended new tweet"
    return HttpResponse(http_response)
コード例 #19
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def create_profile_from_mention(email, location, data):
    signup_data = {}
    try:
        location_res = Geocoder.geocode(location)
        latlng = {
            "type":
            "Point",
            "coordinates":
            [float(location_res.longitude),
             float(location_res.latitude)]
        }
        user_address = location
        postal_code = location_res.postal_code
    except:
        try:
            location_res = Geocoder.geocode(data['user']['location'])
            lat, lon, addr, postal_code = location_res.latitude, location_res.longitude, location_res.postal_code
            latlng = {"type": "Point", "coordinates": [float(lon), float(lat)]}
            signup_data['location_default_on_error'] = 'true'
            user_address = data['user']['location']

        except:
            text = "We cannot recognise your location please try again with a postal code or from http://foodtrade.com"
            HQ_twitter = get_twitter_obj(settings.HQ_ACCESS_TOKEN,
                                         settings.HQ_ACCESS_TOKEN_SECRET)
            HQ_twitter.update_status(status=text,
                                     in_reply_to_status_id=data['id'])
            return

    user_profile_obj = UserProfile()
    min_user_id = int(
        user_profile_obj.get_minimum_id_of_user()[0]['minId']) - 1

    signup_data = {
        'is_unknown_profile': 'false',
        'from_mentions': 'true',
        'address': user_address,
        'latlng': latlng,
        'email': email,
        'zip_code': str(postal_code),
        'description': data['user']['description'],
        'foods': [],
        'name': data['user']['name'],
        'phone_number': '',
        'profile_img': data['user']['profile_image_url'],
        'sign_up_as': 'Individual',
        'type_user': [],
        'updates': [],
        'screen_name': data['user']['screen_name'],
        'Organisations': [],
        'useruid': min_user_id,
        'username': data['user']['screen_name'],
        'subscribed': 0,
        'newsletter_freq': 'Weekly'
    }

    join_time = datetime.datetime.now()
    join_time = time.mktime(join_time.timetuple())
    signup_data['join_time'] = int(join_time)
    user_profile_obj.create_profile(signup_data)
    '''Send Email to confirm Account SignUp via Twitter'''
    template_content = str(
        render_to_response('notice-mail.html', {
            'data': signup_data,
            'register_request_type': 'Twitter'
        }))
    template_content = template_content.replace(
        'Content-Type: text/html; charset=utf-8', '')
    email_object = Email()
    email_object.send_mail('Please confirm your account',
                           template_content=[{
                               'name': 'main',
                               'content': template_content
                           }],
                           to=[{
                               'email': email
                           }])

    try:
        '''Transport the user to MailChimp'''
        mailchimp_obj = MailChimpClass()
        mailchimp_obj.subscribe(signup_data)
    except:
        pass

    try:
        mailchimp_obj_new = MailChimpClass(list_id='eeea3ac4c6')
        mailchimp_obj_new.subscribe(data)
    except:
        pass

    return {'status': 1}
コード例 #20
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def send_newsletter(request, substype):
    if request.GET.get('code') != '11foodtradeESRS22':
        return HttpResponseRedirect('/')
    user_profile_obj = UserProfile()
    substype = substype.capitalize()
    email_to_user = user_profile_obj.get_profile_by_username(
        str(request.GET.get('username')))
    count = 0
    try:
        subscription_status = email_to_user['subscribed']
    except:
        subscription_status = 0
    '''Generate activity for newsletter'''
    if subscription_status == 0:
        if substype == 'None' or substype == 'Weekly':
            '''Note ::: Please change the substype in below line to old after lots of data starts gathering ::: Note'''
            search_handle = Search(
                lon=email_to_user['latlng']['coordinates'][0],
                lat=email_to_user['latlng']['coordinates'][1],
                news="weekly")
        else:
            search_handle = Search(
                lon=email_to_user['latlng']['coordinates'][0],
                lat=email_to_user['latlng']['coordinates'][1],
                news=substype.lower())
    else:
        search_handle = Search(lon=email_to_user['latlng']['coordinates'][0],
                               lat=email_to_user['latlng']['coordinates'][1],
                               news=substype.lower())
    search_results = search_handle.search_all()['results']
    '''Make Default value of newsletter 10'''
    temp_result = []
    no_of_results = 10
    for res in search_results:
        if res["result_type"] == res["user"]["username"] and email_to_user[
                "username"] != res["user"]["username"]:
            temp_result.append(res)
        if len(temp_result) >= no_of_results:
            break
    results = temp_result
    '''Generate content for newsletter from activity'''
    tem_con = str(
        render_to_response('activity-email.html', {'results': results},
                           context_instance=RequestContext(request)))
    tem_con = tem_con.replace('Content-Type: text/html; charset=utf-8', '')
    try:
        if len(results) > 0:
            '''Do not send empty newsletter'''
            if len(email_to_user['email']) > 0:
                m = Email()
                m.send_mail(
                    "Your new business opportunity alerts from FoodTrade",
                    [{
                        'name': 'main',
                        'content': tem_con
                    }], [{
                        'email': email_to_user['email']
                    }])
            else:
                return HttpResponse(json.dumps({'status': '0'}))
    except:
        return HttpResponse(json.dumps({'status': '0'}))
    return HttpResponse(json.dumps({'status': '1'}))
コード例 #21
0
ファイル: forms.py プロジェクト: eddowding/foodtrade
    def save(self, user):
        new_username = self.cleaned_data.get(
            'username') if self.cleaned_data.get('username') != None else ''
        new_password1 = self.cleaned_data.get(
            'password1') if self.cleaned_data.get('password1') != None else ''
        print type(user), 'this is user', user,
        try:
            addr = self.cleaned_data['address']
            lat = self.cleaned_data['lat']
            lon = self.cleaned_data['lng']

            if len(lat) == 0 and len(lon) == 0:
                addr_geo = Geocoder.geocode(addr.strip())
                lat = float(addr_geo.latitude)
                lon = float(addr_geo.longitude)
                postal_code = str(addr_geo.postal_code)
            else:
                result = Geocoder.reverse_geocode(float(lat), float(lon))
                postal_code = str(result.postal_code)
        except:
            lat, lon, addr, postal_code = 51.5072, -0.1275, "3 Whitehall, London SW1A 2EL, UK", "SW1 A 2EL"

        invite_id = ''
        try:
            invite_id = self.request.session['invite_id']
        except:
            invite_id = ''

        address = addr
        '''Get user from the SocialAccount MySql'''
        userprofile = UserProfile()
        try:
            social_account = SocialAccount.objects.get(user__id=user.id)
        except:
            social_account = None
        try:
            old_useruid = userprofile.get_profile_by_username(
                str(social_account.extra_data['screen_name']))['useruid']
            '''update all other affected collections when unclaimed profile changes to claimed'''
            update_all_values(int(old_useruid), int(user.id))
        except:
            pass
        default_profile_img = 'http://a0.twimg.com/sticky/default_profile_images/default_profile_6_normal.png'
        data = {
            'is_unknown_profile':
            'false',
            'useruid':
            int(user.id),
            'sign_up_as':
            str(self.cleaned_data['sign_up_as']),
            'type_user':
            str(self.cleaned_data['type_user']).split(","),
            'zip_code':
            str(postal_code),
            'latlng': {
                "type": "Point",
                "coordinates": [float(lon), float(lat)]
            },
            'address':
            address,
            # 'name': social_account.extra_data['name'],
            'business_org_name':
            self.cleaned_data['buss_org_name'],
            'name':
            self.cleaned_data['display_name'],
            'email':
            str(self.cleaned_data['email']),
            'description':
            social_account.extra_data['description']
            if social_account != None else '',
            'username':
            user.username,
            'screen_name':
            social_account.extra_data['screen_name']
            if social_account != None else new_username,
            'profile_img':
            social_account.extra_data['profile_image_url']
            if social_account != None else default_profile_img,
            'updates': [],
            'foods': [],
            'organisations': [],
            'subscribed':
            0,
            'newsletter_freq':
            'Weekly',
            'followers_count':
            social_account.extra_data['followers_count']
            if social_account != None else 0,
            'friends_count':
            social_account.extra_data['friends_count']
            if social_account != None else 0
        }
        try:
            data['profile_banner_url'] = social_account.extra_data[
                'profile_banner_url'] if social_account != None else ''
        except:
            pass

        if new_password1 != '':
            data['email_registration'] = 1

        join_time = datetime.datetime.now()
        join_time = time.mktime(join_time.timetuple())
        data['join_time'] = int(join_time)
        data['trial_period_starts'] = int(join_time)
        '''Transport  user from MySql to Mongo'''
        # userprofile.update_profile_upsert({'screen_name':social_account.extra_data['screen_name'],
        #          'username':social_account.extra_data['screen_name']},data)
        userprofile.update_profile_upsert(
            {
                'screen_name': data['screen_name'],
                'username': data['username']
            }, data)

        conn = TradeConnection()
        if self.cleaned_data['sign_up_as'] == "Business":
            try:
                usr = User.objects.get(id=99)
                con_data = {'c_useruid': int(user.id), 'b_useruid': 99}
                conn.create_connection(con_data)
            except:
                pass

        try:
            '''Transport user to MailChimp List'''
            mailchimp_obj = MailChimpClass()
            mailchimp_obj.subscribe(data)
            mailchimp_obj_new = MailChimpClass(list_id='eeea3ac4c6')
            mailchimp_obj_new.subscribe(data)
        except:
            pass
        '''Invitation Tracking and Notifying the user who invites the user'''
        if invite_id != '':
            invititation_to = user.username
            # screen_name = social_account.extra_data['screen_name']
            screen_name = data['screen_name']
            invite_accept_obj = InviteAccept()
            invites_obj = Invites()
            result = invites_obj.check_invited_by_invite_id(
                str(screen_name), str(invite_id))
            try:
                if (len(result) > 0):
                    invited_by = result['from_username']
                    invite_accept_obj.insert_invite_accept(
                        invite_id, invited_by, invititation_to)

                    notification_obj = Notification()
                    invites_obj = Invites()
                    '''If the joined user is invited Send notification to who invited'''
                    notification_obj.save_notification({
                        'notification_to':
                        str(invited_by),
                        'notification_message':
                        '@' + str(screen_name) +
                        ' has accepted your invitation and joined FoodTrade. You can connect and add him to your contacts.',
                        'notification_time':
                        time.mktime(datetime.datetime.now().timetuple()),
                        'notification_type':
                        'Invitation Accept',
                        'notification_view_status':
                        'false',
                        'notification_archived_status':
                        'false',
                        'notifying_user':
                        str(screen_name)
                    })

                    now = datetime.datetime.now()
                    notification_time = time.mktime(now.timetuple())

                    invitees_for_this_user = invites_obj.check_invitees(
                        screen_name)
                    if (len(invitees_for_this_user) > 0):
                        for eachInvitees in invitees_for_this_user:
                            notification_obj.save_notification({
                                'notification_to':
                                eachInvitees['from_username'],
                                'notification_message':
                                '@' + str(screen_name) +
                                ' joined FoodTrade. You can add to your contacts and connect.',
                                'notification_time':
                                time.mktime(
                                    datetime.datetime.now().timetuple()),
                                'notification_type':
                                'Joined FoodTrade',
                                'notification_view_status':
                                'false',
                                'notification_archived_status':
                                'false',
                                'notifying_user':
                                str(screen_name)
                            })
            except:
                return HttpResponseRedirect('/activity/')
        if str(self.cleaned_data['sign_up_as']) == "Business":
            # settings.LOGIN_REDIRECT_URL = "/payments/subscribe"
            # return HttpResponseRedirect('/payments/subscribe')
            settings.LOGIN_REDIRECT_URL = "/me/"
            return HttpResponseRedirect('/me/')
        else:
            # settings.LOGIN_REDIRECT_URL = "/activity"
            return HttpResponseRedirect('/activity/')
コード例 #22
0
ファイル: views.py プロジェクト: eddowding/foodtrade
def tweets(request):
    parameters = {}
    HQ_twitter = get_twitter_obj(settings.HQ_ACCESS_TOKEN,
                                 settings.HQ_ACCESS_TOKEN_SECRET)
    bot_twitter = get_twitter_obj(settings.BOT_ACCESS_TOKEN,
                                  settings.BOT_ACCESS_TOKEN_SECRET)
    try:
        max_id = MaxTweetId.objects.all()[0]
    except:
        max_id = MaxTweetId(max_tweet_id=12345)
        max_id.save()
    max_tweet_id = int(max_id.max_tweet_id)
    mentions = HQ_twitter.get_mentions_timeline(count=200,
                                                contributer_details=True,
                                                since_id=max_tweet_id)
    tweet_list = []
    user_profile = UserProfile()
    display_tweets = []
    tweet_feed = TweetFeed()

    for tweet in mentions:
        print tweet
        tweet_list.append(tweet['id'])

        try:
            user_profile = UserProfile()
            usr = user_profile.get_profile_by_username(
                tweet['user']['screen_name'])
            if usr['useruid'] == -1:
                continue

            pic_url_list = []
            if tweet['entities'].get('media') != None:
                for each in tweet['entities'].get('media'):
                    pic_url_list.append(each['media_url'])
            h = HTMLParser.HTMLParser()
            tweet_id = str(tweet['id'])

            parent_id = tweet.get('in_reply_to_status_id')
            if parent_id == None:
                h = HTMLParser.HTMLParser()
                str_text = h.unescape(tweet['text'].strip()).encode('utf-8')
                str_text = str_text[:12].lower()
                if (str_text != "@foodtradehq"):
                    continue

            else:
                single_tweet = tweet_feed.get_tweet_by_id(str(parent_id))
                if single_tweet == None:
                    continue

            parent_tweet_id = "0" if parent_id == None else str(parent_id)

            data = {
                'tweet_id': str(tweet_id),
                'parent_tweet_id': str(parent_tweet_id),
                'status': h.unescape(tweet['text']),
                'picture': pic_url_list,
            }
            tweet_feed.insert_tweet_by_username(usr['username'], data)

        except:
            tweet_id = str(tweet['id'])
            text = "@" + tweet['user'][
                'screen_name'] + " Thanks! Please confirm your post by clicking this http://foodtrade.com/?tweetid=" + str(
                    tweet_id) + " You'll only have to do this once."

            h = HTMLParser.HTMLParser()
            str_text = h.unescape(tweet['text']).encode('utf-8')
            str_text = str_text.replace("#signup", "#join")
            str_text = str_text.replace("#register", "#join")
            if "#join" in str_text:
                str_text = str_text.lower()
                str_text = str_text.strip()
                str_text = str_text.replace('@foodtradehq', "")
                str_text = str_text.strip()
                str_text = str_text.replace("#join", "")
                str_text = str_text.strip()
                import re

                regex = re.compile((
                    "([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
                    "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
                    "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))

                user_emails = re.findall(regex, str_text)

                if len(user_emails) > 0:
                    user_email = user_emails[0][0]
                    str_text = str_text.replace(user_email, "")
                    location = str_text.strip()
                    create_profile_from_mention(user_email, location, tweet)

    if len(tweet_list) != 0:
        max_id.max_tweet_id = max(tweet_list)
        max_id.save()
    return render_to_response('home.html', parameters)