def contact(request):
    if request.method == 'GET':
        return render(request, 'site/pages/contact-us.html')
    validate_contact = ContactForm(request.POST)

    if validate_contact.is_valid():
        payload = {'secret': settings.CAPTCHA_SECRET_KEY, 'response':
                   request.POST.get('g-recaptcha-response'), 'remoteip':  request.META.get('REMOTE_ADDR')}
        r = requests.get(
            'https://www.google.com/recaptcha/api/siteverify', params=payload)
        if json.loads(r.text)['success']:

            if 'enquery_type' in request.POST.keys():
                    Contact.objects.create(
                        country=request.POST.get('country'),
                        enquery_type=request.POST.get('enquery_type')
                    )
            message = "<p>From: "+request.POST.get('full_name') + "</p><p>Email Id: "
            message += request.POST.get('email') + "</p>"
            if request.POST.get('phone'):
                message += "<p>Contact Number: "+request.POST.get('phone')+"</p>"

            if request.POST.get('country'):
                message += "<p>Country: "+request.POST.get('country')+"</p>"

            if request.POST.get('message'):
                message += "<p>Message: "+request.POST.get('message')+"</p>"

            if request.POST.get('enquery_type'):
                message += "<p><b>General Information:</b></p>"
                message += "<p>Enquery Type: "+request.POST.get('enquery_type')+"</p>"

            try:
                message += '<p>Ip Address: '+ str(get_client_ip(request)) + '</p>'
            except:
                pass

            try:
                message += '<p>This request is from <a href="'+ request.META['HTTP_REFERER'] +'">' + request.META['HTTP_REFERER'] +'</a></p>'
            except:
                pass

            sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD)

            contact_msg = sendgrid.Mail()
            contact_msg.set_subject("We received your message | MicroPyramid")
            message_reply = 'Hello ' + request.POST.get('full_name') + ',\n\n'
            message_reply = message_reply + 'Thank you for writing in.\n'
            message_reply = message_reply + \
                'We appreciate that you have taken the time to share your feedback with us! We will get back to you soon.\n\n'
            message_reply = message_reply + 'Regards\n'
            message_reply = message_reply + 'The MicroPyramid Team.'
            contact_msg.set_text(message_reply)
            contact_msg.set_from("hello@micropyramid.com")
            contact_msg.add_to(request.POST.get('email'))
            sg.send(contact_msg)

            sending_msg = sendgrid.Mail()
            sending_msg.set_subject("Service Request - Micropyramid")
            sending_msg.set_html(message)
            sending_msg.set_text('Service Request')
            sending_msg.set_from(request.POST.get('email'))
            sending_msg.add_to("hello@micropyramid.com")
            sg.send(sending_msg)

            request.session['thankyou'] = True
            data = {'error': False, 'response': 'Contact submitted successfully'}
            return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
        else:
            data = {'error': True, 'captcha_response': 'Please Choose Correct Captcha'}
            return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
    else:
        errors = {}
        data = {'error': True, 'errinfo': validate_contact.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') def subscribe(request):
    if request.method == 'GET':
        return render(request, 'site/pages/subscribe.html')
    validate_subscribe = SubscribeForm(request.POST)
    if validate_subscribe.is_valid():
        subscriber = Subscribers.objects.create(
            email=request.POST.get('email'))
        if str(request.POST.get('is_blog')) == 'True':
            if len(request.POST.get('is_category')) > 0:
                category = Category.objects.get(
                    id=request.POST.get('is_category'))
                subscriber.category = category
                create_contact_in_category.delay(
                    category.slug, request.POST.get('email'))
            else:
                create_contact_in_category.delay(
                    'blog', request.POST.get('email'))
            subscriber.blog_post = True
        else:
            create_contact_in_category.delay('site', request.POST.get('email'))
            subscriber.blog_post = False
        subscriber.save()
    else:
        errors = {}
        errors = dict((validate_subscribe.errors).items())
        data = {'error': True, 'errinfo': errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    data = {
        'error': False, 'response': 'Your email has been successfully subscribed.'}
    return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') def site_blog_home(request, **kwargs):
    page = 1
    if 'page' in request.GET.keys():
        try:
            if request.GET.get('page') and int(request.GET.get('page')):
                return redirect(reverse('site_blog_home', kwargs={'page_num': request.GET.get('page')}))
        except:
            return redirect(reverse('site_blog_home'))
    if 'page_num' in kwargs:
        try:
            page = int(kwargs['page_num'])
            if page == 1:
                return redirect(reverse('site_blog_home'))
        except:
            return redirect(reverse('site_blog_home'))
    items_per_page = 10

    posts = Post.objects.filter(status='P').order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    no_pages = int(math.ceil(float(posts.count()) / items_per_page))
    try:
        if int(page) < 0 or int(page) > (no_pages):
            page = 1
            return HttpResponseRedirect(reverse('site_blog_home'))
        else:
            page = int(page)
    except:
        page = 1

    blog_posts = posts[(page - 1) * items_per_page:page * items_per_page]

    c = {}
    c.update(csrf(request))
    prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count(
    page, no_pages)

    return render(request, 'site/blog/index.html', {'current_page': page, 'last_page': no_pages,
                                                    'posts': blog_posts, 'csrf_token': c['csrf_token'],
                                                    'prev_page': prev_page, 'previous_page': previous_page,
                                                    'aft_page': aft_page, 'after_page': after_page}) def blog_category(request, **kwargs):
    page = 1
    slug = kwargs['slug']

    if 'page' in request.GET.keys():
        if request.GET.get('page'):
            return redirect(reverse('blog_category', kwargs={'slug': slug, 'page_num': request.GET.get('page')}))
        else:
            return redirect(reverse('blog_category', kwargs={'slug': slug}))

    if 'page_num' in kwargs:
        page = int(kwargs['page_num'])

        if page == 1:
            return redirect(reverse('blog_category', kwargs={'slug': slug}))

    slug = slug.lower()
    category = get_object_or_404(Category, slug=slug)
    blog_posts = Post.objects.filter(category=category, status="P").order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))

    try:
        if int(page) < 0 or int(page) > (no_pages):
            page = 1
            return HttpResponseRedirect(reverse('blog_category', kwargs={'slug': slug}))
        else:
            page = int(page)
    except:
        page = 1

    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count(
    page, no_pages)

    return render(request, 'site/blog/index.html', {'current_page': page, 'category': category, 'last_page': no_pages,
                                                    'posts': blog_posts, 'csrf_token': c['csrf_token'], 'slug': slug,
                                                    'prev_page': prev_page, 'previous_page': previous_page,
                                                    'aft_page': aft_page, 'after_page': after_page}) def blog_tag(request, slug):
    tag = get_object_or_404(Tags, slug=slug)
    blog_posts = Post.objects.filter(tags__in=[tag], status="P").order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    if "page" in request.GET:
        if not request.GET.get('page').isdigit():
            raise Http404
        page = int(request.GET.get('page'))
    else:
        page = 1
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))
    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    return render(request, 'site/blog/index.html', {'current_page': page, 'tag': tag,
                                                    'last_page': no_pages, 'posts': blog_posts, 'csrf_token': c['csrf_token']}) @login_required
