Пример #1
0
def add_relations_view(request):
    """Used to add a new relation.

    If submitting a request to add a relation, request.POST will contain the following keys:
        email = Email address of the reciever
        share_savemeplan = 1 if savemeplan should be shared, else 0
        share_check = 1 if check should be shared, else 0
        share_prepare = 1 if prepare should be shared, else 0
        share_media = 1 if media should be shared, else 0
    """
    if 'UserId' not in request.session.keys():  # Check if user is logged in
        return HttpResponseRedirect(reverse('login:Login'))
    elif request.session["Role"] != "User":
        return HttpResponseRedirect(reverse('userprofile:Profile'))

    delete_temp_files(request.session)

    profile_lang = get_lang(sections=["userprofile"])

    alerts = dict()
    if request.method == 'POST':
        if login.models.User.objects.filter(
                Email=request.POST['email'].lower()):
            recieverEmail = request.POST['email'].lower()
        else:
            alerts['email'] = 'email_does_not_exist'

        if not alerts:
            try:
                user = login.models.User.objects.filter(
                    UserId=request.session['UserId'])[0]
            except IndexError:
                return HttpResponseRedirect(reverse('login:Login'))
            permissions = '1'
            permissions += '1' if 'share_savemeplan' in request.POST else '0'
            permissions += '1' if 'share_check' in request.POST else '0'
            permissions += '1' if 'share_prepare' in request.POST else '0'
            permissions += '1' if 'share_media' in request.POST else '0'
            new_entry("r1",
                      user.getAnonId(request.session['PrivKey']),
                      "professional: " + permissions,
                      role=request.session['Role'])

            if not userprofile.tools.create_relation(
                    user.getUid(), request.session['PrivKey'], recieverEmail,
                    permissions):
                return HttpResponseRedirect(reverse('userprofile:Relations'))
            else:
                alerts['database'] = 'database_error'

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'back': UNIVERSAL_LANG["universal"]["back"],
        'relations': profile_lang["userprofile"]["relations"],
        'form': profile_lang["userprofile"]["relations"]["form"],
        'alerts': alerts,
        "alert": profile_lang["userprofile"]["long_texts"]["alerts"],
        "warning": UNIVERSAL_LANG["universal"]["warning"]
    }
    return render(request, 'userprofile/addrelations.html', args)
Пример #2
0
def profile_view(request):
    """Main profile view for a user. Used by users and professionals.
    """
    if 'UserId' not in request.session.keys():  # Check if user is logged in
        return HttpResponseRedirect(reverse('login:Login'))

    delete_temp_files(request.session)
    try:
        user = login.models.User.objects.filter(
            UserId=request.session['UserId'])[0]
    except IndexError:
        return HttpResponseRedirect(reverse('login:Login'))

    if request.method == 'GET':  # Used for logout. logout is in GET keys with a value of 1.
        if 'logout' in request.GET.keys():
            new_entry("u2",
                      user.getAnonId(request.session['PrivKey']),
                      "na",
                      role=request.session['Role'])
            request.session.flush()
            return HttpResponseRedirect(reverse('login:Login'))

    profile_lang = get_lang(sections=["userprofile"])
    login_lang = get_lang(sections=["login"])
    new_entry("g1",
              user.getAnonId(request.session['PrivKey']),
              "prof",
              role=request.session['Role'])
    first_name = user.getFirstName(request.session['PrivKey'])
    last_name = user.getLastName(request.session['PrivKey'])

    global_alerts = []  # The variable which is sent to template

    if "global_alerts" in request.session.keys(
    ):  # Check if global_elerts is in session allready.
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    template = "base_professionals.html" if request.session[
        "Role"] == "Professional" else "base.html"
    profView = True if request.session["Role"] == "Professional" else False

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'global_alerts': global_alerts,
        'form': login_lang["login"]["form"],
        'userprofile': profile_lang["userprofile"],
        'profile': profile_lang["userprofile"]["long_texts"],
        'first_name': first_name,
        'last_name': last_name,
        'template': template,
        'profView': profView
    }

    return render(request, 'userprofile/profile.html', args)
Пример #3
0
def contacts_view(request):
    """Used to add a new contact.
    If submitting a request to add a new contact, request.POST contains the following keys:
        name = Name of the contact
        phonenumber = Phonenumber of the contact
        available = When the contact is available
    """

    if not 'UserId' in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))

    prepare.tools.delete_temp_files(request.session)

    alerts = {}
    if request.method == 'POST':
        exceptions = ''
        user = login.models.User.objects.filter(
            UserId=request.session["UserId"])[0]
        prepare_lang = get_lang(sections=["prepare"])
        for index in ['name', 'phonenumber', 'available']:
            if index == 'phonenumber':
                exceptions = '+0123456789'
            if index == 'available':
                exceptions = '0123456789+-/'
            if login.tools.contains_bad_char(request.POST[index], exceptions):
                alerts[index] = "badChar"
        if not alerts:
            prepare.tools.addContact(user.getUid(), request.POST['name'],
                                     request.POST['phonenumber'],
                                     request.POST['available'],
                                     request.session['PrivKey'])
            new_entry("p1",
                      user.getAnonId(request.session["PrivKey"]),
                      request.POST['phonenumber'],
                      mangle=True,
                      role=request.session['Role'])
            return HttpResponseRedirect(
                reverse('prepare:menu-page', args=(5, )))

    prepare_lang = get_lang(sections=["prepare"])

    args = {
        'POST': request.POST,
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'back': UNIVERSAL_LANG['universal']['back'],
        'alert': alerts,
        "back": UNIVERSAL_LANG["universal"]["back"],
        'prepare': prepare_lang["prepare"]
    }
    return render(request, 'prepare/add_contact.html', args)
