def follow(request, user_name):
    if request.method == 'GET':
        userprofile = UserProfile.objects.get(username=user_name)
        requestuser = UserProfile.objects.get(username=request.user.username)

        if(request.user != userprofile):
            mutual_fol = []
            mutual = get_followers(request, user_name)['followers']
            for item in mutual:
                mutual_fol += [item.follower]
            Follow.objects.get_or_create(follower=requestuser, followed=userprofile)
            sender_profile = UserProfile.objects.get(pk=request.user.id)
            sender = User.objects.get(pk=request.user.id)
            the_message = sender.first_name + ' is now following you'
            if sender_profile.gender == 'F':
                the_message_arabic = sender.first_name + " تتابعك الآن".decode("utf-8")
                receivers = [User.objects.get(username=user_name)]
                the_link = '/accounts/profile/' + str(sender.username)
                send_now(receivers, sender, 'new_follower', the_message, the_message_arabic, the_link)
                for receiver in receivers:
                    if not receiver.id == request.user.id:
                        notices = Notice.objects.filter(recipient=receiver, sender=sender, message=the_message, message_arabic=the_message_arabic, link=the_link)
                        p['channel_' + str(receiver.username)].trigger('notification', {
                            'message': '<a href="/notifications/' + str(sender.username) + '/">' + sender.first_name + ' ' + sender.last_name + ' is now following you.</a>',
                            'name': '<a href="/notifications/' + str(notices[0].id) + '/">' + sender.first_name + ' ' + sender.last_name + '</a>',
                            'translated': 'is now following you ',
                            'link': ' ',
                            'the_title': ' ',
                            'the_title_translated': 'You have a new follower',
                        })
            else:
                the_message_arabic = sender.first_name + " يتابعك الآن".decode("utf-8")
                receivers = [User.objects.get(username=user_name)]
                the_link = '/accounts/profile/' + str(sender.username)
                send_now(receivers, sender, 'new_follower', the_message, the_message_arabic, the_link)
                for receiver in receivers:
                    if not receiver.id == request.user.id:
                        notices = Notice.objects.filter(recipient=receiver, sender=sender, message=the_message, message_arabic=the_message_arabic, link=the_link)
                        p['channel_' + str(receiver.username)].trigger('notification', {
                            'message': '<a href="/notifications/' + str(sender.username) + '/">' + sender.first_name + ' ' + sender.last_name + ' is now following you.</a>',
                            'name': '<a href="/notifications/' + str(notices[0].id) + '/">' + sender.first_name + ' ' + sender.last_name + '</a>',
                            'translated': 'is now following you',
                            'link': ' ',
                            'the_title': ' ',
                            'the_title_translated': 'You have a new follower',
                        })

            actor = UserProfile.objects.get(username=request.user.username)
            target = UserProfile.objects.get(username=user_name)

            if isinstance(actor, UserProfile) and isinstance(target, UserProfile):
                add_action(actor, "followed", target, 'followed', target)

            return HttpResponse()
        return HttpResponse()
Пример #2
0
def follow(request, skill_id):
    if request.method == 'GET':
        skill = Tag.objects.get(id=skill_id)
        requestuser = UserProfile.objects.filter(username=request.user.username)
        if len(requestuser) > 0:
            requestuser = requestuser[0]
        else:
            return HttpResponse()
        Follow.objects.get_or_create(follower=requestuser, followed=None, followed_skill=skill)
        from shoghlanah.live_stream import add_action
        add_action(requestuser, "followed_skill", Tag.objects.get(id=skill_id), 'followed', Tag.objects.get(id=skill_id))
        return HttpResponse()
def edit_profile_pic(request, user_name):
    print request.FILES
    editor = UserProfile.objects.get(username=request.user.username)

    form = uploadProfilePicture(request.POST, request.FILES)
    changeimage = False
    if form.is_valid():
        image = form.cleaned_data.get('image')
        if not image == editor.profile_picture:
            changeimage = True
            editor.profile_picture = image
            editor.save()
            add_action(UserProfile.objects.get(username=user_name), "changed_profile_picture", UserProfile.objects.get(username=user_name), str(editor.profile_picture), UserProfile.objects.get(username=user_name))
    return redirect('/accounts/profile/' + request.user.username + '/')