def admin_post_list(request):
    users = User.objects.all()
    blog_posts = Post.objects.all().order_by(
        '-created_on').select_related("user", "category").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    if request.method == "POST":
        if request.user.is_site_admin:
            blog_post = get_object_or_404(Post, id=request.POST.get("blog_id"))
            user = get_object_or_404(
                User, id=request.POST.get("change_author"))
            blog_post.user = user
            blog_post.save()
    return render(request, 'admin/blog/blog-posts.html', {'blog_posts': blog_posts, "users": users}) @login_required
def new_post(request):
    BlogSlugFormSet = inlineformset_factory(Post, Post_Slugs,
                                            can_delete=True, extra=3, fields=('slug', 'is_active'),
                                            formset=CustomBlogSlugInlineFormSet
                                            )
    if request.method == 'POST':
        blog_form = BlogpostForm(request.POST)
        blogslugs_formset = BlogSlugFormSet(request.POST)
        if blog_form.is_valid() and blogslugs_formset.is_valid():
            blog_post = blog_form.save(commit=False)
            blogslugs_formset = BlogSlugFormSet(
                request.POST, instance=blog_post)
            if blogslugs_formset.is_valid():
                blog_post.user = request.user
                if request.POST.get('meta_description'):
                    blog_post.meta_description = request.POST[
                        'meta_description']
                blog_post.status = 'D'
                if request.POST.get('status') == "P":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'P'
                        if not blog_post.published_on:
                            blog_post.published_on = datetime.datetime.now(
                            ).date()

                elif request.POST.get('status') == "T":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'T'

                elif request.POST.get('status') == "R":
                    blog_post.status = 'R'

                blog_post.save()
                blogslugs_formset.save()
                # If no slugs are specified, then create one using title.
                if not blog_post.slugs.all():
                    blog_post.create_blog_slug([slugify(blog_post.title)])
                blog_post.check_and_activate_slug()

                if request.POST.get('tags', ''):
                    tags = request.POST.get('tags')
                    tags = tags.split(',')
                    for tag in tags:
                        blog_tag = Tags.objects.filter(name=tag)
                        if blog_tag:
                            blog_tag = blog_tag[0]
                        else:
                            blog_tag = Tags.objects.create(name=tag)
                        blog_post.tags.add(blog_tag)

                sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD)
                sending_msg = sendgrid.Mail()
                sending_msg.set_subject("New blog post has been created")

                blog_url = 'https://www.micropyramid.com/blog/' + \
                    str(blog_post.slug) + '/'
                message = '<p>New blog post has been created by ' + str(request.user) + ' with the name ' + str(
                    blog_post.title) + ' in the category ' + str(blog_post.category.name) + '.</p>'

                sending_msg.set_html(message)
                sending_msg.set_text('New blog post has been created')
                sending_msg.set_from(request.user.email)
                sending_msg.add_to(
                    [user.email for user in User.objects.filter(is_admin=True)])
                sg.send(sending_msg)

                # cache._cache.flush_all()
                return redirect(reverse('admin_post_list'))
    else:
        blog_form = BlogpostForm()
        blogslugs_formset = BlogSlugFormSet(instance=Post())

    categories = Category.objects.all()
    c = {}
    c.update(csrf(request))
    return render(request, 'admin/blog/blog-new.html',
                  {'categories': categories, 'csrf_token': c['csrf_token'],
                   'blogslugs_formset': blogslugs_formset, 'blog_form': blog_form}
                  ) @login_required