Пример #4
0
def edit_profile_view(request):
    """Used to edit user data.
    If submitting a change request.POST will contain the following keys:
        first_name - Users first name
        last_name - Users last name
        gender - Gender of the user. Is one of the following
            Male
            Female
            Other
        gender_other - If user choose gender=Other this will contain a text.
        email - Users email.
        password - Users entered non hashed password, will be checked and needs to be correct for change to be done.
    request.GET is used for deletion of the entire account.
    """
    if not 'UserId' in request.session.keys():
        return HttpResponseRedirect(reverse('login:Login'))

    delete_temp_files(request.session)

    profile_lang = get_lang(sections=["userprofile"])
    login_lang = get_lang(sections=["login"])

    wrong_pass = False
    account = {}
    try:
        user = login.models.User.objects.filter(
            UserId=request.session['UserId'])[0]
    except IndexError:
        return HttpResponseRedirect(reverse('login:Login'))
    account['firstName'] = user.getFirstName(request.session['PrivKey'])
    account['lastName'] = user.getLastName(request.session['PrivKey'])
    account['gender'] = user.getGender(request.session['PrivKey'])
    account['email'] = user.getEmail()

    if request.GET:
        if request.GET['delete']:
            if userprofile.tools.check_password(request.session['UserId'],
                                                request.session['PrivKey'],
                                                request.POST['password']):
                if request.POST['password']:
                    user = login.models.User.objects.filter(
                        UserId=request.session['UserId'])[0]
                    with transaction.atomic():
                        if not 'researchData' in request.POST.keys():
                            forget_me(
                                user.getAnonId(request.session['PrivKey']))
                        if request.session['Role'] == 'User':
                            userprofile.tools.remove_all_of_users_relations(
                                request.session['UserId'],
                                request.session['PrivKey'])
                        elif request.session['Role'] == 'Professional':
                            userprofile.tools.remove_all_of_professionals_relations(
                                request.session['UserId'],
                                request.session['PrivKey'])
                        tools.mediaman.delete_all_files(
                            user.getAnonId(request.session['PrivKey']))
                        login.models.User.objects.filter(
                            UserId=request.session['UserId']).delete()
                        request.session.flush()
                    return HttpResponseRedirect(reverse('login:Login'))
            else:
                return HttpResponseRedirect(
                    reverse('userprofile:Edit-profile'))
    if request.method == 'POST':
        if userprofile.tools.check_password(request.session['UserId'],
                                            request.session['PrivKey'],
                                            request.POST['password']):
            user = login.models.User.objects.filter(
                UserId=request.session['UserId'])[0]
            if request.POST['gender'] == 'Other':
                user.setGender(request.POST['gender_other'])
            else:
                user.setGender(request.POST['gender'])
            user.setFirstName(request.POST['first_name'])
            user.setLastName(request.POST['last_name'])
            user.setEmail(request.POST['email'])
            user.save()

            #data collection
            for_science = {
                "firstname": (account['firstName'],
                              user.getFirstName(request.session['PrivKey'])),
                "lastname": (account['lastName'],
                             user.getLastName(request.session['PrivKey'])),
                "gender": (account['gender'],
                           user.getGender(request.session['PrivKey'])),
                "email": (account['email'], user.getEmail())
            }
            for science in for_science:
                if for_science[science][0] != for_science[science][0]:
                    new_entry("u3",
                              user.getAnonId(request.session['PrivKey']),
                              science,
                              role=request.session['Role'])
            del for_science, science

            alert = {
                "color":
                "success",
                "title":
                UNIVERSAL_LANG["universal"]
                ["success"],  # Should mostly be success, error or warning. This text is the bold text.
                "message":
                profile_lang["userprofile"]["long_texts"]["alerts"]
                ["changed_info_success"]
            }

            # Check if global_elerts is in session allready.
            if "global_alerts" not in request.session.keys():
                request.session["global_alerts"] = [alert]
            else:
                request.session["global_alerts"].append(alert)
            return HttpResponseRedirect(reverse('userprofile:Profile'))
        else:
            wrong_pass = True

    template = "base_professionals.html" if request.session[
        "Role"] == "Professional" else "base.html"

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'back': UNIVERSAL_LANG["universal"]["back"],
        'form': login_lang["login"]["form"],
        'userprofile': profile_lang["userprofile"],
        'profile': profile_lang["userprofile"]["long_texts"],
        'alerts': login_lang['login']['long_texts']['alerts'],
        "account": account,
        'wrong_pass': wrong_pass,
        'template': template,
        'profView': False
    }

    return render(request, 'userprofile/edit.html', args)
Пример #5
0
def login_view(request):
    """This view will display the login page and when submitting login credentials
    it will enter here.

    If submitting login credentials request.POST will contain the following keys:
        email - Users email.
        password - Users entered non hashed password
    """
    if 'UserId' in request.session:
        try:
            user = login.models.User.objects.filter(
                UserId=request.session['UserId'])[0]
            return HttpResponseRedirect(reverse('userprofile:Profile'))
        except IndexError:
            pass

    login_lang = get_lang(sections=["login"])

    login_fail = False
    if request.method == 'POST':
        try:
            user = login.models.User.objects.filter(
                Email=request.POST['email'].lower())[0]
        except Exception as e:
            user = None
            login_fail = True

        if user:
            key = login.models.gen_rsa(
                login.models.secret_scrambler(request.POST["password"],
                                              user.getUid()))
            if str(key.publickey().export_key()) == str(user.getPubkey()):
                request.session['UserId'] = user.getUid()
                request.session['PrivKey'] = key.export_key().decode("utf-8")
                request.session['Role'] = user.getRole()
                new_entry("u1", user.getAnonId(request.session['PrivKey']),
                          "na")
                if request.session['Role'] == 'User':
                    tools.global_alerts.add_alert(
                        request, 'info', UNIVERSAL_LANG['universal']['info'],
                        login_lang['login']['long_texts']['alerts']
                        ['daily_checkup'], '/check/checkup/')
                    login.tools.survey_time(request, user,
                                            request.session['PrivKey'])
                return HttpResponseRedirect(reverse('userprofile:Profile'))
            else:
                login_fail = True
        else:
            login_fail = True

    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    args = {
        'post': request.POST,
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'global_alerts': global_alerts,  # Sending the alerts to template.
        'form': login_lang["login"]["form"],
        'alerts': login_lang['login']['long_texts']['alerts'],
        'wrong_login_enterd': login_fail  # A check if right login was entered
    }

    return render(request, 'login/login.html', args)
Пример #6
0
def checkup_view(request):
    """Daily checkup page where user says how their day is. Using method GET for value.

    get variables:
    day = is either green, orange or red. Used to describe how your day is going
    """
    if 'UserId' not in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))
    elif request.session["Role"] != "User":
        return HttpResponseRedirect(reverse('userprofile:Profile'))

    check_lang = get_lang(sections=["check"])

    if request.GET:
        if 'day' in request.GET.keys():
            if request.GET['day'] in [
                    'red', 'orange', 'green'
            ]:  # Check if user has manipulated values.
                try:
                    user = login.models.User.objects.filter(
                        pk=request.session['UserId'])[
                            0]  # Session info of user
                except IndexError:
                    return HttpResponseRedirect(
                        reverse('login:Login'))  # Session info of user
                symkey = user.getSymKey(request.session['PrivKey'])
                today = datetime.date.today()
                check.tools.fillcheck(user, symkey)

                all_checks = user.check_set.order_by('CheckId').reverse()
                if len(all_checks) > 0:
                    last_check = all_checks[0]
                else:
                    last_check = None

                if last_check and last_check.getDate() == today:
                    check_entry = last_check
                else:
                    try:
                        check_entry = user.check_set.create(Date=today)
                    except Exception as e:
                        tools.global_alerts.add_alert(
                            request, 'warning',
                            UNIVERSAL_LANG['universal']['error'],
                            check_lang['check']['could_not_save'])
                        check_entry = None

                if check_entry:
                    try:
                        check_entry.setRating(symkey, request.GET['day'])
                        check_entry.save()
                        tools.global_alerts.add_alert(
                            request, 'success',
                            UNIVERSAL_LANG['universal']['success'],
                            check_lang['check']['could_save'])
                        new_entry("c1",
                                  user.getAnonId(request.session['PrivKey']),
                                  request.GET['day'],
                                  role=request.session['Role'])
                        return HttpResponseRedirect(
                            reverse('check:green-case'))

                    except Exception as e:
                        check_entry.delete()
                        tools.global_alerts.add_alert(
                            request, 'warning',
                            UNIVERSAL_LANG['universal']['error'],
                            check_lang['check']['could_not_save'])
            else:
                tools.global_alerts.add_alert(
                    request, 'warning', UNIVERSAL_LANG['universal']['error'],
                    check_lang['check']['could_not_save'])

    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]
        ["titles"],  # This is the menu-titles text retrieved from language file.
        'global_alerts': global_alerts,  # Sending the alerts to template.
        'check': check_lang["check"]
    }

    return render(request, 'check/checkup.html', args)
