# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
__Author__ = 'Ahmadreza Parsaei'
__License__ = "GPL 2.0 http://www.gnu.org/licenses/gpl-2.0.html"
import urllib.parse
from urllib.parse import quote
import urllib.parse
from urllib.request import Request
from django.http import HttpResponse
from django.shortcuts import redirect
#rom suds.client import Client
from django.http import HttpResponseRedirect
import base64
from kavenegar import *
from .models import *
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader
from django.http import HttpResponse
from django import template
#rom rest_framework.views import APIView
#rom rest_framework.response import Response
#rom rest_framework import status
from json import JSONEncoder
from datetime import datetime
from django.http import JsonResponse
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.hashers import check_password
from django.views.generic import TemplateView
from django.conf import settings
from django.db.models.functions import Lower
from django.utils import timezone
from collections import OrderedDict
from django.forms.utils import ErrorList
from django.http import HttpResponse
from .forms import LoginForm, SignUpForm,verifycode,usernameform
import requests
from bs4 import BeautifulSoup
import ghasedak
import random
import string
from django.views.decorators.csrf import csrf_protect 
from django.contrib.sessions.models import Session
from phonenumber_field.phonenumber import PhoneNumber

def get_phone(request):
    context={}
    course_1 = get_object_or_404(course,course_id=20)
    all_student=student.objects.all()
    for item in all_student:
        if course_1 in item.course.all():
            with open("course13_list2.txt", "a",encoding="utf8") as file:
                file.write(f"{str(item.phone).strip()},{str(item.name).strip()}")
                file.write("\n")
                file.close()
    html_template = loader.get_template( 'index.html' )
    context['segment'] = "index.html" 
    return HttpResponse(html_template.render(context, request))


@csrf_exempt
def my_view(request):
	jalali_join = datetime2jalali(request.user.date_joined).strftime('%y/%m/%d _ %H:%M:%S')

def addstu(request):
    file1 = open('10-4-05-half.csv', 'r', encoding='utf-8')
    Lines = file1.readlines()
    
    count = 0
    my_cousre = get_object_or_404(course,course_id=20)
    my_cousre1 = get_object_or_404(course,course_id=1) # bastani
    my_cousre13 = get_object_or_404(course,course_id=13) # sosis kalbas
    my_cousre15 = get_object_or_404(course,course_id=15) # nime amade
    for line in Lines:
        
        count += 1
        line = line.strip()
        list=line.split(",")
        my_phone = "+98"+list[2]
        username=list[0] + list [1]
        if student.objects.filter(phone=my_phone).exists():
            this_student = get_object_or_404(student,phone=my_phone)
            this_student.course.add(my_cousre1)
            this_student.course.add(my_cousre15)
            this_student.save()
        else:
            my_name = list[0] +" "+ list [1]
            this_student = student.objects.create(name=my_name,phone=my_phone)
            this_student.course.add(my_cousre1)
            this_student.course.add(my_cousre15)
            this_student.save()
    context={}
    dore_id=1
    this_dore = get_object_or_404(course,id=dore_id)
    my_videos = videos.objects.filter(dore=this_dore).order_by('video_id')
    context['videos']=my_videos
    context['course']=this_dore
    html_template = loader.get_template( 'shop.html' )
    context['segment'] = "shop.html" 
    
    return HttpResponse(html_template.render(context, request))


def addvideo(request):
    count = 0
    my_video = videos.objects.all()
    for item in my_video:
        if item.player_url != "none":
            item.active = True
            item.save()
    context={}
    dore_id=1
    this_dore = get_object_or_404(course,id=dore_id)
    my_videos = videos.objects.filter(dore=this_dore).order_by('video_id')
    context['videos']=my_videos
    context['course']=this_dore
    html_template = loader.get_template( 'shop.html' )
    context['segment'] = "shop.html" 
    
    return HttpResponse(html_template.render(context, request))



@csrf_exempt
def index(request):
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    my_course = course.objects.filter(hide_in_index=False)
    context['course']=my_course
    html_template = loader.get_template( 'index.html' )
    context['segment'] = "index.html" 
    return HttpResponse(html_template.render(context, request))
    
def all_course(request):
    
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    my_course = course.objects.filter(hide_in_index=False)
    context['course']=my_course

    html_template = loader.get_template( 'all_course.html' )
    context['segment'] = "all_course.html" 
    return HttpResponse(html_template.render(context, request))
def pages(request):
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    try:
        
        load_template      = request.path.split('/')[-1]
        context['segment'] = load_template
        
        html_template = loader.get_template( load_template )
        return HttpResponse(html_template.render(context, request))
        
    except template.TemplateDoesNotExist:

        html_template = loader.get_template( 'page-404.html' )
        return HttpResponse(html_template.render(context, request))

    except:
    
        html_template = loader.get_template( 'page-500.html' )
        return HttpResponse(html_template.render(context, request))