def edit_blog_post(request, blog_slug):
    blog_post = get_object_or_404(Post, slugs__slug=blog_slug)
    active_slug = blog_post.slug
    old_blog_status = blog_post.status
    if active_slug != blog_slug:
        return redirect(reverse('edit_blog_post',
                                kwargs={'blog_slug': active_slug})
                        )
    if not blog_post.is_editable_by(request.user):
        return render_to_response('admin/accessdenied.html')

    BlogSlugFormSet = inlineformset_factory(Post, Post_Slugs,
                                            can_delete=True, extra=3, fields=('slug', 'is_active'),
                                            formset=CustomBlogSlugInlineFormSet
                                            )
    if request.method == 'POST':
        blog_form = BlogpostForm(request.POST, instance=blog_post)
        blogslugs_formset = BlogSlugFormSet(request.POST, instance=blog_post)
        if blog_form.is_valid() and blogslugs_formset.is_valid():
            blog_post = blog_form.save(commit=False)
            if blogslugs_formset.is_valid():
                blog_post.status = old_blog_status
                blog_post.meta_description = request.POST.get(
                    'meta_description')
                if request.POST.get('status') == "P":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'P'
                elif request.POST.get('status') == "T":
                    if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser:
                        blog_post.status = 'T'
                elif (request.POST.get('status') == "R" or
                      request.POST.get('status') == "D"
                      ):
                    blog_post.status = request.POST.get('status')
                else:
                    pass

                blog_post.save()
                blogslugs_formset.save()
                # If no slugs are specified, then create one using title.
                if not blog_post.slugs.all():
                    blog_post.create_blog_slug([slugify(blog_post.title)])
                blog_post.check_and_activate_slug()

                blog_post.tags.clear()
                if request.POST.get('tags', ''):
                    for tag in blog_post.tags.all():
                        blog_post.tags.remove(tag)
                    tags = request.POST.get('tags')
                    tags = tags.split(',')
                    for tag in tags:
                        blog_tag = Tags.objects.filter(name=tag)
                        if blog_tag:
                            blog_tag = blog_tag[0]
                        else:
                            blog_tag = Tags.objects.create(name=tag)

                        blog_post.tags.add(blog_tag)
                # cache._cache.flush_all()
                return redirect(reverse('admin_post_list'))
    else:
        blog_form = BlogpostForm(instance=blog_post)
        blogslugs_formset = BlogSlugFormSet(instance=blog_post)

    categories = Category.objects.all()
    c = {}
    c.update(csrf(request))
    return render(request, 'admin/blog/blog-edit.html', {'blog_post': blog_post,
                                                         'categories': categories, 'csrf_token': c['csrf_token'],
                                                         'blogslugs_formset': blogslugs_formset, 'blog_form': blog_form}
                  ) @login_required
def admin_category_list(request):
    blog_categories = Category.objects.all().order_by('id')
    return render(request, 'admin/blog/blog-category-list.html', {'blog_categories': blog_categories}) @login_required