Пример #4
0
def follow(request, skill_id):
    if request.method == 'GET':
        skill = Tag.objects.get(id=skill_id)
        requestuser = UserProfile.objects.filter(
            username=request.user.username)
        if len(requestuser) > 0:
            requestuser = requestuser[0]
        else:
            return HttpResponse()
        Follow.objects.get_or_create(follower=requestuser,
                                     followed=None,
                                     followed_skill=skill)
        from shoghlanah.live_stream import add_action
        add_action(requestuser, "followed_skill", Tag.objects.get(id=skill_id),
                   'followed', Tag.objects.get(id=skill_id))
        return HttpResponse()
Пример #5
0
def action_gallery(request, count):
    photos = Photo.objects.filter(owner__id=request.user.id).order_by('id')
    x = photos.reverse()[:int(count)]
    url_list = [u.image.url for u in x]
    url_list = url_list[0]
    requestuser = UserProfile.objects.get(username=request.user.username)
    try:
        url_list = url_list[0:url_list.index('?')]
    except:
        pass
    add_action(actor=requestuser,
               verb="upload_photo",
               action_object=requestuser,
               description=url_list,
               target=requestuser)
    return HttpResponse('')
Пример #6
0
def edit_profile_pic(request, user_name):
    print request.FILES
    editor = UserProfile.objects.get(username=request.user.username)

    form = uploadProfilePicture(request.POST, request.FILES)
    changeimage = False
    if form.is_valid():
        image = form.cleaned_data.get('image')
        if not image == editor.profile_picture:
            changeimage = True
            editor.profile_picture = image
            editor.save()
            add_action(UserProfile.objects.get(username=user_name),
                       "changed_profile_picture",
                       UserProfile.objects.get(username=user_name),
                       str(editor.profile_picture),
                       UserProfile.objects.get(username=user_name))
    return redirect('/accounts/profile/' + request.user.username + '/')
Пример #7
0
def save_upload(uploaded, filename, raw_data, user):
    """
    raw_data: if True, uploaded is an HttpRequest object with the file being
            the raw post data 
            if False, uploaded has been submitted via the basic form
            submission and is a regular Django UploadedFile in request.FILES
    """
    try:
        filename = filename.replace(" ", "_")
        filepath = '/'.join(['Gallery', user.username, filename])
        from io import FileIO, BufferedWriter
        with BufferedWriter(
                FileIO('/'.join([settings.MEDIA_ROOT, filepath]),
                       "wb")) as dest:
            # if the "advanced" upload, read directly from the HTTP request
            # with the Django 1.3 functionality
            if raw_data:
                foo = uploaded.read(1024)
                while foo:
                    dest.write(foo)
                    foo = uploaded.read(1024)
            # if not raw, it was a form upload so read in the normal Django chunks fashion
            else:
                for c in uploaded.chunks():
                    dest.write(c)
                # got through saving the upload, report success
            image = Photo()
            image.title = filename
            image.image = filepath
            image.owner = user
            image.save()
            add_action(actor=user,
                       verb="upload_photo",
                       action_object=user,
                       description=image.image,
                       target=user)
            return True
    except IOError:
        # could not open the file most likely
        pass
    return False