def sign_up(request):
    form = SignUpForm
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
  
    msg     = None
    success = False
    print(request.POST)
    
    
    if request.method == "POST":
        form = SignUpForm(request.POST)
        
        
        if form.is_valid():
            
            name = str(form.cleaned_data.get("username"))
            username=urllib.parse.unquote(name)
            phone = str(form.cleaned_data.get("phone"))
            print(phone)
            num="0123456789"
            def get_random_string(length):
                result_str = ''.join(random.choice(num)for i in range(length))
                return result_str

            rand = get_random_string(4)
            msg     = 'User created - please <a href="/login">login</a>.'
            success = True
            url = 'https://panel.spotplayer.ir/license/edit/'
            myobj = {
                "course": ["60be917d6751d64c81631d80"],
                "name": username,
                "watermark": {"texts": [{"text": phone}]}
            }
            headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
            url = "https://api.ghasedak.me/v2/verification/send/simple"
            payload = "receptor="+str(phone)+"&template=foodfaast&type=1&param1="+str(rand)

            headers = {
            'content-type': "application/x-www-form-urlencoded",
            'apikey': "0fb39b9c0172a3399f83f2e068abbf9b72bab7bab038ccd955f768e3348a7b15",
            'cache-control': "no-cache",
            }

            response = requests.request("POST", url, data=payload, headers=headers)
            
            sample_string = str(rand)
            sample_string_bytes = sample_string.encode("ascii")
            
            base64_bytes = base64.b64encode(sample_string_bytes)
            my_key = base64_bytes.decode("ascii")
           
            return redirect(verify_login,my_key=my_key,phone=phone,username=username)
        else:
            msg = 'Error validating the form' 
        
    else:
        form = SignUpForm()

    html_template = loader.get_template( 'register.html' )
    return render(request, "register.html", {"form": form, "msg" : msg, "success" : success })

def logout(request):
    print(request)
    for key, value in request.session.items():
        print('{} => {}'.format(key, value))

    session_id= request.session._session_key
    
    try:
        my_session = Session.objects.get(session_key=session_id)
        my_session.delete()
    except:
        pass
    

    return redirect(index)
def login(request):
    form = LoginForm
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
            return redirect('profile')
    except:
        context["login"]=False
    
    msg     = None
    success = False
    
    
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            
            phone = form.cleaned_data.get("phone")
            print(phone)
            my_phone = str(phone)

            if student.objects.filter(phone=my_phone).exists() or student.objects.filter(phone=phone).exists():
                num="0123456789"
                def get_random_string(length):
                    result_str = ''.join(random.choice(num)for i in range(length))
                    return result_str

                rand = get_random_string(4)
                
                headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
                url = "https://api.ghasedak.me/v2/verification/send/simple"
                payload = "receptor="+str(phone)+"&template=foodfaast&type=1&param1="+str(rand)

                headers = {
                'content-type': "application/x-www-form-urlencoded",
                'apikey': "0fb39b9c0172a3399f83f2e068abbf9b72bab7bab038ccd955f768e3348a7b15",
                'cache-control': "no-cache",
                }

                response = requests.request("POST", url, data=payload, headers=headers)

                request.session['my_key'] = rand
                request.session['phone'] = my_phone
                sample_string = str(rand)
                sample_string_bytes = sample_string.encode("ascii")
                
                base64_bytes = base64.b64encode(sample_string_bytes)
                my_key = base64_bytes.decode("ascii")
                return redirect(verify_login)
            else:
                msg = 'اکانتی یافت نشد'
        else:
            msg = 'Error validating the form' 
        
    else:
        form = LoginForm()

    html_template = loader.get_template( 'login.html' )
    return render(request, "login.html", {"form": form, "msg" : msg, "success" : success })

def verify_login(request):
    form = verifycode
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    
    phone = request.session['phone']
    my_value = request.session['my_key']
    username="student"
    print('in verify')
    
    print(phone)
    username=urllib.parse.unquote(username)

    if request.method == "POST":
        form = verifycode(request.POST)
        if form.is_valid():
            
            code = form.cleaned_data.get("code")
            if code ==int(my_value):
                my_phone=str(phone)
                if not student.objects.filter(phone=my_phone).exists() and not student.objects.filter(phone=phone).exists():
                    student.objects.create(phone=my_phone,name=username,password=str(my_value))
                
                request.session["login"]=True
                return redirect('profile')
            else :
                msg = 'کد وارد شده نا معتبر است'
        else:
            msg = 'Error validating the form' 
        
    else:
        form = verifycode()

    html_template = loader.get_template( 'register.html' )
    return render(request, "verify.html", {"form": form, "msg" : msg, "success" : success })