def new_blog_category(request):
    if request.method == 'POST':
        validate_blogcategory = BlogCategoryForm(request.POST)
        if validate_blogcategory.is_valid():
            validate_blogcategory.save()

            # cache._cache.flush_all()
            data = {'error': False, 'response': 'Blog category created'}
        else:
            data = {'error': True, 'response': validate_blogcategory.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    if request.user.is_superuser:
        c = {}
        c.update(csrf(request))
        return render(request, 'admin/blog/blog-category.html', {'csrf_token': c['csrf_token']})
    else:
        return render_to_response('admin/accessdenied.html') def blog_category(request, **kwargs):
    page = 1
    slug = kwargs['slug']

    if 'page' in request.GET.keys():
        if request.GET.get('page'):
            return redirect(reverse('blog_category', kwargs={'slug': slug, 'page_num': request.GET.get('page')}))
        else:
            return redirect(reverse('blog_category', kwargs={'slug': slug}))

    if 'page_num' in kwargs:
        page = int(kwargs['page_num'])

        if page == 1:
            return redirect(reverse('blog_category', kwargs={'slug': slug}))

    slug = slug.lower()
    category = get_object_or_404(Category, slug=slug)
    blog_posts = Post.objects.filter(category=category, status="P").order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))

    try:
        if int(page) < 0 or int(page) > (no_pages):
            page = 1
            return HttpResponseRedirect(reverse('blog_category', kwargs={'slug': slug}))
        else:
            page = int(page)
    except:
        page = 1

    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count(
    page, no_pages)

    return render(request, 'site/blog/index.html', {'current_page': page, 'category': category, 'last_page': no_pages,
                                                    'posts': blog_posts, 'csrf_token': c['csrf_token'], 'slug': slug,
                                                    'prev_page': prev_page, 'previous_page': previous_page,
                                                    'aft_page': aft_page, 'after_page': after_page}) def blog_article(request, slug):
    if request.path != request.path.lower():
        return redirect(request.path.lower(), permanent=True)

    blog_post = get_object_or_404(Post, slugs__slug=slug)
    active_slug = blog_post.slug
    if active_slug != slug:
        return redirect(reverse('blog_article',
                                kwargs={'slug': active_slug})
                        )
    if not blog_post.status == 'P':
        if not request.user.is_authenticated():
            raise Http404

    all_blog_posts = list(
        Post.objects.filter(status='P').order_by('-published_on'))
    prev_url = ''
    next_url = ''
    for post in all_blog_posts:
        if str(slug) == str(post.slug):
            try:
                current_index = all_blog_posts.index(post)
                next_que = all_blog_posts[current_index + 1]
                next_url = '/blog/' + str(next_que.slug) + '/'
            except:
                next_url = ''
            try:
                current_index = all_blog_posts.index(post)
                prev_que = all_blog_posts[current_index - 1]
                if current_index == 0:
                    prev_url = ''
                else:
                    prev_url = '/blog/' + str(prev_que.slug) + '/'
            except:
                prev_url = ''
            break
    related_posts = Post.objects.filter(
        category=blog_post.category, status='P').exclude(id=blog_post.id).order_by('?')[:3]
    minified_url = ''
    if 'HTTP_HOST' in request.META.keys():
        try:
            minified_url = google_mini('https://' + request.META['HTTP_HOST'] + reverse(
                'blog_article', kwargs={'slug': slug}), settings.GGL_URL_API_KEY)
        except:
            minified_url = 'https://' + \
                request.META[
                    'HTTP_HOST'] + reverse('blog_article', kwargs={'slug': slug})
    c = {}
    c.update(csrf(request))
    return render(request, 'site/blog/article.html', {'csrf_token': c['csrf_token'], 'related_posts': related_posts,
                                                      'post': blog_post, 'minified_url': minified_url, 'prev_url': prev_url, 'next_url': next_url}) def archive_posts(request, year, month):
    blog_posts = Post.objects.filter(status="P", published_on__year=year, published_on__month=month).order_by(
        '-published_on').select_related("user").prefetch_related(
        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),
                 to_attr="active_slugs"
                 )
    )
    items_per_page = 6
    no_pages = int(math.ceil(float(blog_posts.count()) / items_per_page))

    try:
        if int(request.GET.get('page')) < 0 or int(request.GET.get('page')) > (no_pages):
            page = 1
            return HttpResponseRedirect(reverse('archive_posts'), kwargs={'year': blog_posts[0].published_on.year, 'month': blog_posts[0].published_on.month})
        else:
            page = int(request.GET.get('page'))
    except:
        page = 1

    blog_posts = blog_posts[(page - 1) * items_per_page:page * items_per_page]
    if not blog_posts:
        raise Http404
    c = {}
    c.update(csrf(request))
    prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count(
    page, no_pages)

    return render(request, 'site/blog/index.html', {'current_page': page, 'year': year, 'month': month, 'last_page': no_pages,
                                                    'posts': blog_posts, 'csrf_token': c['csrf_token'],
                                                    'prev_page': prev_page, 'previous_page': previous_page,
                                                    'aft_page': aft_page, 'after_page': after_page}) @login_required
def delete_category(request, category_slug):
    category = get_object_or_404(Category, slug=category_slug)
    if request.user.is_superuser:
        category.delete()

        # cache._cache.flush_all()
        return HttpResponseRedirect('/blog/category-list/')
    else:
        return render_to_response('admin/accessdenied.html') def empty(request):
    return render(request, 'site/empty.html') @login_required