Пример #8
0
def post_task(request):
    """
    This method is called when the user posts a task

    The information taken from the html form and creates a task
    with the data entered in the postTask modal

    The Task created is assigned to the user currently login

    After the task is saved in the database, the user is redirected
    to the page the posttask action wast triggered from

    Variable:
    next : is the variable which contains the name of the page
    the posttask was triggered from.
    """

    if request.method == 'POST':
        try:
            # price = request.POST['price']
            # if price == 'Reward':
            #     reward_id = request.POST['reward']
            #     reward = Reward.objects.get(pk = reward_id)
            #     price = None
            # else:
            price = int(request.POST['sliderInput'])
            reward = None
            if isinstance(price, int):
                price = price
            else:
                raise ValueError('Invalid price')
            # if price == None and reward == None:
            if price is None:
                raise ValidationError(
                    u'You have to enter price or reward of the task')
            longitude = request.POST['long']
            latitude = request.POST['lat']
            latitude = latitude.replace(',', '.')
            longitude = longitude.replace(',', '.')
            if longitude == '' or latitude == '':
                longitude = 200.0
                latitude = 200.0
            user = UserProfile.objects.get(id=request.user.id)
            location = request.POST['where']
            if location is not None and len(location) > 0:
                temp_loc = location.split(',')
                if len(temp_loc) > 1:
                    city = temp_loc[len(temp_loc) - 2].strip()
                else:
                    city = temp_loc[0].strip()
                if city.endswith('Governorate'):
                    city = city[:-len('Governorate')].strip()
            else:
                raise ValueError('Empty location')

            title = request.POST['task_name']
            if title is not None and len(title) > 0 and not title.isspace():
                if (len(title) <= 128):
                    title = title.strip()
                else:
                    raise ValueError('Title Too long')
            else:
                raise ValueError('Empty Title')
            task = Task.objects.create(
                title=title,
                address=location,
                city=city,
                price=price,
                reward=reward,
                description=request.POST['task_desc'],
                user=user,
                longitude=float(longitude),
                latitude=float(latitude),
                status='New',
                start_date=datetime.datetime.now(),
            )

            task.tags = ',' + request.POST['skills']
            if 'got_started' in request.POST:

                user.got_started = True
                user.save()
            task.save()
            add_action(user, "task_post", task, "", user)
            # sender = []
            # for tag in task.tags:
            #     sender.append(User.objects.filter(tag__contains=tag))
            sender_profile = UserProfile.objects.get(pk=request.user.id)
            sender = User.objects.get(pk=request.user.id)
            the_message = sender.first_name + ' needs "' + task.title + '"'
            if sender_profile.gender == 'F':
                the_message_arabic = sender.first_name + ' تريد "'.decode(
                    "utf-8") + task.title + '"'
            else:
                the_message_arabic = sender.first_name + ' يريد "'.decode(
                    "utf-8") + task.title + '"'
            receivers = [
                UserProfile.objects.get(id=item.object_id)
                for skill in task.tags
                for item in TaggedItem.objects.filter(tag=skill.id)
                if item.content_type.name == u'user profile'
                and item.object_id != request.user.id
            ]
            the_link = '/task/' + str(task.id)
            send_now(receivers, sender, 'post_task', the_message,
                     the_message_arabic, the_link)

            for receiver in receivers:
                if not receiver.id == request.user.id:
                    notices = Notice.objects.filter(
                        recipient=receiver,
                        sender=sender,
                        message=the_message,
                        message_arabic=the_message_arabic,
                        link=the_link)
                    p['channel_' + str(receiver.username)].trigger(
                        'notification', {
                            'message':
                            sender.first_name + ' ' + sender.last_name +
                            ' needs  ' + '<a href="/task/' + str(task.id) +
                            '/">' + task.title + '</a>',
                            'name':
                            sender.first_name + ' ' + sender.last_name,
                            'translated':
                            'needs',
                            'link':
                            '<a href="/notifications/' + str(notices[0].id) +
                            '/">' + task.title + '</a>',
                            'the_title_translated':
                            'A New shoghlanah is Posted',
                            'the_title':
                            ' ',
                        })

            from shoghlanah.views import email_html
            subject = "A new shoghlanah is posted"
            to = []
            for receiver in receivers:
                # thereceiver = UserProfile.objects.get(id=receiver.id)
                # if thereceiver.email_new_shoghlanah:
                to.append(receiver.email)
            from_email = settings.EMAIL_HOST_USER
            msg = ' shoghlanah is posted.'
            dic = {}
            dic['task'] = task
            email_html(subject=subject,
                       from_email=from_email,
                       to=to,
                       msg=msg,
                       dic=dic)

            # if user.complete_profile <= 100:
            #     return redirect() #to complete hos profile

            if 'facebook' in request.POST:
                post_task_fb(task=task, request=request)
            if 'twitter' in request.POST:
                tweet(request,
                      status="i posted a task on #Shoghlanah " +
                      DEPLOYED_ADDRESS + "task/" + str(task.id) + '/')
            # if 'google' in request.POST:

            messages.info(request,
                          translation.gettext("Created a task successfully"))
            return redirect('/task/' + str(task.id),
                            context_instance=RequestContext(request))
        except:
            messages.warning(
                request,
                translation.gettext("Failed to post a task, try again"))
            return redirect(request.GET['next'],
                            context_instance=RequestContext(request))