def profile(request):
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
   
    print("inprofile")
    try:
        if request.session["login"]==True:
            phone = request.session['phone']
            my_phone=str(phone)
    except:
        return redirect(index) 
    try:
        this_student1= student.objects.filter(phone=phone).first()
    except student.DoesNotExist:
        this_student1= None
    try:
        this_student2= student.objects.filter(phone=my_phone).first()
    except student.DoesNotExist:
        this_student2= None
    if this_student1 != None or this_student2 != None:
        if this_student1 != None:
            profile=this_student1
        else:
            profile=this_student2
        licenses=spotplayer_license.objects.filter(user=profile)
        context['name']=profile.name
        context['phone']=profile.phone
        context['license']=licenses
        
        all_dore=profile.course.all()
        
        for my_dore in all_dore:
            if my_dore.pack:
                for item in my_dore.sub_course.all():
                        profile.course.add(item)
                        profile.save()
                        
        sp_course =  get_object_or_404(course,course_id="13")
        if sp_course in all_dore:
            context['alert']=True
        context['my_course']=profile.course.filter(hide=False)      
        html_template = loader.get_template('profile.html')
        context['segment'] = "profile.html" 
        
        return HttpResponse(html_template.render(context, request))

def shop(request):
    dore_id = request.GET['id']
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
            phone = request.session['phone']
            my_phone=str(phone)
            print("loged in")
            success = True
            try:
                this_student1= student.objects.filter(phone=phone).first()
            except student.DoesNotExist:
                this_student1= None
            try:
                this_student2= student.objects.filter(phone=my_phone).first()
            except student.DoesNotExist:
                this_student2= None
            if this_student1 != None or this_student2 != None:
                if this_student1 != None:
                    this_student=this_student1
                else:
                    this_student=this_student2
            course_set=this_student.course.all()
            this_dore = get_object_or_404(course,id=dore_id)
            for item in course_set:
                if item == this_dore:
                    context['course_active']= True
                    return redirect(player,phone=phone,id=this_dore.course_id)
                    
    except:
        context["login"]=False
    
    this_dore = get_object_or_404(course,id=dore_id)
    if this_dore.course_pack :
        my_headline = this_dore.sub_course.all()
        videolist = {}
        for item in my_headline:
            videolist[f'{item}'] = videos.objects.filter(dore=item).order_by('video_id')
    else:
        my_headline = headline.objects.filter(dore=this_dore).order_by('headline_id')
        videolist = {}
        for item in my_headline:
            videolist[f'{item}'] = videos.objects.filter(headline=item).order_by('video_id')
    context['videolist']=videolist
    context['course']=this_dore
    html_template = loader.get_template( 'shop.html' )
    context['segment'] = "shop.html" 
    
    return HttpResponse(html_template.render(context, request))


@csrf_exempt
def shop_submit(request):
    dore_id = request.GET['id']
    try:
        input_type = request.GET['input']
    except:
        input_type = 0

    form = SignUpForm
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    dore =get_object_or_404(course,course_id=dore_id)
    try: 
        if request.session["login"]==True:
            phone = request.session['phone']
            my_phone=str(phone)
            print("loged in")
            success = True
            try:
                this_student1= student.objects.filter(phone=phone).first()
            except student.DoesNotExist:
                this_student1= None
            try:
                this_student2= student.objects.filter(phone=my_phone).first()
            except student.DoesNotExist:
                this_student2= None
            if this_student1 != None or this_student2 != None:
                if this_student1 != None:
                    this_student=this_student1
                else:
                    this_student=this_student2
            
            if dore.free:
                this_student.course.add(dore)
                for item in dore.sub_course.all():
                    this_student.course.add(item)
                this_student.save()
            
                return redirect(player,phone=phone,id=dore.course_id)
            else:
                return redirect(send_request,dore_id=dore_id,phone=phone,input_type=input_type)
    except:
        pass           


    if request.method == "POST":
        form = SignUpForm(request.POST)
        
        
        if form.is_valid():
            
            name = form.cleaned_data.get("username")
            username=urllib.parse.unquote(name)
            phone = str(form.cleaned_data.get("phone"))
            my_phone=phone
            num="0123456789"
            def get_random_string(length):
                result_str = ''.join(random.choice(num)for i in range(length))
                return result_str

            rand = get_random_string(4)
            msg     = 'User created - please <a href="/login">login</a>.'
            success = True
            url = 'https://panel.spotplayer.ir/license/edit/'
            myobj = {
                "course": [str(dore_id)],
                "name": username,
                "watermark": {"texts": [{"text": phone}]}
            }
            headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
            url = "https://api.ghasedak.me/v2/verification/send/simple"
            payload = "receptor="+str(phone)+"&template=foodfaast&type=1&param1="+str(rand)

            headers = {
            'content-type': "application/x-www-form-urlencoded",
            'apikey': "0fb39b9c0172a3399f83f2e068abbf9b72bab7bab038ccd955f768e3348a7b15",
            'cache-control': "no-cache",
            }

            response = requests.request("POST", url, data=payload, headers=headers)
            try:
                del request.session["my_key"]
            except:
                pass
            sample_string = str(rand)
            sample_string_bytes = sample_string.encode("ascii")
            base64_bytes = base64.b64encode(sample_string_bytes)
            my_key = base64_bytes.decode("ascii")
            print('in login')
            request.session["my_key"]=rand
            return redirect(verify_shoper,phone=phone,username=username,dore_id=dore_id,input_type=input_type)
        else:
            msg = 'Error validating the form' 
        
    else:
        form = SignUpForm()
    
    html_template = loader.get_template( 'shop_submit.html' )
    return render(request, "shop_submit.html", {"form": form, "msg" : msg, "success" : success })
