示例#1
0
    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'
示例#2
0
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'}))
示例#3
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)
示例#4
0
    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/')
示例#5
0
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'}))
示例#6
0
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)
示例#7
0
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))
示例#8
0
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)