Пример #7
0
def green_case_view(request):
    """View for checking how your month is going.

    post variables:
    Used for showing this calender.
    month = month as number.
    year = Year in YYYY.

    """
    if 'UserId' not in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))
    elif request.session["Role"] != "User":
        return HttpResponseRedirect(reverse('userprofile:Profile'))

    prepare.tools.delete_temp_files(request.session)

    calendar = {  # Calendar variables
        'days': [],
        'year': '',
        'month': ''
    }

    if request.method == 'POST':  # Searched month & year
        if request.POST.keys():
            if 'month' and 'year' in request.POST.keys():
                try:
                    user = login.models.User.objects.filter(
                        pk=request.session['UserId'])[
                            0]  # Session info of user
                except IndexError:
                    return HttpResponseRedirect(reverse('login:Login'))

                calendar['year'] = request.POST['year']
                calendar['month'] = request.POST['month']

                first_date = datetime.date(int(request.POST['year']),
                                           int(request.POST['month']),
                                           1)  # First day in the month
                num_days = monthrange(
                    int(request.POST['year']),
                    int(request.POST['month']))  # Number of days in month
                last_date = datetime.date(int(request.POST['year']),
                                          int(request.POST['month']),
                                          num_days[1])  # Last day in month

                calendar['days'].append(
                    num_days[1]
                )  # Provide number of days in month for calendar

                for day in range(num_days[1]):  # Prepare slots for each day
                    calendar['days'].append('')

                objects = user.check_set.filter(
                    Date__range=(first_date,
                                 last_date))  # Retrieve data from database

                for day in objects:  # Fill in data into calendar
                    calendar['days'].insert(
                        day.getDate().day,
                        day.getRating(
                            user.getSymKey(request.session['PrivKey'])))

    else:
        try:
            user = login.models.User.objects.filter(
                pk=request.session['UserId'])[0]  # Session info of user
        except IndexError:
            return HttpResponseRedirect(
                reverse('login:Login'))  # Session info of user

        today = datetime.date.today()
        calendar['year'] = str(today.year)
        calendar['month'] = str(today.month)

        first_date = datetime.date(today.year, today.month,
                                   1)  # First day in the month
        num_days = monthrange(today.year,
                              today.month)  # Number of days in month
        last_date = datetime.date(today.year, today.month,
                                  num_days[1])  # Last day in month

        calendar['days'].append(
            num_days[1])  # Provide number of days in month for calendar

        for day in range(num_days[1]):  # Prepare slots for each day
            calendar['days'].append('')

        objects = user.check_set.filter(
            Date__range=(first_date, last_date))  # Retrieve data from database

        for day in objects:  # Fill in data into calendar
            calendar['days'].insert(
                day.getDate().day,
                day.getRating(user.getSymKey(request.session['PrivKey'])))

    check_lang = get_lang(sections=["check"])

    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'global_alerts': global_alerts,  # Sending the alerts to template.
        'back': UNIVERSAL_LANG["universal"]["back"],
        'check': check_lang["check"],
        'calendar': calendar,
        'template': 'base.html'
    }
    try:
        user = login.models.User.objects.filter(
            pk=request.session['UserId'])[0]  # Session info of user
    except IndexError:
        return HttpResponseRedirect(
            reverse('login:Login'))  # Session info of user
    new_entry("g1",
              user.getAnonId(request.session['PrivKey']),
              "check",
              role=request.session['Role'])
    return render(request, 'check/green_case.html', args)