@csrf_exempt
def verify_shoper(request,phone,username,dore_id,input_type):

    form = verifycode
    context = {}

    try:

        if request.session["login"]==True:

            context["login"]=True

    except:

        context["login"]=False

    
    msg     = None

    success = False

    my_value=request.session["my_key"]

    print(my_value)

    print(phone)

    username=urllib.parse.unquote(username)

    dore =get_object_or_404(course,course_id=dore_id)

    if request.method == "POST":

        msg='in post'

        form = verifycode(request.POST)

        if form.is_valid():

            code = form.cleaned_data.get("code")

            if code ==int(my_value):
                del request.session["my_key"]
                
                my_phone=str(phone)
                if not student.objects.filter(phone=my_phone).exists() and not student.objects.filter(phone=phone).exists() :
                    my_phone=str(phone)
                    student.objects.create(phone=my_phone,name=username,password=str(my_value))
                try:
                    this_student1= student.objects.filter(phone=phone).first()
                except student.DoesNotExist:
                    this_student1= None
                try:
                    this_student2= student.objects.filter(phone=my_phone).first()
                except student.DoesNotExist:
                    this_student2= None
                if this_student1 != None or this_student2 != None:
                    if this_student1 != None:
                        this_student=this_student1
                    else:
                        this_student=this_student2
                request.session["login"]=True
                request.session["phone"]=phone
                course_set=this_student.course.all()
                this_dore = get_object_or_404(course,id=dore_id)
                for item in course_set:
                    if item == this_dore:
                        context['course_active']= True
                        return redirect(player,phone=phone,id=this_dore.course_id)

                if dore.free:

                    this_student.course.add(dore)

                    for item in dore.sub_course.all():

                        this_student.course.add(item)

                    this_student.save()

                    return redirect(player,phone=phone,id=dore.course_id)

                else:

                    return redirect(send_request,dore_id=dore_id,phone=phone,input_type=input_type)

        else:

            msg = 'Error validating the form'

    else:

        form = verifycode()

    html_template = loader.get_template( 'verify.html' )

    return render(request, "verify.html", {"form": form, "msg" : msg, "success" : success })

MMERCHANT_ID = '3d30e3b4-9482-4fe5-81d9-79895bb15c08'  # Required
ZARINPAL_WEBSERVICE = 'https://www.zarinpal.com/pg/services/WebGate/wsdl'  # Required
amount = 1000  # Amount will be based on Toman  Required
description = u'توضیحات تراکنش تستی'  # Required
email = 'user@userurl.ir'  # Optional
mobile = '09123456789'  # Optional
CallbackURL = 'http://127.0.0.1:8000/verify/'


def send_request(request,phone,dore_id,input_type):
    my_phone=str(phone)[1:]
    try:
        this_student1= student.objects.filter(phone=phone).first()
    except student.DoesNotExist:
        this_student1= None
    try:
        this_student2= student.objects.filter(phone=my_phone).first()
    except student.DoesNotExist:
        this_student2= None
    if this_student1 != None or this_student2 != None:
        if this_student1 != None:
            this_student=this_student1
        else:
            this_student=this_student2
        
        dore =get_object_or_404(course,course_id=dore_id)
        
        amount=str(dore.mablagh)
        CallbackURL = 'http://127.0.0.1:8000/verify/'+my_phone+'/'+dore_id+'/'+input_type
        client = Client(ZARINPAL_WEBSERVICE)
        result = client.service.PaymentRequest(MMERCHANT_ID,
                                               amount,
                                               description,
                                               email,
                                               mobile,
                                               CallbackURL)
        if result.Status == 100:
            return redirect('https://www.zarinpal.com/pg/StartPay/' + result.Authority)
        else:
            return HttpResponse('Error')
        
    else:
        msg:'eror'