def edit_category(request, category_slug):
    blog_category = get_object_or_404(Category, slug=category_slug)
    if request.method == 'POST':
        validate_blogcategory = BlogCategoryForm(
            request.POST, instance=blog_category)
        if validate_blogcategory.is_valid():
            validate_blogcategory.save()

            # cache._cache.flush_all()
            data = {'error': False, 'response': 'Blog category updated'}
        else:
            data = {'error': True, 'response': validate_blogcategory.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    if request.user.is_superuser:
        c = {}
        c.update(csrf(request))
        return render(request, 'admin/blog/blog-category-edit.html', {'blog_category': blog_category, 'csrf_token': c['csrf_token']})
    else:
        return render_to_response('admin/accessdenied.html') @login_required
def change_category_status(request, category_slug):
    category = get_object_or_404(Category, slug=category_slug)
    if category.is_display:
        category.is_display = False
    else:
        category.is_display = True
    category.save()
    return HttpResponseRedirect('/blog/category-list/') def thankyou_page(request):
    if 'thankyou' in request.session.keys() and request.session['thankyou'] == True:
        return render(request, 'site/pages/thanks.html')
    return HttpResponseRedirect('/') def site_page(request, slug):
    # pages_slugs = ['web-development', 'web-design', 'testing', 'crm', 'server-maintenance']
    # if slug in pages_slugs:
    #     return render(request, 'site/pages/' + slug + '.html')
    # return render(request, '404.html', status=404)
    if 'country' in request.session.keys() and request.session['country']:
        country_code = request.session['country']
    else:
        country_code = request.COUNTRY_CODE
    if '/us/' in request.path and country_code =='us':
        return redirect('/'+request.path.split('/us/')[-1], permanent=True)

    country = Country.objects.filter(code=slug)
    if country:
        if country[0].code == settings.COUNTRY_CODE:
            return HttpResponseRedirect('/')
        return render(request, 'site/index.html', {
            'google_analytics_code': settings.GOOGLE_ANALYTICS_CODE})

    page = Page.objects.filter(slug=slug, country__code=country_code, is_active=True).first()
    if not page:
        page = Page.objects.filter(slug=slug).first()
        if page:
            page = Page.objects.filter(title__iexact=page.title, country__code=country_code, is_active=True).first()
            if page.country.code == 'us':
                return redirect('/' + page.slug +'/', permanent=True)
            else:
                return redirect('/' + page.country.code + '/' + page.slug +'/', permanent=True)
    if not page:
        page = Page.objects.filter(slug=slug, is_default=True, is_active=True)
    if page:
        posts = Post.objects.filter(status='P').order_by('-published_on')
        if page.category.all():
            posts = Post.objects.filter(category__in=page.category.all(), status='P').order_by('-published_on')
        return render(request, 'site/page.html', {'page': page, 'posts': posts})
    else:
        return render(request, '404.html', status=404) def set_country(request):

    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax()) and
            not is_safe_url(next, request.get_host())):
        next = request.META.get('HTTP_REFERER')
        if next:
            next = unquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(next, request.get_host()):
            next = '/'
        if request.POST.get('country'):
            path = request.META.get('HTTP_REFERER').replace(request.scheme+'://' + request.get_host(), '')

            country_code = get_country_code_from_path(path)
            if country_code:
                path = request.META.get('HTTP_REFERER').replace(request.scheme+'://' + request.get_host(), '').replace('/'+country_code, '')
            if request.POST.get('country') == settings.COUNTRY_CODE:
                next = path
            else:
                next = '/' + request.POST.get('country') + path
    response = HttpResponseRedirect(next) if next else HttpResponse(status=204)
    if request.method == 'POST':
        country_code = request.POST.get('country')
        if country_code:
            request.session['country'] = country_code
            if hasattr(request, 'session'):
                request.session['_country'] = country_code
            else:
                response.set_cookie(
                    settings.COUNTRY_COOKIE_NAME, country_code,
                    max_age=settings.COUNTRY_COOKIE_AGE,
                    path=settings.COUNTRY_COOKIE_PATH,
                    domain=settings.COUNTRY_COOKIE_DOMAIN,
                )
    return response def rss(request):

    xml = '''<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
                <channel>
                <atom:link href="https://micropyramid.com/rss.xml" rel="self" type="application/rss+xml" />
                <title>MicroPyramid | Web Development | Mobile App Development</title>
                <description>MicroPyramid python development company.
                  MicroPyramid python development company.
                  Our ambit of service encompasses and is as vivid as e-commerce,
                  web applications, news portals, community and job portals design &amp;
                  development. We work on Python, Django, nodejs, Mongodb, Responsive web design, CSS3,
                  JavaScript, Jquery, Angularjs, Amazon web services</description>
                <link>https://micropyramid.com</link>
                <category domain="micropyramid.com">
                MicroPyramid | Web Development | Mobile App Development
                </category>
                <copyright>Copyright 2014 MicroPyramid</copyright>
                <language>en-us</language>
                <image>
                <url>https://micropyramid.com/static/site/images/logo.png</url>
                <title>MicroPyramid | Web Development | Mobile App Development</title>
                <link>https://micropyramid.com</link>
                <description>MicroPyramid python development company.
                 Our ambit of service encompasses and is as vivid as e-commerce,
                 web applications, news portals, community and job portals design &amp;
                  development. We work on Python, Django, Mongodb, Responsive web design, CSS3,
                   JavaScript, Jquery, Angularjs, Amazon web services, iphone, ruby on rails</description>
                </image>
                    '''
    if 'category' in request.GET.keys():
        posts = Post.objects.filter(status='P', category__name__icontains=request.GET.get('category')).order_by('-updated_on')[:10]
    else:
        posts = Post.objects.filter(status='P').order_by('-updated_on')[:10]
    for post in posts:

        nowtuple = post.updated_on.timetuple()
        nowtimestamp = time.mktime(nowtuple)
        published_date = utils.formatdate(nowtimestamp)

        xml = xml + '<item><title><![CDATA[' + post.title + ']]></title>'
        xml = xml + '<description><![CDATA[' + post.content + ']]></description>'
        xml = xml + '<link>https://micropyramid.com/blog/' + post.slug + '/</link>'
        xml = xml + '<category domain="micropyramid.com"><![CDATA[' + post.category.name + ']]></category>'
        xml = xml + '<comments>https://micropyramid.com/blog/' + post.slug + '/</comments>'
        xml = xml + '<pubDate>' + published_date + '</pubDate>'
        xml = xml + '<guid>https://micropyramid.com/blog/' + post.slug + '/</guid></item>'

    xml = xml + '</channel></rss>'

    return HttpResponse(xml, content_type="text/xml") def blog_rss(request):

    xml = '''<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
                <channel>
                <atom:link href="https://micropyramid.com/blog.rss" rel="self" type="application/rss+xml" />
                <title>MicroPyramid | Web Development | Mobile App Development</title>
                <description>MicroPyramid python development company.
                 MicroPyramid python development company.
                  Our ambit of service encompasses and is as vivid as e-commerce,
                  web applications, news portals, community and job portals design &amp;
                  development. We work on Python, Django, nodejs, Mongodb, Responsive web design, CSS3,
                  JavaScript, Jquery, Angularjs, Amazon web services</description>
                <link>https://micropyramid.com</link>
                <category domain="micropyramid.com">
                MicroPyramid | Web Development | Mobile App Development
                </category>
                <copyright>Copyright 2014 MicroPyramid</copyright>
                <language>en-us</language>
                <image>
                <url>https://micropyramid.com/static/site/images/logo.png</url>
                <title>MicroPyramid | Web Development | Mobile App Development</title>
                <link>https://micropyramid.com</link>
                <description>MicroPyramid python development company.
                 Our ambit of service encompasses and is as vivid as e-commerce,
                 web applications, news portals, community and job portals design &amp;
                  development. We work on Python, Django, Mongodb, Responsive web design, CSS3,
                   JavaScript, Jquery, Angularjs, Amazon web services, iphone, ruby on rails</description>
                </image>
                    '''
    if 'category' in request.GET.keys():
        posts = Post.objects.filter(status='P', category__name__icontains=request.GET.get('category')).order_by('-published_on')[:10]
    else:
        posts = Post.objects.filter(status='P').order_by('-published_on')[:10]

    for post in posts:

        nowtuple = post.updated_on.timetuple()
        nowtimestamp = time.mktime(nowtuple)
        published_date = utils.formatdate(nowtimestamp)

        xml = xml + '<item><title><![CDATA[' + post.title + ']]></title>'
        xml = xml + '<description><![CDATA[' + post.excerpt + ']]></description>'
        xml = xml + '<link>https://micropyramid.com/blog/' + post.slug + '/</link>'
        xml = xml + '<category domain="micropyramid.com"><![CDATA[' + post.category.name + ']]></category>'
        xml = xml + '<comments>https://micropyramid.com/blog/' + post.slug + '/</comments>'
        xml = xml + '<pubDate>' + published_date + '</pubDate>'
        xml = xml + '<guid>https://micropyramid.com/blog/' + post.slug + '/</guid></item>'

    xml = xml + '</channel></rss>'

    return HttpResponse(xml, content_type="text/xml") def sitemap_xml(request, **kwargs):
    country = request.COUNTRY_CODE
    if kwargs:
        country = kwargs['country_name']

    # pages, blog categories, blog posts

    xml = '''<?xml version="1.0" encoding="UTF-8"?>
             <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
             http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'''

    if country == 'us':
        xml = xml + '<url><loc>https://micropyramid.com/</loc></url>'
    else:
        xml = xml + '<url><loc>https://micropyramid.com/' + str(country) + '/</loc></url>'

    if country == 'us':
        countries = Country.objects.filter().exclude(code='us')
        for each in countries:
            xml = xml + '<url><loc>https://micropyramid.com/' + str(each.code) + '/sitemap.xml</loc></url>'

    menus = Menu.objects.filter(status="on", url__isnull=False, country__code=country).exclude(url__in=['/', 'blog'])
    for menu in menus:
        if menu.url and str(menu.url) != 'none':
            if country == 'us':
                xml = xml + '<url><loc>https://micropyramid.com/' + menu.url + '/</loc></url>'
            else:
                xml = xml + '<url><loc>https://micropyramid.com/' + str(country) + '/' + menu.url + '/</loc></url>'
    categories = Category.objects.filter(is_display=True)
    for category in categories:
        if category.blog_posts.filter(status='P').exists():
            xml = xml + '<url><loc>https://micropyramid.com/blog/category/' + category.slug + '/'
            xml = xml + '</loc>/</url>'

    posts = Post.objects.filter(status="P").order_by('-published_on')
    for post in posts:
        xml = xml + '<url><loc>https://micropyramid.com/blog/' + post.slug + '/</loc></url>'

    no_pages = int(math.ceil(float(posts.count()) / 10))
    for page_num in range(1, no_pages+1):
        xml = xml + '<url><loc>https://micropyramid.com/blog/' + str(page_num) + '/</loc></url>'

    xml = xml + '<url><loc>https://micropyramid.com/sitemap/</loc></url>'
    xml = xml + '</urlset>'

    return HttpResponse(xml, content_type="text/xml") def facebook_rss(request):
    xml = '''<rss version="2.0"
             xmlns:content="http://purl.org/rss/1.0/modules/content/">
            <channel>
            <title>Django and Python Web Development | Application Development Services India – MicroPyramid</title>
            <link>https://micropyramid.com</link>
            <description>
              MicroPyramid python development company.
              Our ambit of service encompasses and is as vivid as e-commerce,
              web applications, news portals, community and job portals design &amp;
              development. We work on Python, Django, nodejs, Mongodb, Responsive web design, CSS3,
              JavaScript, Jquery, Angularjs, Amazon web services
            </description>
            <language>en-us</language>
            <lastBuildDate>2016-05-17T04:44:16Z</lastBuildDate>'''
    posts = Post.objects.filter(status='P').order_by('-published_on')[:50]

    for post in posts:
        if post.published_on:
            nowtuple = post.published_on.timetuple()
        else:
            nowtuple = post.updated_on.timetuple()
        nowtimestamp = time.mktime(nowtuple)
        published_date = utils.formatdate(nowtimestamp)
        xml = xml + '<item><title>' + post.title + '</title>'
        xml = xml + '<link>https://micropyramid.com/blog/' + post.slug + '/</link>'
        xml = xml + '<guid>' + str(post.slug) + '</guid>'
        xml = xml + '<pubDate>' + published_date + '</pubDate>'
        xml = xml + '<author>' + post.user.get_full_name() + '</author>'
        xml = xml + '<description>' + post.title + '</description>'
        xml = xml + '<content:encoded><![CDATA[<!doctype html><html lang="en" prefix="op: http://media.facebook.com/op#">'
        xml = xml + '<head><meta charset="utf-8">'
        xml = xml + '<link rel="canonical" href="https://micropyramid.com/blog/' + post.slug + '/">'
        xml = xml + '<meta property="op:markup_version" content="v1.0">'
        xml = xml + '</head><body><article>'
        xml = xml + '<header>'
        xml = xml + str(post.title) + ' - Micropyramid'
        xml = xml + '</header>'
        xml = xml + '<p>' + post.excerpt + '</p>'
        xml = xml + '</article></body></html>]]>'
        xml = xml + '</content:encoded></item>'

    xml = xml + '</channel></rss>'

    return HttpResponse(xml, content_type="text/xml") def index(request):
    return render(request, 'site/index.html', {
        'google_analytics_code': settings.GOOGLE_ANALYTICS_CODE}) @login_required(login_url='/')