Пример #8
0
def step_view(request, step):
    """Main Save.me Plan view. Handles all interfaces and saving to database for each step.

    step=Current step, is between 0-15. 0, 5, 10, 15 is Part A, B, C, D
    And those between is the actual steps for Save.me Plan ex 1=A1, 7=B2...

    post variables:
    step 1,2,3,4,5,6,7,9:
    choosen_item = A text used for autofilling textarea.
    describe = Text a user enters and want to save on step.
    rating = A given rating to describe

    step:8
    bad = a bad thing to replace
    good = A good thing to replace the the bad thing

    if bad == other
    use bad_other
    if good = other
    use good_other

    step: 13
    place = a place to go
    """
    if not 'UserId' in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))
    elif request.session["Role"] != "User":
        return HttpResponseRedirect(reverse('userprofile:Profile'))

    prepare.tools.delete_temp_files(request.session)
    try:
        user = User.objects.filter(pk=request.session['UserId'])[0]
    except IndexError:
        return HttpResponseRedirect(reverse('login:Login'))

    symkey = user.getSymKey(request.session['PrivKey'])

    savemeplan_lang = get_lang(sections=['savemeplan'])
    title = savemeplan_lang['savemeplan']['title']
    template = ''  # Diffrent step sets diffrent template
    content = {  # Main variable for each step content
        'describe_info': savemeplan_lang['savemeplan']['long_texts']['describe_info'],
        'current_step': step,
        'history': savemeplan_lang['savemeplan']['history'],
    }

    next_step = savemeplan_lang['savemeplan']['next_step']

    if 'reset' in request.GET.keys(
    ) and 'SaveMePlanId' in request.session.keys():
        del request.session[
            'SaveMePlanId']  # User is now done with this session.

    if step not in range(0, 17):  # If someone enters a non existing step
        step = 0

    if request.POST:
        if 'choosen_item' in request.POST.keys():
            content["textarea_text"] = request.POST['choosen_item']
        else:  # User is going to next step.
            steps = {
                1: 'A1',
                2: 'A2',
                3: 'A3',
                4: 'A4',
                6: 'B1',
                7: 'B2',
                8: 'B3',
                9: 'B4',
                11: 'C1',
                12: 'C2',
                13: 'C3',
                14: 'C4',
            }
            if 'SaveMePlanId' not in request.session.keys():

                last_savemeplan = user.savemeplan_set.order_by(
                    'SaveMePlanId').reverse()
                if len(last_savemeplan) != 0:
                    request.session['SaveMePlanId'] = last_savemeplan[
                        0].SaveMePlanId + 1  # Increase SaveMePlanId with one.
                else:
                    request.session['SaveMePlanId'] = 0

            current_smp_session = user.savemeplan_set.filter(
                SaveMePlanId=request.session['SaveMePlanId'])
            done_steps = savemeplan.tools.decrypt_steps(
                current_smp_session, symkey)

            found_id = -1
            for item in done_steps:
                if item[1] == steps[step]:
                    found_id = item[0]

            if found_id == -1:
                savemeplan_step = SaveMePlan(
                    SaveMePlanId=request.session['SaveMePlanId'], UserId=user)
            else:  # User is changing on a previously saved step
                savemeplan_step = SaveMePlan.objects.filter(pk=found_id)[0]

            if step in [1, 2, 3, 4, 6, 7,
                        9]:  # Is using step_default.html template
                if len(request.POST['describe']) != 0:
                    if found_id == -1:
                        savemeplan_step.setStep(
                            symkey,
                            steps[step])  # Save step as a user reads it

                    if 'describe' in request.POST.keys():
                        if len(request.POST['describe']) != 0:
                            if len(request.POST['describe']) <= 64:
                                savemeplan_step.setText(
                                    symkey, request.POST['describe'])
                            else:
                                savemeplan_step.setText(
                                    symkey, request.POST['describe'][:64])
                                tools.global_alerts.add_alert(
                                    request, 'warning',
                                    UNIVERSAL_LANG['universal']['warning'],
                                    savemeplan_lang['savemeplan']['long_texts']
                                    ['text_to_long'])
                        elif found_id == -1:
                            savemeplan_step.setText(symkey, 'EMPTY')
                    elif found_id == -1:
                        savemeplan_step.setText(symkey, 'EMPTY')

                    if 'rating' in request.POST.keys():
                        if len(request.POST['rating']) != 0:
                            savemeplan_step.setValue(symkey,
                                                     request.POST['rating'])
                        elif found_id == -1:
                            savemeplan_step.setValue(symkey, '-1')
                    elif found_id == -1:
                        savemeplan_step.setValue(symkey, '-1')

                    savemeplan_step.setTime(symkey, str(int(time.time())))

                    savemeplan_step.save()
                elif found_id != -1:
                    savemeplan_step.delete()

            elif step == 8:  # Replace a bad thing with a good thing step.
                if 'bad' and 'good' in request.POST.keys():

                    if (((request.POST['bad'] == 'bad_other'
                          and len(request.POST['bad_other']) != 0) and
                         (request.POST['good'] == 'good_other'
                          and len(request.POST['good_other']) != 0))
                            or request.POST['bad'] != 'bad_other'
                            or request.POST['good'] != 'good_other'):
                        if found_id == -1:
                            savemeplan_step.setStep(
                                symkey,
                                steps[step])  # Save step as a user reads it

                        replace = ''  # Will have format <bad>;<good> IF one of them is empty they will be replaced by EMPTY

                        if 'bad' in request.POST.keys():
                            if request.POST['bad'] != 'other':
                                if len(request.POST['bad']) <= 64:
                                    replace = f"{request.POST['bad']};"
                                else:
                                    replace = f"{request.POST['bad'][:64]};"
                                    tools.global_alerts.add_alert(
                                        request, 'warning',
                                        UNIVERSAL_LANG['universal']['warning'],
                                        savemeplan_lang['savemeplan']
                                        ['long_texts']['text_to_long'])

                            else:
                                if len(request.POST['bad_other']) != 0:
                                    if len(request.POST['bad_other']) <= 64:
                                        replace = f"{request.POST['bad_other']};"
                                    else:
                                        replace = f"{request.POST['bad_other'][:64]};"
                                        tools.global_alerts.add_alert(
                                            request, 'warning',
                                            UNIVERSAL_LANG['universal']
                                            ['warning'],
                                            savemeplan_lang['savemeplan']
                                            ['long_texts']['text_to_long'])

                                else:
                                    replace = 'EMPTY;'
                        else:
                            replace = 'EMPTY;'

                        if 'good' in request.POST.keys():
                            if request.POST['good'] != 'other':
                                if len(request.POST['good']) <= 64:
                                    replace = f"{replace}{request.POST['good']}"
                                else:
                                    replace = f"{request.POST['good'][:64]};"
                                    tools.global_alerts.add_alert(
                                        request, 'warning',
                                        UNIVERSAL_LANG['universal']['warning'],
                                        savemeplan_lang['savemeplan']
                                        ['long_texts']['text_to_long'])

                            else:
                                if len(request.POST['good_other']) != 0:
                                    if len(request.POST['good_other']) <= 64:
                                        replace = f"{replace}{request.POST['good_other']}"
                                    else:
                                        replace = f"{request.POST['good_other'][:64]};"
                                        tools.global_alerts.add_alert(
                                            request, 'warning',
                                            UNIVERSAL_LANG['universal']
                                            ['warning'],
                                            savemeplan_lang['savemeplan']
                                            ['long_texts']['text_to_long'])
                                else:
                                    replace = f"{replace}EMPTY"

                        else:
                            replace = f"{replace}EMPTY"
                        if replace != 'EMPTY;EMPTY':
                            savemeplan_step.setText(symkey, replace)
                            savemeplan_step.setValue(symkey, '-1')
                            savemeplan_step.setTime(symkey,
                                                    str(int(time.time())))
                            savemeplan_step.save()
                    elif found_id != -1:
                        savemeplan_step.delete()
                elif found_id != -1:
                    savemeplan_step.delete()

            elif step == 13:  # Go to a safe place step
                if ('place' in request.POST.keys()
                        and (request.POST['place'] != 'other' or
                             (request.POST['place'] == 'other'
                              and len(request.POST['place_other']) != 0))):
                    if found_id == -1:
                        savemeplan_step.setStep(
                            symkey,
                            steps[step])  # Save step as a user reads it

                    goto = ''

                    if 'place' in request.POST.keys():
                        if request.POST['place'] != 'other':
                            goto = request.POST['place']

                        else:
                            if len(request.POST['place_other']) != 0:
                                goto = request.POST['place_other']
                            else:
                                goto = 'EMPTY'

                    else:
                        goto = 'EMPTY'

                    if found_id == -1:
                        if len(goto) <= 64:
                            savemeplan_step.setText(symkey, goto)
                        else:
                            savemeplan_step.setText(symkey, goto[:64])
                            tools.global_alerts.add_alert(
                                request, 'warning',
                                UNIVERSAL_LANG['universal']['warning'],
                                savemeplan_lang['savemeplan']['long_texts']
                                ['text_to_long'])

                    savemeplan_step.setValue(symkey, '-1')
                    savemeplan_step.setTime(symkey, str(int(time.time())))

                    savemeplan_step.save()
                elif found_id != -1:
                    savemeplan_step.delete()

            return HttpResponseRedirect(
                reverse('savemeplan:Step', args=(step + 1, )))

    if step == 0:  # Part A
        new_entry("g1",
                  user.getAnonId(request.session['PrivKey']),
                  f"save",
                  role=request.session['Role'])

        template = 'savemeplan/part.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][0]}"  # Tab title
        content[
            'title'] = f"{savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][0]}: {savemeplan_lang['savemeplan']['part_a']}"
        content['part'] = 'A'

        content['step_1'] = (
            1,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][1]}: {savemeplan_lang['savemeplan']['mysit'].upper()}",
            STEP_COLORS['A1'])
        content['step_2'] = (
            2,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][2]}: {savemeplan_lang['savemeplan']['myemo'].upper()}",
            STEP_COLORS['A2'])
        content['step_3'] = (
            3,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][3]}: {savemeplan_lang['savemeplan']['mytho'].upper()}",
            STEP_COLORS['A3'])
        content['step_4'] = (
            4,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][4]}: {savemeplan_lang['savemeplan']['mybeh'].upper()}",
            STEP_COLORS['A4'])

    elif step == 1:  # Step A1

        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][1]}"
        content['part'] = 'A'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][1]} - {savemeplan_lang['savemeplan']['long_texts']['steps'][0]}"
        content['step'] = savemeplan_lang['savemeplan']['mysit']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'sitrate']
        top_5 = savemeplan.tools.top5_options(user, 'A1',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'A1')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'sittext']
        content['rate'] = savemeplan_lang['savemeplan'][
            'rate_sit']  # Rating text
        content['1'] = savemeplan_lang['savemeplan'][
            'unbearable']  # Rating 1 text
        content['9'] = savemeplan_lang['savemeplan']['nomild']  # Rating 9 text

        content['step_bg'] = STEP_COLORS[
            'A1']  # Colors on title box and step part

    elif step == 2:  # Step A2

        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][2]}"
        content['part'] = 'A'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][2]} - {savemeplan_lang['savemeplan']['long_texts']['steps'][0]}"
        content['step'] = savemeplan_lang['savemeplan']['myemo']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'emorate']
        top_5 = savemeplan.tools.top5_options(user, 'A2',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'A2')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'emotext']
        content['rate'] = savemeplan_lang['savemeplan'][
            'rate_emo']  # Rating text
        content['1'] = savemeplan_lang['savemeplan'][
            'unbearable']  # Rating 1 text
        content['9'] = savemeplan_lang['savemeplan']['nomild']  # Rating 9 text

        content['step_bg'] = STEP_COLORS[
            'A2']  # Colors on title box and step part

    elif step == 3:  # Step A3

        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][3]}"
        content['part'] = 'A'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][3]} - {savemeplan_lang['savemeplan']['long_texts']['steps'][0]}"
        content['step'] = savemeplan_lang['savemeplan']['mytho']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'thorate']
        top_5 = savemeplan.tools.top5_options(user, 'A3',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'A3')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'thotext']
        content['rate'] = savemeplan_lang['savemeplan']['rate_tho']
        content['1'] = savemeplan_lang['savemeplan']['unbearable']
        content['9'] = savemeplan_lang['savemeplan']['nomild']

        content['step_bg'] = STEP_COLORS['A3']

    elif step == 4:  # Step a 4
        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][4]}"
        content['part'] = 'A'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][4]} - {savemeplan_lang['savemeplan']['long_texts']['steps'][0]}"
        content['step'] = savemeplan_lang['savemeplan']['mybeh']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'behrate']
        top_5 = savemeplan.tools.top5_options(user, 'A4',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'A4')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'emotext']
        content['rate'] = savemeplan_lang['savemeplan']['rate_beh']
        content['1'] = savemeplan_lang['savemeplan']['unbearable']
        content['9'] = savemeplan_lang['savemeplan']['nomild']

        content['step_bg'] = STEP_COLORS['A4']

    elif step == 5:  # Part B

        template = 'savemeplan/part.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][1]}"
        content['part'] = 'B'

        content[
            'title'] = f"{savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][1]}: {savemeplan_lang['savemeplan']['part_b']}"
        content['step_1'] = (
            6,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][5]}: {savemeplan_lang['savemeplan']['calm'].upper()}",
            STEP_COLORS['B1'])
        content['step_2'] = (
            7,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][6]}: {savemeplan_lang['savemeplan']['rout'].upper()}",
            STEP_COLORS['B2'])
        content['step_3'] = (
            8,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][7]}: {savemeplan_lang['savemeplan']['repl'].upper()}",
            STEP_COLORS['B3'])
        content['step_4'] = (
            9,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][8]}: {savemeplan_lang['savemeplan']['prot'].upper()}",
            STEP_COLORS['B4'])

    elif step == 6:  # Step B1

        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][5]}"
        content['part'] = 'B'

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'calrate']
        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][5]} - {savemeplan_lang['savemeplan']['calmtitle'].upper()}"
        content['step'] = savemeplan_lang['savemeplan']['calm_step']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'calrate']
        top_5 = savemeplan.tools.top5_options(user, 'B1',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'B1')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'calmtext']
        content['rate'] = savemeplan_lang['savemeplan']['rate_calm']
        content['1'] = savemeplan_lang['savemeplan']['unbearable']
        content['9'] = savemeplan_lang['savemeplan']['nomild']

        content['step_bg'] = STEP_COLORS['B1']

    elif step == 7:  # Step B2
        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][6]}"
        content['part'] = 'B'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][6]} - {savemeplan_lang['savemeplan']['routtitle'].upper()}"
        content['step'] = savemeplan_lang['savemeplan']['my_route']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'rourate']
        top_5 = savemeplan.tools.top5_options(user, 'B2',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'B2')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'routtext']
        content['rate'] = savemeplan_lang['savemeplan']['rate_rout']
        content['1'] = savemeplan_lang['savemeplan']['yes']
        content['4'] = savemeplan_lang['savemeplan']['no']

        content['step_bg'] = STEP_COLORS['B2']

    elif step == 8:  # Step B3

        template = 'savemeplan/step_replace.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][7]}"
        content['part'] = 'B'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][7]} - {savemeplan_lang['savemeplan']['repltitle']}"
        content['step'] = savemeplan_lang['savemeplan']['repltitle']

        default_bad = savemeplan_lang['savemeplan']['long_texts']['repbad']
        default_good = savemeplan_lang['savemeplan']['long_texts']['repgood']
        top_5 = savemeplan.tools.top_5_bad_good(user, symkey)
        content['options'] = list()

        if 'SaveMePlanId' in request.session.keys():
            text = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey,
                'B3')[0].split(';')
            if len(text) == 2:
                content['text_bad'] = text[0]
                content['text_good'] = text[1]

        if len(top_5[0]) < 5:
            top_5[0] = savemeplan.tools.extend_top5(top_5[0], default_bad)

        if len(top_5[1]) < 5:
            top_5[1] = savemeplan.tools.extend_top5(top_5[1], default_good)

        for i in range(len(top_5[0])):
            content['options'].append((top_5[0][i], top_5[1][i]))

        content['dangerous'] = savemeplan_lang['savemeplan']['put_away']
        content['good'] = savemeplan_lang['savemeplan']['find_safe']
        content['other'] = savemeplan_lang['savemeplan']['other']
        content['other_placeholder'] = savemeplan_lang['savemeplan']['repladd']

        content['step_bg'] = STEP_COLORS['B3']

    elif step == 9:  # Step B4

        template = 'savemeplan/step_default.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][8]}"
        content['part'] = 'B'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][8]} - {savemeplan_lang['savemeplan']['prot_title']}"
        content['step'] = savemeplan_lang['savemeplan']['my_values']

        default_options = savemeplan_lang['savemeplan']['long_texts'][
            'protect']
        top_5 = savemeplan.tools.top5_options(user, 'B4',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys(
        ):  # Check if user allready submittet a value.
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'B4')

        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'name_values']
        content['rate'] = savemeplan_lang['savemeplan']['rate_values']
        content['1'] = '0 %'
        content['9'] = '100 %'

        # Colors on part title and descibe parts.
        content['step_bg'] = STEP_COLORS['B4']

    elif step == 10:  # Part C

        template = 'savemeplan/part.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][2]}"
        content['part'] = 'C'

        content[
            'title'] = f"{savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][2]}: {savemeplan_lang['savemeplan']['part_c']}"
        content['step_1'] = (
            11,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][9]}: {savemeplan_lang['savemeplan']['smsto'].upper()}",
            STEP_COLORS['C1'])
        content['step_2'] = (
            12,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][10]}: {savemeplan_lang['savemeplan']['call'].upper()}",
            STEP_COLORS['C2'])
        content['step_3'] = (
            13,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][11]}: {savemeplan_lang['savemeplan']['gosafe'].upper()}",
            STEP_COLORS['C3'])
        content['step_4'] = (
            14,
            f"{savemeplan_lang['savemeplan']['steps'][0]} {savemeplan_lang['savemeplan']['steps'][12]}: {savemeplan_lang['savemeplan']['indanger'].upper()} {UNIVERSAL_LANG['universal']['emergency_number']}",
            STEP_COLORS['C4'])

    elif step == 11:  # Step C1

        template = 'savemeplan/step_message.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][9]}"
        content['part'] = 'C'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][9]} - {savemeplan_lang['savemeplan']['sms_chat']}"

        all_contacts_enc = user.contacts_set.all()
        all_contacts_dec = []

        for contact in all_contacts_enc:
            name = contact.getName(request.session['PrivKey'])
            nr = contact.getPhonenumber(request.session['PrivKey'])
            available = contact.getAvailable(request.session['PrivKey'])
            all_contacts_dec.append({
                'name': name,
                'number': nr,
                'available': available
            })

        content['contacts_list'] = all_contacts_dec

        content['code_red'] = savemeplan_lang['savemeplan']['codered'].upper()
        content['code_orange'] = savemeplan_lang['savemeplan']['codeor'].upper(
        )
        content['code_yellow'] = savemeplan_lang['savemeplan'][
            'codeyel'].upper()
        content['code_blue'] = savemeplan_lang['savemeplan']['codeblue'].upper(
        )
        content['code_green'] = savemeplan_lang['savemeplan']['codegre'].upper(
        )

        content['contacts'] = savemeplan_lang['savemeplan'][
            'contacts']  # Word contacts
        content['message'] = savemeplan_lang['savemeplan']['long_texts'][
            'messages']  # Code texts
        content['chat'] = savemeplan_lang['savemeplan']['long_texts'][
            'chat']  # word chat
        content['chat_website'] = savemeplan_lang['savemeplan']['chat_site']
        content['available'] = savemeplan_lang['savemeplan']['available']

        # Colors on part title and descibe parts.
        content['step_bg'] = STEP_COLORS['C1']

    elif step == 12:  # Step C2

        template = 'savemeplan/step_call.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][10]}"
        content['part'] = 'C'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][10]} - {savemeplan_lang['savemeplan']['callhelper']}"

        all_contacts_enc = user.contacts_set.all()
        all_contacts_dec = []

        for contact in all_contacts_enc:
            name = contact.getName(request.session['PrivKey'])
            nr = contact.getPhonenumber(request.session['PrivKey'])
            available = contact.getAvailable(request.session['PrivKey'])
            all_contacts_dec.append({
                'name': name,
                'number': nr,
                'available': available
            })

        content['contacts_list'] = all_contacts_dec
        content['available'] = savemeplan_lang['savemeplan']['available']

        content['step_bg'] = STEP_COLORS['C2']

    elif step == 13:  # Step C3

        template = 'savemeplan/step_gosafe.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][11]}"
        content['part'] = 'C'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][11]} - {savemeplan_lang['savemeplan']['safe']}"
        content['step'] = savemeplan_lang['savemeplan']['go_to_safe']

        default_options = savemeplan_lang['savemeplan']['long_texts']['safe']
        top_5 = savemeplan.tools.top5_options(user, 'C3',
                                              symkey)  # Get most used options
        if len(top_5) < 5:
            top_5 = savemeplan.tools.extend_top5(top_5, default_options)
        content['options'] = top_5

        if 'SaveMePlanId' in request.session.keys():
            content['data'] = savemeplan.tools.get_step_data(
                request.session['SaveMePlanId'], user, symkey, 'C3')

        content['other_placeholder'] = savemeplan_lang['savemeplan'][
            'add_safe']
        content['other'] = savemeplan_lang['savemeplan']['other']
        content['describe_placeholder'] = savemeplan_lang['savemeplan'][
            'thotext']

        content['step_bg'] = STEP_COLORS['C3']

    elif step == 14:  # Step C4

        template = 'savemeplan/step_sos.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][12]}"
        content['part'] = 'C'

        content[
            'step_title'] = f"{savemeplan_lang['savemeplan']['steps'][0].upper()} {savemeplan_lang['savemeplan']['steps'][12]} - {savemeplan_lang['savemeplan']['if_danger']}"
        content['step'] = savemeplan_lang['savemeplan']['cant_talk']

        content['sos_1'] = savemeplan_lang['savemeplan']['sos_1']
        content['sos_2'] = savemeplan_lang['savemeplan']['sos_2']
        content['sos_3'] = savemeplan_lang['savemeplan']['sos_3']

        content['call'] = savemeplan_lang['savemeplan']['call_sos']
        content['repeat'] = savemeplan_lang['savemeplan']['repeat_smp']
        content['emergency_nr'] = UNIVERSAL_LANG['universal'][
            'emergency_number']

        # Colors on part title and descibe parts.
        content['step_bg'] = STEP_COLORS['C4']

    elif step == 15:  # Summary
        template = 'savemeplan/step_summary.html'
        title = f"{title} - {savemeplan_lang['savemeplan']['part'].upper()} {savemeplan_lang['savemeplan']['parts'][3]}"
        content['part'] = 'D'

        STEP_TITLES = {
            'A1': savemeplan_lang['savemeplan']['mysit'],
            'A2': savemeplan_lang['savemeplan']['myemo'],
            'A3': savemeplan_lang['savemeplan']['mytho'],
            'A4': savemeplan_lang['savemeplan']['mybeh'],
            'B1': savemeplan_lang['savemeplan']['calm'],
            'B2': savemeplan_lang['savemeplan']['rout'],
            'B3': savemeplan_lang['savemeplan']['repl'],
            'B4': savemeplan_lang['savemeplan']['prot'],
            'C3': savemeplan_lang['savemeplan']['gosafe'],
        }

        content['step_title'] = savemeplan_lang['savemeplan']['summary']
        content['download'] = savemeplan_lang['savemeplan']['download']
        content['rating'] = savemeplan_lang['savemeplan']['rating']

        if 'SaveMePlanId' in request.session.keys():
            content['steps'] = savemeplan.tools.get_savemeplan_items(
                user, symkey, request.session['SaveMePlanId'])
            del request.session[
                'SaveMePlanId']  # User is now done with this session.
        else:
            content['old'] = savemeplan_lang['savemeplan']['long_texts'][
                'old_session']
            content['steps'] = savemeplan.tools.get_savemeplan_items(
                user, symkey)

        for smp_step in content['steps']:
            smp_step.append(STEP_COLORS[smp_step[0]])
            smp_step.append(STEP_TITLES[smp_step[0]])

    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]
        ["titles"],  # This is the menu-titles text retrieved from language file.,
        'global_alerts': global_alerts,  # Sending the alerts to template.
        'title': title,
        'content': content,
        'next_step': next_step,
        'back': UNIVERSAL_LANG['universal']['back'],
        'history': savemeplan_lang['savemeplan']['history'],
        'feature_title': savemeplan_lang['savemeplan']['title']
    }
    new_entry("s3",
              user.getAnonId(request.session['PrivKey']),
              f"step {step}",
              role=request.session['Role'])
    return render(request, template, args)