def verify(request,phone,dore_id,input_type):
    client = Client(ZARINPAL_WEBSERVICE)
    my_phone="+"+str(phone)
    try:
        this_student1= student.objects.filter(phone=phone).first()
    except student.DoesNotExist:
        this_student1= None
    try:
        this_student2= student.objects.filter(phone=my_phone).first()
    except student.DoesNotExist:
        this_student2= None
    if this_student1 != None or this_student2 != None:
        if this_student1 != None:
            this_student=this_student1
        else:
            this_student=this_student2
        my_dore =get_object_or_404(course,course_id=dore_id)
        username=this_student.name
        amount=str(my_dore.mablagh)
        if request.GET.get('Status') == 'OK':
            result = client.service.PaymentVerification(MMERCHANT_ID,
                                                        request.GET['Authority'],
                                                        amount)
            if result.Status == 100 or 101:
            
                this_student.course.add(my_dore)
                if my_dore.pack:
                    for item in my_dore.sub_course.all():
                        this_student.course.add(item)
                this_student.save()
                my_input = get_object_or_404(input,input_id=int(input_type))
                my_input.count = my_input.count + 1
                my_input.save()
                smsname = username.replace(" ","")
                url = "https://api.ghasedak.me/v2/verification/send/simple"
                payload = "receptor="+str(phone)+"&template=ffactive&type=1&param1="+str(smsname)+"&param2="+urllib.parse.quote(str(my_dore.suport))
    
                headers = {
                'content-type': "application/x-www-form-urlencoded",
                'apikey': "9d7ee80e9ea959c286cdbb2e870976da555adffdfb93c4e0e760153d577c9cb5",
                'cache-control': "no-cache",
                }
    
                response = requests.request("POST", url, data=payload.encode('utf8'), headers=headers)

                url = 'https://panel.spotplayer.ir/license/edit/'
                myobj = {
                    "course": [str(dore_id)],
                    "offline": 30,
                    "name": username,
                    
                    "watermark": {
                        
                    "texts": [
                        {
                            "text": phone,
                            "repeat": 10,
                            "font": 1,
                            "weight": 1,
                            "color": 2164260863,
                            "size": 50,
                            "stroke": {"color": 2164260863, "size": 1}
                        },
                    ]
                    },
                    "device": {
                        "p0": 4, 
                        "p1": 2, 
                        "p2": 0, 
                        "p3": 0, 
                        "p4": 2, 
                        "p5": 0,
                        "p6": 2,
                    }
                }
                headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
                request.session["login"]=True
                request.session["phone"]=my_phone
                return redirect('profile')
            
            else:
                return HttpResponse('Transaction failed. Status: ' + str(result.Status))
        else:
            return HttpResponse('Transaction failed or canceled by user')
            
    else:
        msg='eror'

def insta_ghore(request):
    
    form = usernameform
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    print(request.POST)
    
    
    if request.method == "POST":
        form = usernameform(request.POST)
        
        
        if form.is_valid():
            
            username = form.cleaned_data.get("username")
            
            if not ghore.objects.filter(username=username).exists():
                msg = 'اکانت شما با موفقیت ثبت شد'
                my_id = int(ghore.objects.all().count())+1
                ghore.objects.create(username=username,ghore_id=my_id)
            else:
                msg = 'این اکانت قبلا ثبت شده است'
        
        
        else:
            msg = 'Error validating the form' 
        
    else:
        form = usernameform()
    
    html_template = loader.get_template( 'ghore.html' )
    return render(request, "ghore.html", {"form": form, "msg" : msg, "success" : success })

def videoPlayer(request):
    context={}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    dore_id = request.GET['id']
    this_dore =get_object_or_404(course,course_id=dore_id)
    my_videos = videos.objects.filter(dore=this_dore).order_by('video_id')
    my_files = course_file.objects.filter(dore=this_dore)
    context['files']=my_files
    context['videos']=my_videos
    context['course']=this_dore
    
    context['license']="null"
    html_template = loader.get_template( 'videoPlayer.html' )
    context['segment'] = "videoPlayer.html" 
    
    return HttpResponse(html_template.render(context, request))
    
def course_submit(request):
    
    form = SignUpForm
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    print(request.POST)
    
    
    if request.method == "POST":
        form = SignUpForm(request.POST)
        
        
        if form.is_valid():
            
            name = form.cleaned_data.get("username")
            username=urllib.parse.unquote(name)
            print(username)
            phone = str(form.cleaned_data.get("phone"))
            print(phone)
            num="0123456789"
            def get_random_string(length):
                result_str = ''.join(random.choice(num)for i in range(length))
                return result_str

            rand = get_random_string(4)
            
            url = "https://api.ghasedak.me/v2/verification/send/simple"
            payload = "receptor="+str(phone)+"&template=foodfaast&type=1&param1="+str(rand)

            headers = {
            'content-type': "application/x-www-form-urlencoded",
            'apikey': "0fb39b9c0172a3399f83f2e068abbf9b72bab7bab038ccd955f768e3348a7b15",
            'cache-control': "no-cache",
            }

            response = requests.request("POST", url, data=payload, headers=headers)

            sample_string = str(rand)
            sample_string_bytes = sample_string.encode("ascii")
            
            base64_bytes = base64.b64encode(sample_string_bytes)
            my_key = base64_bytes.decode("ascii")
            print('in login')
            for key, value in request.session.items():
                print('{} => {}'.format(key, value))
            return redirect(course_login,my_key=my_key,phone=phone,username=username)
        else:
            msg = 'Error validating the form' 
        
    else:
        form = SignUpForm()

    html_template = loader.get_template( 'register.html' )
    return render(request, "shop_submit.html", {"form": form, "msg" : msg, "success" : success })