def edit(request):
    """
    Dont forget the documentation.
    """
    user_name = request.user.username
    editor = UserProfile.objects.get(username=request.user.username)

    try:
        facebook_link = ''
        twitter_link = ''
        google_plus_link = ''
        linkedin_link = ''

        if 'google_plus' in request.POST:
            if not request.POST['google_plus'] is None:
                google_plus_link = request.POST['google_plus']

        if 'linkedin' in request.POST:
            if not request.POST['linkedin'] is None:
                linkedin_link = request.POST['linkedin']

        if 'gender' in request.POST:
            if request.POST['gender'] == "male":
                editor.gender = 'M'
            else:
                editor.gender = 'F'
            editor.save()

        if not request.POST['first_name'] == "":
            if not request.POST['first_name'] == editor.first_name:
                editor.first_name = request.POST['first_name']
                if editor.gender == 'F':
                    add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed her first name', UserProfile.objects.get(username=user_name))
                else:
                    add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed his first name', UserProfile.objects.get(username=user_name))
        else:
            raise ValidationError('Empty First Name')

        if not request.POST['last_name'] == "":
            if not request.POST['last_name'] == editor.last_name:
                editor.last_name = request.POST['last_name']
                if editor.gender == 'F':
                    add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed her last name', UserProfile.objects.get(username=user_name))
                else:
                    add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed his last name', UserProfile.objects.get(username=user_name))
        else:
            raise ValidationError('Empty Last Name')

        if not request.POST['job_title'] == editor.job_title:
            editor.job_title = request.POST['job_title']
            if editor.gender == 'F':
                add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed her job title', UserProfile.objects.get(username=user_name))
            else:
                add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed his job title', UserProfile.objects.get(username=user_name))

        if not request.POST['mobile_number'] == editor.mobile_number:
            if request.POST['mobile_number'] == 11:
                editor.isVerified = False
                editor.isRequest_Verification = False
                if request.POST['mobile_number'] == "":
                    editor.mobile_number = None
                else:
                    editor.mobile_number = int(request.POST['mobile_number'])
                if editor.gender == 'F':
                    add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed her mobile number', UserProfile.objects.get(username=user_name))
                else:
                    add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed his mobile number', UserProfile.objects.get(username=user_name))

        if not request.POST['about_me'] == editor.about:
            editor.about = request.POST['about_me']
            if editor.gender == 'F':
                add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), "changed her 'About Me' info", UserProfile.objects.get(username=user_name))
            else:
                add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), "changed his 'About Me' info", UserProfile.objects.get(username=user_name))

        if not request.POST['where'] == editor.location:
            location = request.POST['where']
            city = ''
            if location is not None and len(location) > 0:
                temp_loc = location.split(',')
                if len(temp_loc) > 1:
                    city = temp_loc[len(temp_loc)-2].strip()
                else:
                    city = temp_loc[0].strip()
                if city.endswith('Governorate'):
                    city = city[:-len('Governorate')].strip()
            editor.location = location
            editor.city = city
            longitude = request.POST['lng']
            latitude = request.POST['lat']
            if longitude == '' or latitude == '' or city == '':
                longitude = 200.0
                latitude = 200.0
            editor.latitude = latitude
            editor.longitude = longitude
            if editor.gender == 'F':
                add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed her location', UserProfile.objects.get(username=user_name))
            else:
                add_action(UserProfile.objects.get(username=user_name), "edited_profile", UserProfile.objects.get(username=user_name), 'changed his location', UserProfile.objects.get(username=user_name))

        # Google+ Saving
        if editor.google_plus_link:
            if not request.POST['google_plus'] == editor.google_plus_link:
                editor.google_plus_link = google_plus_link
        else:
            if not google_plus_link == "":
                editor.google_plus_link = google_plus_link

        # LinkedIn Saving
        if editor.linkedin_link:
            if not request.POST['linkedin'] == editor.linkedin_link:
                editor.linkedin_link = linkedin_link
        else:
            if not linkedin_link == "":
                editor.linkedin_link = linkedin_link

        editor.tags = request.POST['skills']  # Skills editing part

        editor.save()

        if form.is_valid():
            if not image == editor.profile_picture:
                add_action(UserProfile.objects.get(username=user_name), "changed_profile_picture", UserProfile.objects.get(username=user_name), str(editor.profile_picture), UserProfile.objects.get(username=user_name))

        # calculate_profile_completion(request)

    except ValidationError as e:
        raise e
    except ValueError:
        raise Http404("Phone Number cant be a string")
    return redirect('/accounts/profile/' + request.user.username + '/')