Пример #9
0
def memory_view(request, id):

    if not 'UserId' in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))

    try:
        user = login.models.User.objects.filter(
            pk=request.session["UserId"])[0]
    except IndexError:
        return HttpResponseRedirect(reverse('login:Login'))
    userPrivkey = request.session["PrivKey"]
    prepare_lang = get_lang(sections=["prepare"])
    profView = False
    content = dict()
    try:
        memory = prepare.models.Media.objects.filter(pk=id)[0]
    except Exception as e:
        if request.session['Role'] == 'User':
            return HttpResponseRedirect(
                reverse('prepare:menu'))  #Http404("Memory does not exist!")
        else:
            return HttpResponseRedirect(reverse('professionals:clients'))

    if memory.UserId.UserId != request.session["UserId"]:
        # User doesn't belong here
        mediaOwnerId = memory.getUserId().getUid()
        try:
            userPrivkey = userprofile.tools.shares_data_with(
                mediaOwnerId, request.session["UserId"], userPrivkey,
                'media').decode("utf-8")
        except AttributeError:
            if request.session['Role'] == 'User':
                return HttpResponseRedirect(reverse(
                    'prepare:menu'))  #Http404("Memory does not exist!")
            else:
                return HttpResponseRedirect(reverse('professionals:clients'))
        else:
            if userPrivkey:
                user = mediaOwnerId = memory.getUserId()
                profView = True
            else:
                if request.session['Role'] == 'User':
                    return HttpResponseRedirect(reverse(
                        'prepare:menu'))  #Http404("Memory does not exist!")
                else:
                    return HttpResponseRedirect(
                        reverse('professionals:clients'))

    prepare.tools.delete_temp_files(request.session)

    content["id"] = id
    content["title"] = memory.getMediaTitle(userPrivkey)
    content["type"] = memory.getMemory(userPrivkey)
    content["size"] = int(memory.getMediaSize(userPrivkey)) / 1000000

    url = ""
    memtype = ""
    file = ""
    unidentified_url = ""

    local_url_pattern = re.compile(
        "^[a-zA-Z0-9]{40}\/([a-zA-Z0-9]{40})$"
    )  # Pattern for local files such as video, photo or sound

    if memory.MediaText:
        content["text"] = memory.getMediaText(userPrivkey)
    if memory.MediaLink:
        unidentified_url = memory.getLink(userPrivkey)

    if "youtube.com" in unidentified_url:
        memtype = "youtube"
        index = unidentified_url.find("?v=")
        done = False
        content[memtype] = ""

        for i in range(index + 3,
                       len(unidentified_url)):  # get video id of youtube video
            if unidentified_url[i] == "&":
                done = True
            if not done:
                content[memtype] += unidentified_url[i]

    elif "youtu.be" in unidentified_url:
        memtype = "youtube"
        content[memtype] = unidentified_url.split("/")[
            -1]  # get video id of youtube video

    elif local_url_pattern.match(unidentified_url):
        url = unidentified_url
        memtype = "photo/video/sound"

    else:
        memtype = "url_other"
        content[memtype] = unidentified_url

    if request.GET and "delete" in request.GET.keys():

        if memtype == "photo/video/sound":
            delete_file(url)
        redirect_path = memory.getMemory(
            userPrivkey)  # To know which step to redirect to.
        memory.delete()
        tools.global_alerts.add_alert(
            request, 'success', UNIVERSAL_LANG["universal"]["info"],
            prepare_lang["prepare"]["long_texts"]["alerts"]["memory_deleted"])

        new_entry("m2",
                  user.getAnonId(userPrivkey),
                  url.split("/")[-1],
                  role=request.session['Role'])
        if redirect_path == "s":
            return HttpResponseRedirect(
                reverse('prepare:menu-page', args=(3, )))
        else:
            return HttpResponseRedirect(
                reverse('prepare:menu-page', args=(4, )))

    if memtype == "photo/video/sound":
        photo_extenssions = [  # Some of the more popular allowed formats
            # Photos
            ".JPG",
            ".JPEG",
            ".EXIF",
            ".GIF",
            ".BMP",
            ".PNG",
            ".WEBP",
            ".HEIF",
        ]

        video_extenssions = [
            ".WEBM",
            ".MPG",
            ".MP2",
            ".MPEG",
            ".MPE",
            ".MPV",
            ".OGG",
            ".MP4",
            ".M4P",
            ".M4V",
            ".AVI",
            ".WMV",
            ".MOV",
            ".QT",
            ".FLV",
            ".SWF",
            ".AVCHD",
        ]

        sound_extenssions = [
            ".AA", ".AAX", ".AIFF", ".ALAC", ".DVF", ".M4A", ".M4B", ".MMF",
            ".MP3", ".MPC", ".OPUS", ".RF64", ".MAV", ".WMA", ".WV"
        ]
        file_type = ""

        try:
            file = open_file(user.getSymKey(userPrivkey), url)

        except RuntimeError as e:
            tools.global_alerts.add_alert(
                request, 'danger', UNIVERSAL_LANG["universal"]["error"],
                prepare_lang["prepare"]["long_texts"]["alerts"]
                ["checksum_error"])
            return HttpResponseRedirect(reverse('prepare:menu'))

        for line in file[0].split("\n"):
            splitline = line.split(":")
            if splitline[0] == "filetype":
                file_type = splitline[1]

        if "." + file_type.upper() in photo_extenssions:
            memtype = "photo"
        elif "." + file_type.upper() in video_extenssions:
            memtype = "video"
        elif "." + file_type.upper() in sound_extenssions:
            memtype = "sound"
        else:
            memtype = "error"

        if memtype != "error":

            file_path = "temp/"
            file_name = str(time.time())
            file_name = "".join(file_name.split("."))

            try:
                default_storage.save(file_path + file_name + "." + file_type,
                                     ContentFile(file[1]))

                content[
                    memtype] = "media/" + file_path + file_name + "." + file_type  # Full path to media

                if "files_to_delete" in request.session.keys():
                    request.session["files_to_delete"].append(content[memtype])
                else:
                    request.session["files_to_delete"] = [content[memtype]]
            except Exception as e:
                tools.global_alerts.add_alert(
                    request, 'danger', UNIVERSAL_LANG["universal"]["error"],
                    prepare_lang["prepare"]["long_texts"]["alerts"]
                    ["could_not_open_file"])
                return HttpResponseRedirect(reverse('prepare:menu'))

    using_space = prepare_lang["prepare"]["long_texts"]["memory_size"].replace(
        "%mb%", str(int(content["size"])))
    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    template = "base_professionals.html" if request.session[
        "Role"] == "Professional" else "base.html"

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]
        ["titles"],  # This is the menu-titles text retrieved from language file.
        'global_alerts': global_alerts,  # Sending the alerts to template.
        "using_space": using_space,
        "content": content,
        "back": UNIVERSAL_LANG["universal"]["back"],
        'prepare': prepare_lang["prepare"],
        'profView': profView,
        'UserId': user.getUid(),
        "template": template
    }
    new_entry("m3",
              user.getAnonId(userPrivkey),
              url.split("/")[-1],
              role=request.session['Role'])

    return render(request, 'prepare/memory.html', args)