def course_login(request,my_key,phone,username):
    form = verifycode
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    username=urllib.parse.unquote(username)
    base64_string = str(my_key)
    base64_bytes = base64_string.encode("ascii") 
    sample_string_bytes = base64.b64decode(base64_bytes)
    my_value = sample_string_bytes.decode("ascii")
    print('in verify')
    for key, value in request.session.items():
        print('{} => {}'.format(key, value))
    print(phone)
    
    my_dore =get_object_or_404(course,course_id="612f674cc026b9882fd16a66")
    if request.method == "POST":
        form = verifycode(request.POST)
        if form.is_valid():
            
            code = form.cleaned_data.get("code")
            if code ==int(my_value):
                my_phone=str(phone)
                if not student.objects.filter(phone=my_phone).exists() and not student.objects.filter(phone=phone).exists():
                    this_student=student.objects.create(phone=my_phone,name=username,password=str(my_value),course1=True,course2=True)
                try:
                    this_student1= student.objects.filter(phone=phone).first()
                except student.DoesNotExist:
                    this_student1= None
                try:
                    this_student2= student.objects.filter(phone=my_phone).first()
                except student.DoesNotExist:
                    this_student2= None
                if this_student1 != None or this_student2 != None:
                    if this_student1 != None:
                        this_student=this_student1
                    else:
                        this_student=this_student2
                    course_1= get_object_or_404(course,course_id="60be917d6751d64c81631d80")
                    course_2= get_object_or_404(course,course_id="612f674cc026b9882fd16a66")
                    course_3= get_object_or_404(course,course_id="3")
                    this_student.course.add(course_1)
                    this_student.course.add(course_2)
                    this_student.save()
                    
                spot_course=['612f674cc026b9882fd16a66','60be917d6751d64c81631d80']
                url = 'https://panel.spotplayer.ir/license/edit/'
                myobj = {
                    "course": spot_course,
                    "offline": 30,
                    "name": username,
                    "watermark": {
                    "texts": [
                        {
                            "text": phone,
                            "repeat": 10,
                            "font": 1,
                            "weight": 1,
                            "color": 2164260863,
                            "size": 50,
                            "stroke": {"color": 2164260863, "size": 1}
                        },
                    ]
                    },
                    "device": {
                        "p0": 4, 
                        "p1": 2, 
                        "p2": 0, 
                        "p3": 0, 
                        "p4": 2, 
                        "p5": 0,
                        "p6": 2,
                    }
                }
                headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
                return redirect(profile,phone=phone)
            else :
                msg = 'رمز نامعتبر است'
        else:
            msg = 'Error validating the form' 
        
    else:
        form = verifycode()

    html_template = loader.get_template( 'register.html' )
    return render(request, "verify.html", {"form": form, "msg" : msg, "success" : success })
    
def player(request,phone,id):
    context={}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    dore_id = id
    my_phone=phone
    try:
        this_student1= student.objects.filter(phone=phone).first()
    except student.DoesNotExist:
        this_student1= None
    try:
        this_student2= student.objects.filter(phone=my_phone).first()
    except student.DoesNotExist:
        this_student2= None
    if this_student1 != None or this_student2 != None:
        if this_student1 != None:
            this_student=this_student1
        else:
            this_student=this_student2
        this_dore =get_object_or_404(course,course_id=dore_id)
        try:
            my_license=get_object_or_404(spotplayer_license,user=this_student,dore=this_dore)
            context['license']=my_license.license
        except:
            pass
        if this_dore.course_pack :
            context['course_pack']=True
            my_files = []
            my_headline = this_dore.sub_course.all().order_by('course_id')
            videolist = {}
            for item in my_headline:
                videolist[f'{item}'] = videos.objects.filter(dore=item).order_by('video_id')
                my_files.append(course_file.objects.filter(dore=item))
        else:
            my_headline = headline.objects.filter(dore=this_dore).order_by('headline_id')
            videolist = {}
            for item in my_headline:
                videolist[f'{item}'] = videos.objects.filter(headline=item).order_by('video_id')
            if len(my_headline)==0:
                videolist['سرفصل'] = videos.objects.filter(dore=this_dore).order_by('video_id')
            my_files = course_file.objects.filter(dore=this_dore)
        if this_dore.alert_active :
            context['alert'] = this_dore.alert
        else :
            context['alert'] = False
        context['files']=my_files
        context['videolist']=videolist
        context['course']=this_dore
        html_template = loader.get_template( 'video.html' )
        context['segment'] = "video.html" 
        
        return HttpResponse(html_template.render(context, request))