Пример #10
0
def edit(request):
    """
    Dont forget the documentation.
    """
    user_name = request.user.username
    editor = UserProfile.objects.get(username=request.user.username)

    try:
        facebook_link = ''
        twitter_link = ''
        google_plus_link = ''
        linkedin_link = ''

        if 'google_plus' in request.POST:
            if not request.POST['google_plus'] is None:
                google_plus_link = request.POST['google_plus']

        if 'linkedin' in request.POST:
            if not request.POST['linkedin'] is None:
                linkedin_link = request.POST['linkedin']

        if 'gender' in request.POST:
            if request.POST['gender'] == "male":
                editor.gender = 'M'
            else:
                editor.gender = 'F'
            editor.save()

        if not request.POST['first_name'] == "":
            if not request.POST['first_name'] == editor.first_name:
                editor.first_name = request.POST['first_name']
                if editor.gender == 'F':
                    add_action(UserProfile.objects.get(username=user_name),
                               "edited_profile",
                               UserProfile.objects.get(username=user_name),
                               'changed her first name',
                               UserProfile.objects.get(username=user_name))
                else:
                    add_action(UserProfile.objects.get(username=user_name),
                               "edited_profile",
                               UserProfile.objects.get(username=user_name),
                               'changed his first name',
                               UserProfile.objects.get(username=user_name))
        else:
            raise ValidationError('Empty First Name')

        if not request.POST['last_name'] == "":
            if not request.POST['last_name'] == editor.last_name:
                editor.last_name = request.POST['last_name']
                if editor.gender == 'F':
                    add_action(UserProfile.objects.get(username=user_name),
                               "edited_profile",
                               UserProfile.objects.get(username=user_name),
                               'changed her last name',
                               UserProfile.objects.get(username=user_name))
                else:
                    add_action(UserProfile.objects.get(username=user_name),
                               "edited_profile",
                               UserProfile.objects.get(username=user_name),
                               'changed his last name',
                               UserProfile.objects.get(username=user_name))
        else:
            raise ValidationError('Empty Last Name')

        if not request.POST['job_title'] == editor.job_title:
            editor.job_title = request.POST['job_title']
            if editor.gender == 'F':
                add_action(UserProfile.objects.get(username=user_name),
                           "edited_profile",
                           UserProfile.objects.get(username=user_name),
                           'changed her job title',
                           UserProfile.objects.get(username=user_name))
            else:
                add_action(UserProfile.objects.get(username=user_name),
                           "edited_profile",
                           UserProfile.objects.get(username=user_name),
                           'changed his job title',
                           UserProfile.objects.get(username=user_name))

        if not request.POST['mobile_number'] == editor.mobile_number:
            if request.POST['mobile_number'] == 11:
                editor.isVerified = False
                editor.isRequest_Verification = False
                if request.POST['mobile_number'] == "":
                    editor.mobile_number = None
                else:
                    editor.mobile_number = int(request.POST['mobile_number'])
                if editor.gender == 'F':
                    add_action(UserProfile.objects.get(username=user_name),
                               "edited_profile",
                               UserProfile.objects.get(username=user_name),
                               'changed her mobile number',
                               UserProfile.objects.get(username=user_name))
                else:
                    add_action(UserProfile.objects.get(username=user_name),
                               "edited_profile",
                               UserProfile.objects.get(username=user_name),
                               'changed his mobile number',
                               UserProfile.objects.get(username=user_name))

        if not request.POST['about_me'] == editor.about:
            editor.about = request.POST['about_me']
            if editor.gender == 'F':
                add_action(UserProfile.objects.get(username=user_name),
                           "edited_profile",
                           UserProfile.objects.get(username=user_name),
                           "changed her 'About Me' info",
                           UserProfile.objects.get(username=user_name))
            else:
                add_action(UserProfile.objects.get(username=user_name),
                           "edited_profile",
                           UserProfile.objects.get(username=user_name),
                           "changed his 'About Me' info",
                           UserProfile.objects.get(username=user_name))

        if not request.POST['where'] == editor.location:
            location = request.POST['where']
            city = ''
            if location is not None and len(location) > 0:
                temp_loc = location.split(',')
                if len(temp_loc) > 1:
                    city = temp_loc[len(temp_loc) - 2].strip()
                else:
                    city = temp_loc[0].strip()
                if city.endswith('Governorate'):
                    city = city[:-len('Governorate')].strip()
            editor.location = location
            editor.city = city
            longitude = request.POST['lng']
            latitude = request.POST['lat']
            if longitude == '' or latitude == '' or city == '':
                longitude = 200.0
                latitude = 200.0
            editor.latitude = latitude
            editor.longitude = longitude
            if editor.gender == 'F':
                add_action(UserProfile.objects.get(username=user_name),
                           "edited_profile",
                           UserProfile.objects.get(username=user_name),
                           'changed her location',
                           UserProfile.objects.get(username=user_name))
            else:
                add_action(UserProfile.objects.get(username=user_name),
                           "edited_profile",
                           UserProfile.objects.get(username=user_name),
                           'changed his location',
                           UserProfile.objects.get(username=user_name))

        # Google+ Saving
        if editor.google_plus_link:
            if not request.POST['google_plus'] == editor.google_plus_link:
                editor.google_plus_link = google_plus_link
        else:
            if not google_plus_link == "":
                editor.google_plus_link = google_plus_link

        # LinkedIn Saving
        if editor.linkedin_link:
            if not request.POST['linkedin'] == editor.linkedin_link:
                editor.linkedin_link = linkedin_link
        else:
            if not linkedin_link == "":
                editor.linkedin_link = linkedin_link

        editor.tags = request.POST['skills']  # Skills editing part

        editor.save()

        if form.is_valid():
            if not image == editor.profile_picture:
                add_action(UserProfile.objects.get(username=user_name),
                           "changed_profile_picture",
                           UserProfile.objects.get(username=user_name),
                           str(editor.profile_picture),
                           UserProfile.objects.get(username=user_name))

        # calculate_profile_completion(request)

    except ValidationError as e:
        raise e
    except ValueError:
        raise Http404("Phone Number cant be a string")
    return redirect('/accounts/profile/' + request.user.username + '/')