def tools(request):
    return render(request, 'site/tools/index.html') @login_required(login_url='/')
def url_checker_tool(request):
    if request.method == "POST":
        redirects_count = []
        urls = []
        responses = []

        if request.POST.get('urls'):
            urls = request.POST.get('urls').split('\r\n')
        if request.FILES.get('file'):
            for line in request.FILES.get('file'):
                urls.append(line.rstrip('\r\n'))

        for url in urls:
            if url:
                try:
                    response = requests.head(url, allow_redirects=True)
                except Exception:
                    response = {'url': url, 'status_code': 'Invalid Url'}
                responses.append(response)
                try:
                    response_history = len(response.history)
                except Exception:
                    response_history = 0
                redirects_count.append(response_history)

        max_redirects = max(redirects_count) if redirects_count else 1
        return render(request, 'site/tools/url_checker.html', {'responses': responses, 'max_redirects': max_redirects})

    return render(request, 'site/tools/url_checker.html') @login_required(login_url='/')
def s3_objects_set_metadata(request):
    if request.method == "POST":
        errors = {}
        if not request.POST.get('expiry_time').isnumeric():
            errors['expiry_time'] = "Expiry Time must be in number of days."

        if not request.POST.get('max_age').isnumeric():
            errors['max_age'] = "Invalid max-age value. Max Age must be in seconds."

        # Make an S3 Connection
        conn = S3Connection(request.POST.get('access_key'), request.POST.get('secret_key'))

        # Get a bucket from S3 or None if the bucket does not exist
        bucket = conn.lookup(request.POST.get('bucket_name'))
        if not bucket:
            errors['bucket_name'] = "NoSuchBucket - The specified bucket does not exist."

        if errors:
            return HttpResponse(json.dumps({"error": True, "errors": errors}), content_type='application/json; charset=utf-8')

        for x in bucket.list():
            mime_type = MimeTypes().guess_type(x.key)
            expires = datetime.utcnow() + timedelta(days=request.POST.get('expiry_time'))
            expiration_period = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")

            if mime_type[0] is not None:
                x.set_metadata('Cache-Control', 'max-age = ' + request.POST.get('max_age'))
                x.set_metadata('Expires', expiration_period)
                x.set_metadata('Content-Type', mime_type[0])

                x.copy(
                    x.bucket.name,
                    x.name,
                    x.metadata,
                    preserve_acl=True
                )

        return HttpResponse(json.dumps({"error": False}),
                            content_type='application/json; charset=utf-8')

    return render(request, 'site/tools/s3_objects_set_metadata.html') def sitemap(request, **kwargs):
    if request.GET.get('page'):
        url = request.path + request.GET.get('page') + '/'
        return redirect(url, permanent=False)
    page = 1
    country = request.COUNTRY_CODE
    if 'country_name' in kwargs.keys():
        country = kwargs['country_name']
        request.session['country'] = country
        if hasattr(request, 'session'):
            request.session['_country'] = country

    if 'page_num' in kwargs.keys():
        page = int(kwargs['page_num'])
        if page == 1:
            return redirect('/sitemap/')

    categories = Category.objects.all()
    blog_posts = Post.objects.filter(status='P').order_by('-published_on')
    countries = Country.objects.filter()
    services = Page.objects.filter(is_active='True', country__code=country).order_by('id')
    sitemap_links = list(chain(categories, services, blog_posts))

    object_list = Paginator(sitemap_links, 100)
    try:
        sitemap_links = object_list.page(page)
    except PageNotAnInteger:
        sitemap_links = object_list.page(1)
    except EmptyPage:
        sitemap_links = object_list.page(object_list.num_pages)
    return render(request, 'site/sitemap.html',  {'sitemap_links': sitemap_links, 'country': country, 'countries': countries}) def books(request, path):
    if path is None or path == '':
        documents_file = open(os.path.join(
            settings.BASE_DIR + '/books/', 'books.yml'), 'r')
        data = yaml.load(documents_file)
        books = []
        if data.get("documents") and data.get("documents") != None:
            if request.user.is_authenticated():
                books = [
                    book for position, book in sorted(
                        data['documents'].items())]
            else:
                books = [
                    book for position, book in sorted(
                        data['documents'].items()
                    ) if book.get("visibilty").lower() == "public"]
        return render(request, "site/books.html", {"books": books})
        # return render(request, 'html/index.html')
    else:
        # if path.endswith('html'):
        #     return render(request, 'html/' + path)
        # else:
        return serve(
            request, path,
            document_root=settings.BASE_DIR + '/books/templates/html/') def oss(request):
    return render(request, 'site/oss/index.html') def servicee(request):
    return render(request, 'site/empty.html') def country_patterns(*urls, prefix_default_country=True):
    """
    Adds the country code prefix to every URL pattern within this
    function. This may only be used in the root URLconf, not in an included
    URLconf.
    """
    if not settings.USE_COUNTRY_URL:
        return list(urls)
    return [CountryRegexURLResolver(list(urls), prefix_default_country=prefix_default_country)]
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from micro_blog.views import (contact, subscribe, site_blog_home, blog_category, blog_tag, admin_post_list, new_post, edit_blog_post,
                              admin_category_list, new_blog_category, blog_category,
                              blog_article, archive_posts, delete_category, empty,
                              edit_category, change_category_status, thankyou_page)