def freeview(request):
    context={}
    
    dore_id = request.GET['id']
    this_dore =get_object_or_404(course,course_id=dore_id)
    
    my_headline = headline.objects.filter(dore=this_dore).order_by('headline_id')
    videolist = {}
    if this_dore.course_pack :
        context['course_pack']=True
        my_files = []
        my_headline = this_dore.sub_course.all().order_by('course_id')
        videolist = {}
        for item in my_headline:
            videolist[f'{item}'] = videos.objects.filter(dore=item).order_by('video_id')
            my_files.append(course_file.objects.filter(dore=item))
    else:
        my_headline = headline.objects.filter(dore=this_dore).order_by('headline_id')
        videolist = {}
        for item in my_headline:
            videolist[f'{item}'] = videos.objects.filter(headline=item).order_by('video_id')
        if len(my_headline)==0:
            videolist['سرفصل'] = videos.objects.filter(dore=this_dore).order_by('video_id')
        my_files = course_file.objects.filter(dore=this_dore)

        sub_course = this_dore.sub_course.all().order_by('course_id')
        subcourse_videolist = {}
        subcourse_files = []
        for item in sub_course:
            subcourse_videolist[f'{item}'] = videos.objects.filter(dore=item).order_by('video_id')
            subcourse_files.append(course_file.objects.filter(dore=item))
        context['subcourse_videolist'] = subcourse_videolist
    context['files']=my_files
    context['videolist']=videolist
    
    context['course']=this_dore
    html_template = loader.get_template( 'freeview.html' )
    context['segment'] = "freeview.html" 
        
    return HttpResponse(html_template.render(context, request))

def course_submit3(request):
    
    form = SignUpForm
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    print(request.POST)
    
    
    if request.method == "POST":
        form = SignUpForm(request.POST)
        
        
        if form.is_valid():
            
            name = form.cleaned_data.get("username")
            username=urllib.parse.unquote(name)
            print(username)
            phone = str(form.cleaned_data.get("phone"))
            print(phone)
            num="0123456789"
            def get_random_string(length):
                result_str = ''.join(random.choice(num)for i in range(length))
                return result_str

            rand = get_random_string(4)
            
            url = "https://api.ghasedak.me/v2/verification/send/simple"
            payload = "receptor="+str(phone)+"&template=foodfaast&type=1&param1="+str(rand)

            headers = {
            'content-type': "application/x-www-form-urlencoded",
            'apikey': "0fb39b9c0172a3399f83f2e068abbf9b72bab7bab038ccd955f768e3348a7b15",
            'cache-control': "no-cache",
            }

            response = requests.request("POST", url, data=payload, headers=headers)

            sample_string = str(rand)
            sample_string_bytes = sample_string.encode("ascii")
            
            base64_bytes = base64.b64encode(sample_string_bytes)
            my_key = base64_bytes.decode("ascii")
            print('in login')
            for key, value in request.session.items():
                print('{} => {}'.format(key, value))
            return redirect(course_login3,my_key=my_key,phone=phone,username=username)
        else:
            msg = 'Error validating the form' 
        
    else:
        form = SignUpForm()

    html_template = loader.get_template( 'register.html' )
    return render(request, "shop_submit.html", {"form": form, "msg" : msg, "success" : success })

def course_login3(request,my_key,phone,username):
    form = verifycode
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False

    msg     = None
    success = False
    username=urllib.parse.unquote(username)
    base64_string = str(my_key)
    base64_bytes = base64_string.encode("ascii") 
    sample_string_bytes = base64.b64decode(base64_bytes)
    my_value = sample_string_bytes.decode("ascii")
    print('in verify')
    for key, value in request.session.items():
        print('{} => {}'.format(key, value))
    print(phone)
    
    my_dore =get_object_or_404(course,course_id="612f674cc026b9882fd16a66")
    if request.method == "POST":
        form = verifycode(request.POST)
        if form.is_valid():
            
            code = form.cleaned_data.get("code")
            if code ==int(my_value):
                my_phone=str(phone)
                if not student.objects.filter(phone=my_phone).exists() and not student.objects.filter(phone=phone).exists():
                    this_student=student.objects.create(phone=my_phone,name=username,password=str(my_value),course3=True)
                    course_3= get_object_or_404(course,course_id="3")
                    this_student.course.add(course_3)
                    
                    this_student.save()
        
                else:
                    try:
                        this_student1= student.objects.filter(phone=phone).first()
                    except student.DoesNotExist:
                        this_student1= None
                    try:
                        this_student2= student.objects.filter(phone=my_phone).first()
                    except student.DoesNotExist:
                        this_student2= None
                    if this_student1 != None or this_student2 != None:
                        if this_student1 != None:
                            this_student=this_student1
                        else:
                            this_student=this_student2
                        course_1= get_object_or_404(course,course_id="60be917d6751d64c81631d80")
                        course_2= get_object_or_404(course,course_id="612f674cc026b9882fd16a66")
                        course_3= get_object_or_404(course,course_id="3")
                        this_student.course.add(course_3)
                        
                        this_student.save()
                    
                spot_course=['612f674cc026b9882fd16a66','60be917d6751d64c81631d80']
                url = 'https://panel.spotplayer.ir/license/edit/'
                myobj = {
                    "course": spot_course,
                    "offline": 30,
                    "name": username,
                    "watermark": {
                    "texts": [
                        {
                            "text": phone,
                            "repeat": 10,
                            "font": 1,
                            "weight": 1,
                            "color": 2164260863,
                            "size": 50,
                            "stroke": {"color": 2164260863, "size": 1}
                        },
                    ]
                    },
                    "device": {
                        "p0": 4, 
                        "p1": 2, 
                        "p2": 0, 
                        "p3": 0, 
                        "p4": 2, 
                        "p5": 0,
                        "p6": 2,
                    }
                }
                headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
                return redirect(profile,phone=phone)
            else :
                msg = 'رمز نامعتبر است'
        else:
            msg = 'Error validating the form' 
        
    else:
        form = verifycode()

    html_template = loader.get_template( 'register.html' )
    return render(request, "verify.html", {"form": form, "msg" : msg, "success" : success })
    