Пример #11
0
def follow(request, user_name):
    if request.method == 'GET':
        userprofile = UserProfile.objects.get(username=user_name)
        requestuser = UserProfile.objects.get(username=request.user.username)

        if (request.user != userprofile):
            mutual_fol = []
            mutual = get_followers(request, user_name)['followers']
            for item in mutual:
                mutual_fol += [item.follower]
            Follow.objects.get_or_create(follower=requestuser,
                                         followed=userprofile)
            sender_profile = UserProfile.objects.get(pk=request.user.id)
            sender = User.objects.get(pk=request.user.id)
            the_message = sender.first_name + ' is now following you'
            if sender_profile.gender == 'F':
                the_message_arabic = sender.first_name + " تتابعك الآن".decode(
                    "utf-8")
                receivers = [User.objects.get(username=user_name)]
                the_link = '/accounts/profile/' + str(sender.username)
                send_now(receivers, sender, 'new_follower', the_message,
                         the_message_arabic, the_link)
                for receiver in receivers:
                    if not receiver.id == request.user.id:
                        notices = Notice.objects.filter(
                            recipient=receiver,
                            sender=sender,
                            message=the_message,
                            message_arabic=the_message_arabic,
                            link=the_link)
                        p['channel_' + str(receiver.username)].trigger(
                            'notification', {
                                'message':
                                '<a href="/notifications/' +
                                str(sender.username) + '/">' +
                                sender.first_name + ' ' + sender.last_name +
                                ' is now following you.</a>',
                                'name':
                                '<a href="/notifications/' +
                                str(notices[0].id) + '/">' +
                                sender.first_name + ' ' + sender.last_name +
                                '</a>',
                                'translated':
                                'is now following you ',
                                'link':
                                ' ',
                                'the_title':
                                ' ',
                                'the_title_translated':
                                'You have a new follower',
                            })
            else:
                the_message_arabic = sender.first_name + " يتابعك الآن".decode(
                    "utf-8")
                receivers = [User.objects.get(username=user_name)]
                the_link = '/accounts/profile/' + str(sender.username)
                send_now(receivers, sender, 'new_follower', the_message,
                         the_message_arabic, the_link)
                for receiver in receivers:
                    if not receiver.id == request.user.id:
                        notices = Notice.objects.filter(
                            recipient=receiver,
                            sender=sender,
                            message=the_message,
                            message_arabic=the_message_arabic,
                            link=the_link)
                        p['channel_' + str(receiver.username)].trigger(
                            'notification', {
                                'message':
                                '<a href="/notifications/' +
                                str(sender.username) + '/">' +
                                sender.first_name + ' ' + sender.last_name +
                                ' is now following you.</a>',
                                'name':
                                '<a href="/notifications/' +
                                str(notices[0].id) + '/">' +
                                sender.first_name + ' ' + sender.last_name +
                                '</a>',
                                'translated':
                                'is now following you',
                                'link':
                                ' ',
                                'the_title':
                                ' ',
                                'the_title_translated':
                                'You have a new follower',
                            })

            actor = UserProfile.objects.get(username=request.user.username)
            target = UserProfile.objects.get(username=user_name)

            if isinstance(actor, UserProfile) and isinstance(
                    target, UserProfile):
                add_action(actor, "followed", target, 'followed', target)

            return HttpResponse()
        return HttpResponse()