Пример #10
0
def menu_view(request, page=0):
    """Main view for the prepare app.
    If a diary entry is created on page 7 or 8, request.POST contains the following keys:
        date = Date of the diary entry, used for sorting
        text = Content of the diary entry

    request.GET is used to track which page should be displayed.
    """

    if not 'UserId' in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))
    if request.session['Role'] == 'Professional':
        return HttpResponseRedirect(reverse('professionals:clients'))

    prepare.tools.delete_temp_files(request.session)

    prepare_lang = get_lang(sections=["prepare"])
    template = 'prepare/menu.html'
    memories = []
    contacts = []
    diary = []
    try:
        user = login.models.User.objects.filter(
            pk=request.session["UserId"])[0]
    except IndexError:
        return HttpResponseRedirect(reverse('login:Login'))

    base_template = "base_professionals.html" if request.session[
        "Role"] == "Professional" else "base.html"

    if page == 1:
        template = 'prepare/1_howto.html'
    elif page == 2:
        template = 'prepare/2_practicebreathing.html'
    elif page == 3:
        memories = prepare.tools.show_all_memories(request.session['UserId'],
                                                   request.session['PrivKey'],
                                                   's')
        template = 'prepare/3_supportivememories.html'
    elif page == 4:
        memories = prepare.tools.show_all_memories(request.session['UserId'],
                                                   request.session['PrivKey'],
                                                   'd')
        template = 'prepare/4_destructivememories.html'
    elif page == 5:
        contacts = prepare.tools.show_contacts(request.session['UserId'],
                                               request.session['PrivKey'])
        template = 'prepare/5_contacts.html'
    elif page == 6:
        template = 'prepare/6_wheretocall.html'
    elif page == 7:
        symkey = user.getSymKey(request.session['PrivKey'])
        if request.method == 'POST':
            if 'date' in request.POST.keys() and 'text' in request.POST.keys():
                now = str(datetime.datetime.now())
                diary_entry = prepare.models.Diary(UserId=user)
                diary_entry.setAuthorId(symkey, request.session['UserId'])
                diary_entry.setAuthor(
                    symkey,
                    login.models.User.objects.filter(
                        UserId=request.session['UserId'])[0].getName(
                            request.session['PrivKey']))
                diary_entry.setDate(symkey, request.POST['date'])
                text = request.POST['text'] if len(
                    request.POST['text']
                ) <= 500 else request.POST['text'][0:500]
                diary_entry.setEntryType(symkey, 'Diary')
                diary_entry.setText(symkey, text)
                diary_entry.setTimestamp(symkey, now)
                diary_entry.save()
        diary = prepare.tools.show_diary(user.getUid(), symkey, 'Diary',
                                         request.session['UserId'])
        template = 'prepare/7_diary.html'
    elif page == 8:
        symkey = user.getSymKey(request.session['PrivKey'])
        if request.method == 'POST':
            if 'date' in request.POST.keys() and 'text' in request.POST.keys():
                now = str(datetime.datetime.now())
                diary_entry = prepare.models.Diary(UserId=user)
                diary_entry.setAuthorId(symkey, request.session['UserId'])
                diary_entry.setAuthor(
                    symkey,
                    login.models.User.objects.filter(
                        UserId=request.session['UserId'])[0].getName(
                            request.session['PrivKey']))
                diary_entry.setDate(symkey, request.POST['date'])
                text = request.POST['text'] if len(
                    request.POST['text']
                ) <= 500 else request.POST['text'][0:500]
                diary_entry.setEntryType(symkey, 'Notes')
                diary_entry.setText(symkey, text)
                diary_entry.setTimestamp(symkey, now)
                diary_entry.save()
        diary = prepare.tools.show_diary(user.getUid(), symkey, 'Notes',
                                         request.session['UserId'])
        template = 'prepare/8_therapynotes.html'
    else:
        #Science segment
        new_entry("g1",
                  user.getAnonId(request.session['PrivKey']),
                  "prep",
                  role=request.session['Role'])

        template = 'prepare/menu.html'

    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]["titles"],
        'global_alerts': global_alerts,
        'back': UNIVERSAL_LANG["universal"]["back"],
        'prepare': prepare_lang["prepare"],
        'nav': prepare_lang["prepare"]["nav"],
        'memories': memories,
        'contacts': contacts,
        'entries': diary,
        'template': base_template
    }

    if 0 < page < 9:
        new_entry("p3", user.getAnonId(request.session['PrivKey']),
                  f"step {page}")

    return render(request, template, args)