def course_spot(request):

    form = SignUpForm
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    
    msg     = None
    success = False
    print(request.POST)
        
    
    if request.method == "POST":
        form = SignUpForm(request.POST)
        
        
        if form.is_valid():
            
            name = form.cleaned_data.get("username")
            username=urllib.parse.unquote(name)
            print(username)
            phone = str(form.cleaned_data.get("phone"))
            print(phone)
            num="0123456789"
            def get_random_string(length):
                result_str = ''.join(random.choice(num)for i in range(length))
                return result_str

            rand = get_random_string(4)
            
            url = "https://api.ghasedak.me/v2/verification/send/simple"
            payload = "receptor="+str(phone)+"&template=foodfaast&type=1&param1="+str(rand)

            headers = {
            'content-type': "application/x-www-form-urlencoded",
            'apikey': "0fb39b9c0172a3399f83f2e068abbf9b72bab7bab038ccd955f768e3348a7b15",
            'cache-control': "no-cache",
            }

            response = requests.request("POST", url, data=payload, headers=headers)

            sample_string = str(rand)
            sample_string_bytes = sample_string.encode("ascii")
            
            base64_bytes = base64.b64encode(sample_string_bytes)
            my_key = base64_bytes.decode("ascii")
            print('in login')
            for key, value in request.session.items():
                print('{} => {}'.format(key, value))
            return redirect(course_login_spot,my_key=my_key,phone=phone,username=username)
        else:
            msg = 'Error validating the form' 
        
    else:
        form = SignUpForm()

    html_template = loader.get_template( 'register.html' )
    return render(request, "shop_submit.html", {"form": form, "msg" : msg, "success" : success })

def course_login_spot(request,my_key,phone,username):
    form = verifycode
    context = {}
    try:
        if request.session["login"]==True:
            context["login"]=True
    except:
        context["login"]=False
    msg     = None
    success = False
    username=urllib.parse.unquote(username)
    base64_string = str(my_key)
    base64_bytes = base64_string.encode("ascii") 
    sample_string_bytes = base64.b64decode(base64_bytes)
    my_value = sample_string_bytes.decode("ascii")
    print('in verify')
    for key, value in request.session.items():
        print('{} => {}'.format(key, value))
    print(phone)
    
    my_dore =get_object_or_404(course,course_id="3")
    if request.method == "POST":
        form = verifycode(request.POST)
        if form.is_valid():
            
            code = form.cleaned_data.get("code")
            if code ==int(my_value):
                my_phone=str(phone)
                if not student.objects.filter(phone=my_phone).exists() and not student.objects.filter(phone=phone).exists():
                    this_student=student.objects.create(phone=my_phone,name=username,password=str(my_value),course3=True)
                
        
                else:
                    try:
                        this_student1= student.objects.filter(phone=phone).first()
                    except student.DoesNotExist:
                        this_student1= None
                    try:
                        this_student2= student.objects.filter(phone=my_phone).first()
                    except student.DoesNotExist:
                        this_student2= None
                    if this_student1 != None or this_student2 != None:
                        if this_student1 != None:
                            this_student=this_student1
                        else:
                            this_student=this_student2
                        this_student.course3=True
                        this_student.save()
                    
                spot_course=['61a615899029ee732d81bc8c']
                url = 'https://panel.spotplayer.ir/license/edit/'
                myobj = {
                    "course": spot_course,
                    "offline": 30,
                    "name": username,
                    "watermark": {
                    "texts": [
                        {
                            "text": phone,
                            "repeat": 10,
                            "font": 1,
                            "weight": 1,
                            "color": 2164260863,
                            "size": 50,
                            "stroke": {"color": 2164260863, "size": 1}
                        },
                    ]
                    },
                    "device": {
                        "p0": 4, 
                        "p1": 2, 
                        "p2": 0, 
                        "p3": 0, 
                        "p4": 2, 
                        "p5": 0,
                        "p6": 2,
                    }
                }
                headers = {'$API': 'YL6NoGdR1kyBYx1EsM2JuVP6yVo2hkbcFw=='}
                x = requests.post(url, headers=headers,json= myobj)
                print(x.json())
                try :
                    my_license=x.json()["key"]
                    spotplayer_license.objects.create(dore=my_dore,user=this_student,license=my_license)
                except: 
                    pass   
                return redirect(profile,phone=phone)
            else :
                msg = 'رمز نامعتبر است'
        else:
            msg = 'Error validating the form' 
        
    else:
        form = verifycode()

    html_template = loader.get_template( 'register.html' )
    return render(request, "verify.html", {"form": form, "msg" : msg, "success" : success })
    