Пример #12
0
def ajax_upload(request):
    if request.method == "POST":
        if request.is_ajax():

            # the file is stored raw in the request
            upload = request
            is_raw = True
            # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
            try:
                filename = request.GET['qqfile']
            except KeyError:
                return HttpResponseBadRequest("AJAX request not valid")
        # not an ajax upload, so it was the "basic" iframe version with submission via form
        else:

            is_raw = False
            if len(request.FILES) == 1:
                # FILES is a dictionary in Django but Ajax Upload gives the uploaded file an
                # ID based on a random number, so it cannot be guessed here in the code.
                # Rather than editing Ajax Upload to pass the ID in the querystring,
                # observer that each upload is a separate request,
                # so FILES should only have one entry.
                # Thus, we can just grab the first (and only) value in the dict.
                upload = request.FILES.values()[0]
            else:
                raise Http404("Bad Upload")
                filename = upload.name

        # save the file
        user = UserProfile.objects.get(id=request.user.id)
        # In case locally
        if settings.DEBUG:
            folder = '/'.join([settings.MEDIA_ROOT, 'Gallery', user.username])
            if not os.path.isdir(folder):
                os.makedirs(folder)
            filename = filename.replace(" ", "_")
            success = save_upload(upload, filename, is_raw, user)
        else:
            filename = filename.replace(" ", "_")

            # The path to save to the image
            folder = '/'.join(
                [settings.MEDIA_ROOT + 'Gallery', user.username, filename])
            filepath = '/'.join(['Gallery', user.username, filename])
            # Initiate the connection with S3
            c = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,
                                settings.AWS_SECRET_ACCESS_KEY)
            s3 = c.lookup(settings.AWS_STORAGE_BUCKET_NAME)
            mp = s3.initiate_multipart_upload(folder)

            success = upload_file(upload, folder, is_raw, user, mp)
            if success:
                # for debug to check if the the file is uploaded
                mp.complete_upload()
                print 'after complete'
                image = Photo()
                image.title = filename
                image.image = filepath
                image.owner = user
                image.save()
                add_action(actor=user,
                           verb="upload_photo",
                           action_object=user,
                           description=image.image,
                           target=user)
            else:
                mp.cancel_upload()
        # let Ajax Upload know whether we saved it or not
        import json
        ret_json = {
            'success': success,
        }
        return HttpResponse(json.dumps(ret_json))