Пример #11
0
def add_memory_view(request):
    """View for adding memories.

    POST keys:
    title = The title of the memory. Required!
    media_text = Text. Optional!
    link = A url which can be youtube video or other urls. Optional!
    type = Memory type! Can be Music, Game, Video, Image, Phrase, Story, Award
    or Theme. Take the first and last letter as lower case and you get value
    from type (example mc is Music). Required!

    FILES keys:
    media = Can be image, video or song. Optional!
    """
    if not 'UserId' in request.session.keys(
    ):  # This is a check if a user is logged in.
        return HttpResponseRedirect(reverse('login:Login'))
    elif request.session["Role"] != "User":
        return HttpResponseRedirect(reverse('userprofile:Profile'))

    prepare.tools.delete_temp_files(request.session)

    prepare_lang = get_lang(sections=["prepare"])
    media_conf = get_conf(sections=["media"])["media"]
    alerts = {}

    mem_type = ""
    if "mem_type" in request.GET.keys():
        mem_type = request.GET['mem_type']
    elif "mem_type" in request.POST.keys():
        mem_type = request.POST['mem_type']
    else:
        mem_type = "s"

    if mem_type != "s" and mem_type != "d":
        mem_type = "s"

    allowed_extenssions = [  # Some of the more popular allowed formats
        #  Videos
        ".WEBM",
        ".MPG",
        ".MP2",
        ".MPEG",
        ".MPE",
        ".MPV",
        ".OGG",
        ".MP4",
        ".M4P",
        ".M4V",
        ".AVI",
        ".WMV",
        ".MOV",
        ".QT",
        ".FLV",
        ".SWF",
        ".AVCHD",

        # Photos
        ".JPG",
        ".JPEG",
        ".EXIF",
        ".GIF",
        ".BMP",
        ".PNG",
        ".WEBP",
        ".HEIF",
    ]

    media_type = ""  # Used for displaying url input or file input on page.
    if request.POST and "save" in request.POST.keys(
    ):  # Cant use method here because of two methods are used.
        if ('title' in request.POST.keys() and len(request.POST["title"]) <= 64
                and len(request.POST["title"]) > 0):

            with transaction.atomic():
                try:
                    user = login.models.User.objects.filter(
                        pk=request.session["UserId"])[0]
                except IndexError:
                    return HttpResponseRedirect(reverse('login:Login'))
                memory = user.media_set.create(
                )  # Create a Media entry with foreignkey this user.
                memory.setMediaTitle(user.getPubkey(), request.POST["title"])
                memory.setMediaSize(user.getPubkey(), 0)
                memory.setMemory(user.getPubkey(), mem_type)

                if 'type' in request.POST.keys() and len(
                        request.POST["type"]) > 0:
                    memory.setMediaType(user.getPubkey(), request.POST["type"])

                    if "link" in request.POST.keys():  # Optional
                        memory.setLink(user.getPubkey(), request.POST["link"])
                    elif "media" in request.FILES.keys():  # Optional

                        if (request.FILES["media"].size <
                                int(media_conf["max_size_mb"]) * 1000000
                                and "." + request.FILES["media"].name.split(
                                    ".")[-1].upper() in allowed_extenssions):

                            medias = user.media_set.exclude(
                                pk=memory.MediaId
                            )  # Get all memories exept current one.
                            total_space_used = 0
                            for media in medias:
                                total_space_used += int(
                                    media.getMediaSize(
                                        request.session["PrivKey"]))

                            if total_space_used + int(
                                    request.FILES["media"].size) <= int(
                                        media_conf["max_per_user"]) * 1000000:
                                try:
                                    file = save_file(
                                        user.getSymKey(
                                            request.session["PrivKey"]),
                                        request.FILES["media"].read(),
                                        user.getAnonId(
                                            request.session["PrivKey"]),
                                        upload_name=request.FILES["media"].name
                                    )

                                    memory.setMediaSize(
                                        user.getPubkey(),
                                        request.FILES["media"].size)
                                    memory.setLink(user.getPubkey(), file[0])
                                    new_entry(
                                        "m1",
                                        user.getAnonId(
                                            request.session["PrivKey"]),
                                        file[0].split("/")[-1])

                                except RuntimeError as e:
                                    alerts["file"] = prepare_lang["prepare"][
                                        "long_texts"]["alerts"]["file_to_big"]
                                    memory.delete()

                                except Exception as e:
                                    alerts["file"] = prepare_lang["prepare"][
                                        "long_texts"]["alerts"]["file_error"]
                                    memory.delete()

                            else:
                                alerts["file"] = prepare_lang["prepare"][
                                    "long_texts"]["alerts"]["not_enough_space"]
                                memory.delete()

                        else:
                            alerts["file"] = prepare_lang["prepare"][
                                "long_texts"]["alerts"]["file_to_big"]
                            memory.delete()

                    if 'media_text' in request.POST.keys() and len(
                            request.POST["media_text"]
                    ) <= 500 and not alerts:  # Optional
                        memory.setMediaText(user.getPubkey(),
                                            request.POST["media_text"])
                    elif len(request.POST["media_text"]) > 500:
                        alerts["text"] = prepare_lang["prepare"]["long_texts"][
                            "alerts"]["text_to_long"]

                    if not alerts and not request.GET:
                        memory.save()
                        tools.global_alerts.add_alert(
                            request, 'success',
                            UNIVERSAL_LANG["universal"]["success"],
                            prepare_lang["prepare"]["long_texts"]["alerts"]
                            ["memory_added"])

                        return HttpResponseRedirect(
                            reverse('prepare:memory',
                                    args=(memory.MediaId,
                                          )))  # Redirect to created memory

                else:  # If no type is entered
                    alerts["type"] = prepare_lang["prepare"]["long_texts"][
                        "alerts"]["no_type"]
                    memory.delete()

        else:  # If Title is either empty or too long
            if len(request.POST["title"]) >= 64:
                alerts["title"] = prepare_lang["prepare"]["long_texts"][
                    "alerts"]["title_to_long"]
            else:
                alerts["title"] = prepare_lang["prepare"]["long_texts"][
                    "alerts"]["no_title"]

        if "link" in request.POST.keys():  # Displaying text input type
            media_type = "url"
        elif "media" in request.FILES.keys():  # Displaying file input type
            media_type = "file"

    if request.GET:
        if "media_type" in request.GET.keys(
        ) and request.GET["media_type"] == "url":  # Display file input type
            media_type = "url"
        elif "media_type" in request.GET.keys(
        ) and request.GET["media_type"] == "file":  # Display text input type
            media_type = "file"

    global_alerts = []  # The variable which is sent to template
    if "global_alerts" in request.session.keys(
    ):  # Check if there is global alerts
        global_alerts = request.session[
            "global_alerts"]  # Retrive global alerts.
        request.session["global_alerts"] = []  # Reset

    args = {
        'menu_titles': UNIVERSAL_LANG["universal"]
        ["titles"],  # This is the menu-titles text retrieved from language file.
        'global_alerts': global_alerts,  # Sending the alerts to template.
        'back': UNIVERSAL_LANG["universal"]["back"],
        'media_type': media_type,
        'POST': request.POST,
        'prepare': prepare_lang["prepare"],
        'error': UNIVERSAL_LANG["universal"]["error"],
        'alerts': alerts,
        'max_file_size': int(media_conf["max_size_mb"]),
        'mem_type': mem_type
    }
    return render(request, 'prepare/add_memory.html', args)