from pages.views import site_page, set_country
from microsite_front.xml import rss, blog_rss, sitemap_xml, facebook_rss
from microsite_front.views import index, tools, url_checker_tool, s3_objects_set_metadata, sitemap, books, oss, servicee
from search.views import autocomplete
from django.views.static import serve
from .country_urls import country_patterns
from django.utils.translation import ugettext_lazy as _
from django.conf.urls.static import static
    from django.views.static import serve
import microsite_front
    import debug_toolbar





urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'_static/(?P<path>.*)$', serve, {'document_root': settings.BASE_DIR + '/books/templates/html/_static/'}),
    url(r'_sources/(?P<path>.*)$', serve, {'document_root': settings.BASE_DIR + '/books/templates/html/_sources/'}),
    url(r'^$', index),
    url(r'^books/(?P<path>.*)$', books),
    url(r'^tools/$', tools, name='tools'),
    url(r'^tools/url-checker/$', url_checker_tool, name='url_checker_tool'),
    url(r'^tools/set-meta-data-for-S3-objects/$', s3_objects_set_metadata, name='s3_objects_set_metadata'),

    url(r'^subscribe/$', subscribe),
    # url(r'^servicee/$', servicee),

    url(r'^set_country/$', set_country, name="set_country"),

    url(r'^forum/', include('django_simple_forum.urls', namespace="django_simple_forum")),

    url(r'^portal/', include('micro_admin.urls', namespace='micro_admin')),
    url(r'^contact-india/$', contact, name="contact_india"),

    url(r'^thank-you/$', thankyou_page, name="thankyou_page"),

    url(r'^contact-usa/$', contact, name="contact_usa"),
    url(r'^contact-aus/$', contact, name="contact_usa"),
    url(r'^contact-uk/$', contact, name="contact_usa"),
    url(r'^contact-uae/$', contact, name="contact_uae"),


    url(r'^blog/list/$', admin_post_list, name='admin_post_list'),
    url(r'^blog/new-post/$', new_post, name='new_post'),
    url(r'^blog/edit-post/(?P<blog_slug>[-\w]+)/$', edit_blog_post, name='edit_blog_post'),
    url(r'^blog/category-list/$', admin_category_list, name='admin_category_list'),
    url(r'^blog/new-category/$', new_blog_category, name='new_blog_category'),

    url(r'^blog/(?P<page_num>[0-9]+)/$', site_blog_home, name="site_blog_home"),

    url(r'^blog/(?P<slug>[-\w]+)/$', blog_article, name='blog_article'),
    url(r'^blog/(?P<year>\w{0,})/(?P<month>w{0,})/$', archive_posts),

    url(r'^blog/edit-category/(?P<category_slug>[-\w]+)/$', edit_category, name='edit_blog_category'),
    url(r'^blog/delete-category/(?P<category_slug>[-\w]+)/$', delete_category, name='delete_blog_category'),
    url(r'^blog/category/status/(?P<category_slug>[-\w]+)/$', change_category_status, name='change_category_status'),

    url(r'^blog/category/(?P<slug>[-\w]+)/$', blog_category, name="blog_category"),
    url(r'^blog/category/(?P<slug>[-\w]+)/(?P<page_num>[-\w]+)/$', blog_category, name="blog_category"),

    url(r'^blog/$', site_blog_home, name="site_blog_home"),

    url(r'^portal/content/', include('pages.urls', namespace='pages')),
    url(r'^sitemap.xml$', sitemap_xml, name="sitemap_xml"),
    # url(r'^sitemap-(?P<country_name>[-\w]+).xml/$', sitemap_xml, name="sitemap_xml"),

    url(r'^sitemap/$', sitemap, name="sitemap"),
    url(r'^empty/$', empty),
    url(r'^sitemap-(?P<country_name>[-\w]+)/$', sitemap, name="sitemap"),
    url(r'^sitemap-(?P<country_name>[-\w]+)/(?P<page_num>[-\w]+)/$', sitemap, name="sitemap"),
    url(r'^sitemap/(?P<page_num>[-\w]+)/$', sitemap, name="sitemap"),

    url(r'^(?P<slug>[-\w]+)/$', site_page),
    url(r'^facebook.rss$', facebook_rss),
    url(r'^rss.xml$', rss),

    url(r'^blog.rss$', blog_rss),