Esempio n. 1
0
def fail_page_course(slug):
    """ The Course Buy report fail page. """
    data = PageDetails().course_page_info(slug)
    if data is False:
        abort(404)
    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    try:
        identity = session["Data"]["Email"]
    except KeyError:
        identity = ""

    if slug not in Database().get_users_access_data_from_db(identity):
        return redirect("/Course/{slug}".format(slug=slug))
    try:
        code = (request.args['auth_code'])
    except KeyError:
        return redirect("/Course/{slug}".format(slug=slug))
    return render_template("courses_and_days/fail_payment.html",
                           course=data[0],
                           days=data[1],
                           intro=data[2],
                           code=code)
Esempio n. 2
0
def upload_day_pic_ck():
    """ The Upload day Api. """
    if request.method == "POST":
        #slug = request.args.get('slug')
        #day = int(request.args.get('day'))
        #if Database().get_courses_data_from_db(slug) is False:
        #    abort(400)

        uploaded_image = request.files.get("upload")
        uploaded_image_bytes = uploaded_image.read()

        saved_picture_data = General(
        ).save_picture_of_day_of_course_not_in_specific_location(
            uploaded_image_bytes)

        location_image = saved_picture_data["image"]
        file_name = saved_picture_data["file_name"]
        location_image_href = saved_picture_data["href"]

        width, height = General().size_image_file(image_path=location_image)
        return {
            "uploaded": 1,
            "fileName": file_name,
            "url": location_image_href,
            "width": width,
            "height": height,
        }

    return ""
Esempio n. 3
0
def tools_index():
    """ The Tools page """
    posts_per_page = 9
    page = request.args.get("page")
    posts = Database().get_all_tools_data_db()
    last_page = len(posts) // posts_per_page
    if len(posts) - last_page * posts_per_page > 0:
        last_page += 1
    if page is None:
        page = 1
    else:
        try:
            page = int(page)
        except ValueError:
            page = 1
    if page < 1:
        return redirect("?page=1")
    limited_posts = (posts[(page - 1) * posts_per_page:page * posts_per_page])
    if limited_posts == [] and page != 1:
        return redirect("?page={}".format(last_page))
    return render_template(
        "tools/tools_index.html",
        posts=limited_posts,
        now_page=page,
        last_page=last_page,
        pagination=General().pagination_designer(page, last_page),
        days_till_now=General().days_passed_till_now(),
    )
Esempio n. 4
0
def start_free_course(slug):
    """ The free Course start page. """
    data = PageDetails().course_page_info(slug)
    if data is False:
        abort(404)
    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    try:
        identity = session["Data"]["Email"]
    except KeyError:
        identity = ""
    if slug in Database().get_users_access_data_from_db(identity):
        return redirect("/Course/{slug}".format(slug=slug))
    if not (slug in Database().get_users_access_data_from_db(identity)
            or data[0]["Free"] is True or data[0]["Now_Price"] == 0):
        return redirect("/Course/{slug}/buy".format(slug=slug))

    return render_template(
        "courses_and_days/start_course_card.html",
        course=data[0],
        days=data[1],
        intro=data[2],
    )
Esempio n. 5
0
def buy_course_redirect(slug):
    """ The Course redirect to zarinpall page. """
    data = PageDetails().course_page_info(slug)
    if data is False:
        abort(404)
    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    try:
        identity = session["Data"]["Email"]
    except KeyError:
        return redirect("/LogIn")

    if slug in Database().get_users_access_data_from_db(identity):
        return redirect("/Course/{slug}".format(slug=slug))

    client = Client(ZARINPAL_WEBSERVICE)
    result = client.service.PaymentRequest(
        MMERCHANT_ID, int(str(data[0]["Now_Price"]).replace(",", "")),
        description, 'email', "mobile",
        str(url_for('courses_and_days.buy_callback', _external=True)))

    if result.Status == 100:
        Database().add_payment_record_to_db(slug, data[0]["Now_Price"],
                                            identity, str(result.Authority))
        return redirect('https://www.zarinpal.com/pg/StartPay/' +
                        result.Authority)
    else:
        return 'Error'
Esempio n. 6
0
        def form_course(request):
            if request.form.get("slug") == "":
                return {"Message": "نام انگلیسی دوره را وارد کنید."}
            slug = request.form.get("slug").replace(" ", "-")
            try:
                uploaded_file = request.files["cover"]
            except:
                return {"Message": "تصویر را آپلود کنید."}
            try:
                length_of_course = int(request.form.get("len"))
            except ValueError:
                return {"Color": "red", "Message": "طول دوره باید عدد باشد."}
            if (Database().get_courses_data_from_db(slug) != ""
                    and uploaded_file.filename == ""):
                return {"Message": "تصویر را آپلود کنید."}
            result_pic = General().save_picture_of_course(
                slug, uploaded_file, length_of_course)
            if result_pic["Result"] is False:
                return result_pic
            if request.form.get("price-status") == "Free":
                price = "0"
                free = True
            else:
                price = request.form.get("price")
                free = False

            try:
                if request.form.get("soon") == "Soon":
                    days_till_open = int(request.form.get("date_open"))
                else:
                    days_till_open = 0
            except ValueError:
                General().remove_file(result_pic["path"])
                return {
                    "Color": "red",
                    "Message": "فاصله زمانی تا باز شدن باید عدد باشد."
                }
            try:
                int(price.replace(",", ""))
            except ValueError:
                General().remove_file(result_pic["path"])
                return {"Color": "red", "Message": "قیمت دوره باید عدد باشد."}

            message = Database().add_course_data_to_db(
                name=request.form.get("name"),
                slug=slug,
                description=request.form.get("description"),
                intro=None,
                image_href=result_pic["href"],
                now_price=int(price.replace(",", "")),
                length_of_course=int(request.form.get("len")),
                robbin=request.form.get("robbin"),
                free=free,
                days_till_publish=days_till_open)
            if message is not True:
                General().remove_file(result_pic["path"])
            return message
Esempio n. 7
0
def sub_course(slug, day):
    """ The one sub Course page. """
    # Day is a number or not
    try:
        day = int(day)
    except ValueError:
        abort(404)
    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    try:
        identity = session["Data"]["Email"]
    except KeyError:
        identity = ""

    # Get needed Data
    course_data = Database().get_courses_data_from_db(slug=slug)
    day_data = Database().get_one_day_data_of_courses_data_from_db(slug, day)

    # Check Length Day
    if int(day) > int(course_data["Length"]):
        return redirect("/Course/{}".format(slug))

    # Check if data is FALSE or not
    if course_data is False or day_data is False:
        abort(404)

    # Some days and courses in database might not have "Free" key, so we add them.
    if "Free" not in day_data:
        day_data["Free"] = False
    if "Free" not in course_data:
        course_data["Free"] = False

    # Check if day or course is not free and if we do not have access
    user_accesses = Database().get_users_access_data_from_db(identity)
    if (course_data["Free"] is not True and slug not in user_accesses
            and day_data["Free"] is False):
        return redirect("/Course/{}/info".format(slug))

    if slug in user_accesses and (user_accesses[slug] - 1 + day -
                                  General().days_passed_till_now()) > 0:
        return redirect("/Course/{}".format(slug))

    return render_template(
        "courses_and_days/day.html",
        course=PageDetails(session).course_page_info(slug)[0],
        day=PageDetails(session).sub_course_page_info_html(slug, day),
    )
Esempio n. 8
0
def info_course(slug):
    """ The one Course info page. """

    data = PageDetails().info_intro_course_page(slug)
    if data is False or "Intro" not in data:
        return redirect(url_for("courses_and_days.one_course", slug=slug))
    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    return render_template(
        "courses_and_days/course_info.html",
        course=data,
    )
Esempio n. 9
0
def register():
    form = RegisterForm()
    if request.method == "POST" and form.validate_on_submit():
        email = form.email.data
        user = General.query.filter_by(email=email).first()
        if user:
            flash("This user already exist. Log in instead!")
            return redirect(url_for("register_login_page.login"))

        hash_pw = generate_password_hash(form.password.data,
                                         method="pbkdf2:sha256",
                                         salt_length=8)

        new_user = General(
            name=form.name.data,
            password=hash_pw,
            email=form.email.data,
        )
        db.session.add(new_user)
        db.session.commit()

        login_user(new_user)

        return redirect(url_for("main_page.home"))

    return render_template("login_register.html", title="Register", form=form)
Esempio n. 10
0
def musics_index():
    """ The Music page """
    posts_per_page = 10
    page = request.args.get("page")
    posts = Database().get_all_musics_data_from_db()
    last_page = len(posts) // posts_per_page
    if len(posts) - last_page * posts_per_page > 0:
        last_page += 1
    if page is None:
        page = 1
    else:
        try:
            page = int(page)
        except ValueError:
            page = 1
    if page < 1:
        return redirect("?page=1")
    limited_posts = (posts[(page - 1) * posts_per_page:page * posts_per_page])
    if limited_posts == [] and page != 1:
        return redirect("?page={}".format(last_page))
    return render_template("music/music_posts.html",
                           posts=limited_posts,
                           now_page=page,
                           last_page=last_page,
                           pagination=General().pagination_designer(
                               page, last_page))
Esempio n. 11
0
def post_blog_options_admin():
    """ The edit/remove a Post for blog options Page as an admin. """

    return render_template(
        "admin/admin_edit_remove_post_options.html",
        posts=Database().get_blog_posts_data_from_db(),
        days_passed_till_now=General().days_passed_till_now())
Esempio n. 12
0
 def form_handler(request):
     if request.form.get("confirmation") == "True":
         message = Database().delete_post_blog_data_from_db(slug_post)
     else:
         message = {"Result": False, "Message": "حذف تایید نشده است."}
     General().remove_file_to_trash(
         "static/assets/images/blog/{slug}/".format(slug=slug_post))
     return message
Esempio n. 13
0
        def form_handler(request):
            text = request.form.get("text")
            slug = (request.form.get("name_eng").replace(" ", "-")).replace(
                "_", "-")
            if request.form.get("name_persian") == "":
                return {
                    "Result": False,
                    "Message": "نام فارسی دوره را وارد کنید."
                }
            if slug == "":
                return {
                    "Result": False,
                    "Message": "نام انگلیسی دوره را وارد کنید."
                }
            if text == "":
                return {"Result": False, "Message": "متن اصلی را وارد کنید."}
            uploaded_file = request.files["cover"]
            if uploaded_file.filename == "":
                return {"Message": "تصویر را آپلود کنید."}

            english_name = slug
            uploaded_image = request.files.get("cover")
            uploaded_image_bytes = uploaded_image.read()

            format_file = General().format_recognizer(uploaded_image_bytes)

            General().setup_blog_post_folder(slug)
            file_name = "blog-cover_" + english_name + "." + format_file
            location_image = "static/assets/images/blog/{}/".format(
                slug) + file_name
            location_image_href = "/static//assets/images/blog/{}/".format(
                slug) + file_name
            with open(location_image, "wb") as file:
                file.write(uploaded_image_bytes)

            General().image_resizer_using_imgp(location_image, 1500)
            General().image_optimizer_using_imgp(location_image)

            links_images = re.findall("src=[\"\'](.*?)[\"\']", text)
            for link in links_images:
                file_path = General().href_to_path(link)
                file_name = (file_path.split("/"))[-1]
                new_file_path = "static/assets/images/blog/{slug}/{file_name}".format(
                    slug=slug, file_name=file_name)
                new_file_href = "/static//assets/images/blog/{slug}/{file_name}".format(
                    slug=slug, file_name=file_name)
                General().move_file_path(file_path, new_file_path)
                text = text.replace(link, new_file_href)

            message = Database().add_post_blog_to_db(
                persian_name=request.form.get("name_persian"),
                eng_name=english_name,
                cover_href=location_image_href,
                text=text,
            )
            return message
Esempio n. 14
0
        def form_handler(request):
            slug = request.form.get("name_eng")
            if request.form.get("name_persian") == "":
                return {
                    "Result": False,
                    "Message": "نام فارسی دوره را وارد کنید."
                }
            if request.form.get("name_eng") == "":
                return {
                    "Result": False,
                    "Message": "نام انگلیسی دوره را وارد کنید."
                }
            if request.form.get("text") == "":
                return {"Result": False, "Message": "متن اصلی را وارد کنید."}
            uploaded_file = request.files["cover"]
            if uploaded_file.filename != "":

                english_name = slug
                uploaded_image = request.files.get("cover")
                uploaded_image_bytes = uploaded_image.read()
                format_file = General().format_recognizer(uploaded_image_bytes)
                General().setup_blog_post_folder(slug)
                file_name = "blog-cover_" + english_name + "." + format_file
                location_image = "static/assets/images/blog/{}/".format(
                    slug) + file_name
                location_image_href = "/static//assets/images/blog/{}/".format(
                    slug) + file_name
                with open(location_image, "wb") as file:
                    file.write(uploaded_image_bytes)
                General().image_resizer_using_imgp(location_image, 1500)
                General().image_optimizer_using_imgp(location_image)
            else:
                location_image_href = post["Cover"]

            message = Database().edit_post_blog_to_db(
                old_enlish_name=slug_post,
                persian_name=request.form.get("name_persian"),
                eng_name=(request.form.get("name_eng").replace(" ",
                                                               "-")).replace(
                                                                   "_", "-"),
                cover_href=location_image_href,
                text=request.form.get("text"),
            )
            return message, (request.form.get("name_eng").replace(
                " ", "-")).replace("_", "-")
Esempio n. 15
0
File: blog.py Progetto: urgemag/urge
def blog_post(english_name):
    """ One post from Blog """
    post = Database().get_blog_post_data_from_db(english_name)
    if post is False:
        abort(404)
    return render_template(
        "blog/blog_post.html",
        posts=Database().get_blog_posts_data_from_db(),
        postss=Database().get_blog_posts_data_from_db(),
        days_passed_till_now=General().days_passed_till_now(),
        post=post)
Esempio n. 16
0
def start_course_redirect(slug):
    """ The Course redirect to start the free course page. """
    data = PageDetails().course_page_info(slug)
    if data is False:
        abort(404)
    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    try:
        identity = session["Data"]["Email"]
    except KeyError:
        return redirect("/LogIn")

    if slug in Database().get_users_access_data_from_db(identity):
        return redirect("/Course/{slug}".format(slug=slug))

    Database().add_users_access_data_to_db(identity, slug)
    return redirect("/Course/{slug}/start/success".format(slug=slug))
Esempio n. 17
0
File: blog.py Progetto: urgemag/urge
def upload_blog_pic_ck():
    """ The Upload blog Api. """
    if request.method == "POST":

        uploaded_image = request.files.get("upload")
        uploaded_image_bytes = uploaded_image.read()

        hash_image = General().sha256_hash_bytes(uploaded_image_bytes)

        format_file = General().format_recognizer(uploaded_image_bytes)
        file_name = "post_blog_" + str(hash_image) + "." + format_file
        location_image = "static/assets/images/ck_cache/" + file_name
        location_image_href = "/static//assets/images/ck_cache/" + file_name

        with open(location_image, "wb") as file:
            file.write(uploaded_image_bytes)

        General().image_resizer_using_imgp(location_image)
        General().logo_merger(location_image)
        General().image_optimizer_using_imgp(location_image)
        width, height = General().size_image_file(image_path=location_image)
        return {
            "uploaded": 1,
            "fileName": file_name,
            "url": location_image_href,
            "width": width,
            "height": height,
        }

    return ""
Esempio n. 18
0
def one_course(slug):
    """ The one Course page. """
    try:
        identity = session["Data"]["Email"]
    except KeyError:
        identity = ""
    data = PageDetails().course_page_info(slug)
    if data is False:
        abort(404)

    course = Database().get_courses_data_from_db(slug)
    published_date = General().convert_timestamp_to_days(
        course["First_Created_TimeStamp"]) + course["Days_Till_Open"]
    if published_date > General().days_passed_till_now():
        abort(404)
    return render_template(
        "courses_and_days/course.html",
        course=data[0],
        days=data[1],
        intro=data[2],
        accesses=Database().get_users_access_data_from_db(identity),
        days_till_now=General().days_passed_till_now())
Esempio n. 19
0
def all_courses():
    """ The Courses page. """
    courses_per_page = 10
    courses = PageDetails(session).all_courses_list_sorted_by_date()
    courses.reverse()
    page = request.args.get("page")
    last_page = len(courses) // courses_per_page
    if len(courses) - last_page * courses_per_page > 0:
        last_page += 1
    if page is None:
        page = 1
    else:
        try:
            page = int(page)
        except ValueError:
            page = 1
    if page < 1:
        return redirect("?page=1")
    limited_courses = (courses[(page - 1) * courses_per_page:page *
                               courses_per_page])
    if limited_courses == [] and page != 1:
        return redirect("?page={}".format(last_page))

    try:
        identity = session["Data"]["Email"]
    except KeyError:
        identity = ""

    return render_template(
        "courses_and_days/courses.html",
        courses=limited_courses,
        accesses=Database().get_users_access_data_from_db(identity),
        days_till_now=General().days_passed_till_now(),
        now_page=page,
        last_page=last_page,
        pagination=General().pagination_designer(page, last_page))
Esempio n. 20
0
def general():
    form = GeneralForm()
    if request.method == "POST" and form.validate_on_submit():
        new_general = General(
            name=form.name.data,
            occupation=form.occupation.data,
            email=form.email.data,
            github=form.github.data,
            linkedin=form.linkedin.data,
            user_intro=form.user_intro.data,
        )
        db.session.add(new_general)
        db.session.commit()
        return redirect(url_for("main_page.home") + "#General")

    return render_template("form_page.html", form=form, title="General")
Esempio n. 21
0
        def form_handler(request):

            remove_ones = []
            course_names = []
            for course in PageDetails().all_courses_page_info_html():
                course_names.append(course["Slug"])
            for part in course_names:
                if (part) == request.form.get(part):
                    remove_ones.append(part)

            for course in remove_ones:
                Database().delete_courses_data_from_db(course)
                General().remove_file_to_trash(
                    "static/assets/images/blog/{slug}/".format(slug=course))

            return True
Esempio n. 22
0
def mbti_test_tool():
    """ The mbti 16personalities tool page. """
    if request.method == "POST":
        all_answers = []
        for answer_index in range(1, 60 + 1):
            answer = request.form.get(str(answer_index))
            if answer is None:
                return f"Quesion {answer_index} is not answered."
            all_answers.append(answer)
        user_mbti_answer = Tools().mbti_type_answer(all_answers)
        return redirect(
            url_for("tools.mbti_types_page",
                    mbti_type=user_mbti_answer["final_type"],
                    answer_percent=user_mbti_answer["answer_percent"]))

    return render_template("tools/mbti.html",
                           tool=Database().get_tool_data_db("mbti"),
                           questions=General().open_json_file(
                               "static/tools/mbti.json")["questions"])
Esempio n. 23
0
        def form_handler(request):
            text = request.form.get("text")
            day = request.form.get("day")
            slug = request.form.get("slug")

            if slug == "":
                return {
                    "Result": False,
                    "Message": "نام انگلیسی دوره را وارد کنید."
                }
            if request.form.get("day") == "":
                return {"Result": False, "Message": "روز دوره را وارد کنید."}
            if text == "":
                return {"Result": False, "Message": "متن اصلی را وارد کنید."}

            try:
                int(day)
            except ValueError:
                return {"Result": False, "Message": "روز دوره باید عدد باشد."}

            if Database().get_courses_data_from_db(slug) is False:
                return {
                    "Result": False,
                    "Message": "همچین دوره ای وجود ندارد."
                }

            links_images = re.findall("src=[\"\'](.*?)[\"\']", text)

            if General().check_existence_of_a_file(
                    "static/assets/courses/{slug}/days/{day}".format(
                        slug=slug, day=day)) is False:
                General().setup_course_folder(slug)

            for link in links_images:
                file_path = General().href_to_path(link)
                file_name = (file_path.split("/"))[-1]
                new_file_path = "static/assets/courses/{slug}/days/{day_number}/{file_name}".format(
                    slug=slug, day_number=day, file_name=file_name)
                new_file_href = "/static//assets/courses/{slug}/days/{day_number}/{file_name}".format(
                    slug=slug, day_number=day, file_name=file_name)
                General().move_file_path(file_path, new_file_path)
                text = text.replace(link, new_file_href)

            message = Database().add_day_text_data_to_db(
                course_name_slug=slug,
                day_num=day,
                text=text,
            )
            return message
Esempio n. 24
0
def mbti_types_page(mbti_type):
    """ The mbti type page. """
    user_mbti_type_upper = mbti_type.upper()
    answer_percent = request.args.get("answer_percent")
    if answer_percent is not None:
        answer_percent = (ast.literal_eval(answer_percent))
    if user_mbti_type_upper not in [
            'ESFJ', 'ESFP', 'ESTJ', 'ESTP', 'ENFJ', 'ENFP', 'ENTJ', 'ENTP',
            'ISFJ', 'ISFP', 'ISTJ', 'ISTP', 'INFJ', 'INFP', 'INTJ', 'INTP'
    ]:
        return redirect(url_for("tools.mbti_test_tool"))

    user_mbti_answer = {
        'final_type': f'{user_mbti_type_upper}',
        'answer_percent': answer_percent
    }
    return render_template(
        f"tools/mbti_base.html",
        tool=Database().get_tool_data_db("mbti"),
        user_answer=user_mbti_answer,
        user_mbti_data=General().open_json_file("static/tools/mbti.json")
        ["mbti_types"][user_mbti_answer["final_type"]])
Esempio n. 25
0
def add_user_admin():
    """ The Add User Page as an admin. """

    message = False
    if request.method == "POST":
        accesses = []
        for course in Database().get_all_slug_and_names_of_courses_from_db():
            if (course["Slug"]) == request.form.get(course["Slug"]):
                accesses.append(course["Slug"])
        message = Database().add_users_data_to_db(
            email=request.form.get("email"),
            password=General().sha256_hash(request.form.get("password")),
            first_name=request.form.get("name"),
            last_name=request.form.get("last_name"),
            phone_number=request.form.get("phone_num"),
            about_me=request.form.get("about_me"),
            bio=request.form.get("bio"),
            website=request.form.get("web"),
            birth_day=request.form.get("day"),
            birth_month=request.form.get("month"),
            birth_year=request.form.get("year"),
            Accesses=accesses,
        )
        if message is True:
            message = {"Color": "green", "Result": "با موفقیت اضافه شد."}
        else:
            message["Result"] = message["Message"]
            message["Color"] = "red"

        flash(message)
        return redirect(url_for("admin_add.add_user_admin"))

    return render_template(
        "admin/admin_add_user.html",
        Accesses=PageDetails().all_accesses_admin_page(),
        message=message,
    )
Esempio n. 26
0
def isoG():

    if request.method == 'POST':
        # ____________________________________________________________________________________________________________________B.FormVariables.General

        from viewfuncs import parseline, popjo, jovec, newjo, timedata, nonone, nononef
        from viewfuncs import numcheck, numcheckv, viewbuttons, get_ints, numcheckvec

        #Zero and blank items for default
        username = session['username'].capitalize()
        cache = 0
        modata = 0
        modlink = 0
        fdata = 0
        filesel = ''
        docref = ''
        doctxt = ''
        longs = ''

        today = datetime.date.today()
        now = datetime.datetime.now().strftime('%I:%M %p')

        leftsize = 10

        match = request.values.get('Match')
        modify = request.values.get('Modify')
        vmod = request.values.get('Vmod')
        viewo = request.values.get('ViewO')
        print = request.values.get('Print')
        returnhit = request.values.get('Return')
        deletehit = request.values.get('Delete')
        delfile = request.values.get('DELF')
        # hidden values
        update = request.values.get('Update')
        newjob = request.values.get('NewJ')
        thisjob = request.values.get('ThisJob')
        oder = request.values.get('oder')
        modlink = request.values.get('modlink')
        longs = request.values.get(longs)
        searchfind = request.values.get('mastersearch')
        assemble = request.values.get('Assemble')

        oder = nonone(oder)
        modlink = nonone(modlink)

        leftscreen = 1
        err = ['All is well', ' ', ' ', ' ', ' ']

        if returnhit is not None:
            modlink = 0

        if searchfind is not None:
            modlink = 20

# ____________________________________________________________________________________________________________________E.FormVariables.General
# ____________________________________________________________________________________________________________________B.DataUpdates.General

        if update is not None and modlink == 1:
            if oder > 0:
                modata = General.query.get(oder)
                vals = ['subject', 'category', 'longs']
                a = list(range(len(vals)))
                for i, v in enumerate(vals):
                    a[i] = request.values.get(v)

                modata.Subject = a[0]
                modata.Category = a[1]
                modata.Textinfo = a[2]

                db.session.commit()
                err[3] = 'Modification to General id ' + str(
                    modata.id) + ' completed.'
                modlink = 0

# ____________________________________________________________________________________________________________________B.GetData.General
        odata = General.query.all()

        if assemble is not None:
            avec = numcheckvec(odata, 'oder')
            scommand = ['pdfunite']
            if len(avec) > 0:
                for a in avec:
                    gdat = General.query.get(a)
                    dot = gdat.Path
                    docref = f'tmp/{scac}/data/vgeneral/' + dot
                    scommand.append(docref)
                scommand.append(
                    f'tmp/{scac}/data/vunknown/assembledoutput.pdf')
                tes = subprocess.check_output(scommand)
# ____________________________________________________________________________________________________________________B.Search.General

        if (newjob is None and modlink < 10) or modlink == 20:
            oder, numchecked = numcheck(1, odata, 0, 0, 0, 0, ['oder'])

# ____________________________________________________________________________________________________________________E.Search.General

# ____________________________________________________________________________________________________________________B.Views.General

        if viewo is not None and numchecked == 1:
            err = [
                ' ', ' ', 'There is no document available for this selection',
                ' ', ' '
            ]
            if oder > 0:
                modata = General.query.get(oder)
                if modata.Path is not None:
                    dot = modata.Path
                    txt = dot.split('.', 1)[0] + '.txt'
                    docref = f'tmp/{scac}/data/vgeneral/' + dot
                    doctxt = docref.replace('.pdf', '.txt').replace(
                        '.jpg', '.txt').replace('.jpeg', '.txt')
                    leftscreen = 0
                    leftsize = 10
                    modlink = 0
                    err = [' ', ' ', 'Viewing document ' + docref, ' ', ' ']

        if (viewo is not None) and numchecked != 1:
            err = [
                'Must check exactly one box to use this option', ' ', ' ', ' ',
                ' '
            ]

# ____________________________________________________________________________________________________________________E.Views.General
# ____________________________________________________________________________________________________________________B.Modify.General
        if (modify is not None or vmod is not None) and numchecked == 1:
            modlink = 1
            leftsize = 8

            if oder > 0:
                modata = General.query.get(oder)
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]
                    if modata.Path is not None:
                        dot = modata.Path
                        docref = f'tmp/{scac}/data/vgeneral/' + dot
                        doctxt = docref.replace('.pdf', '.txt').replace(
                            '.jpg', '.txt').replace('.jpeg', '.txt')

                        leftscreen = 0

                        err = ['All is well', ' ', ' ', ' ', ' ']

        if (modify is not None or vmod is not None) and numchecked != 1:
            modlink = 0
            err[0] = ' '
            err[2] = 'Must check exactly one box to use this option'
# ____________________________________________________________________________________________________________________E.Modify.General

# ____________________________________________________________________________________________________________________B.Delete.General
        if deletehit is not None and numchecked == 1:
            if oder > 0:
                #This section is to determine if we can delete the source file along with the data.  If other data is pointing to this
                #file then we need to keep it.
                modata = General.query.get(oder)
                if modata.Path is not None:
                    dot = modata.Path
                    docref = f'tmp/{scac}/data/vgeneral/' + dot

                othdoc = General.query.filter((General.Path == dot) & (
                    General.Path != modata.id)).first()
                if othdoc is None:
                    try:
                        os.remove(addpath(docref))
                        os.remove(addtxt(docref))
                    except:
                        err[0] = 'File already removed'

                General.query.filter(General.id == oder).delete()
                db.session.commit()

        if deletehit is not None and numchecked != 1:
            err = [
                ' ', ' ',
                'Must have exactly one item checked to use this option', ' ',
                ' '
            ]
# ____________________________________________________________________________________________________________________E.Delete.General

# ____________________________________________________________________________________________________________________B.Newjob.General
        if newjob is not None:
            err = ['Select Source Document from List']
            fdata = myoslist(f'tmp/{scac}/data/vunknown')
            fdata.sort()
            modlink = 10
            leftsize = 8
            leftscreen = 0
            docref = f'tmp/{scac}/data/vunknown/NewJob.pdf'

        if newjob is None and update is None and modlink == 10:
            filesel = request.values.get('FileSel')
            filetxt = filesel.replace('.pdf',
                                      '.txt').replace('.jpg', '.txt').replace(
                                          '.jpeg', '.txt')
            fdata = myoslist(f'tmp/{scac}/data/vunknown')
            fdata.sort()
            leftsize = 8
            leftscreen = 0
            docref = f'tmp/{scac}/data/vunknown/' + filesel
            doctxt = f'tmp/{scac}/data/vunknown/' + filetxt

            try:
                longs = open(addpath(doctxt)).read()
                longs = longs[0:999]
            except:
                doctxt = ''
                longs = ''

        if delfile is not None and modlink == 10:
            modlink = 0
            filesel = request.values.get('FileSel')
            if filesel != '1':
                dockill1 = f'tmp/{scac}/data/vunknown/' + filesel
                try:
                    os.remove(addpath(dockill1))
                except:
                    err[1] = 'Could not delete ...'
                try:
                    os.remove(addtxt(dockill1))
                except:
                    err[2] = 'Could not delete txt'

        if update is not None and modlink == 10:
            modlink = 0
            #Create the new database entry for the source document
            filesel = request.values.get('FileSel')

            if filesel != '1':
                docold = f'tmp/{scac}/data/vunknown/' + filesel
                docref = f'tmp/{scac}/data/vgeneral/' + filesel
                try:
                    shutil.move(addpath(docold), addpath(docref))
                except:
                    err[4] = 'File has been moved already'
                try:
                    shutil.move(addtxt(docold), addtxt(docref))
                except:
                    err[4] = 'File has been moved already'

            else:
                docref = ''
                doctxt = ''

            subject = request.values.get('subject')
            category = request.values.get('category')
            longs = request.values.get('longs')

            input = General(Subject=subject,
                            Category=category,
                            Textinfo=longs,
                            Path=filesel)
            db.session.add(input)
            db.session.commit()
            db.session.close()

            odata = General.query.all()

            modlink = 0
            leftscreen = 1
            oder = 0
            leftsize = 10
            err = ['All is well', ' ', ' ', ' ', ' ']
# ____________________________________________________________________________________________________________________E.Newjob.General

        if modlink == 20:
            odata = General.query.filter(
                (General.Textinfo.contains(searchfind))
                | (General.Subject.contains(searchfind))
                | (General.Category.contains(searchfind))).all()

    #This is the else for 1st time through (not posting data from overseas.html)
    else:
        from viewfuncs import popjo, jovec, timedata, nonone, nononef, init_truck_zero
        today = datetime.date.today()
        #today = datetime.datetime.today().strftime('%Y-%m-%d')
        now = datetime.datetime.now().strftime('%I:%M %p')
        oder = 0
        cache = 0
        modata = 0
        modlink = 0
        fdata = 0
        filesel = ''
        docref = ''
        doctxt = ''
        longs = ''
        odata = General.query.all()
        leftscreen = 1
        leftsize = 10
        err = ['All is well', ' ', ' ', ' ', ' ']

    fdata = myoslist('data/vunknown')
    fdata.sort()
    doctxt = os.path.splitext(docref)[0] + '.txt'
    leftsize = 8
    return odata, oder, err, modata, modlink, leftscreen, docref, leftsize, fdata, filesel, today, now, doctxt, longs
Esempio n. 27
0
app = Flask(
    __name__,
    template_folder=setting.template_folder,
    static_folder=setting.static_folder,
)

app.config[
    "COMPRESS_REGISTER"] = True  # disable default compression of all eligible requests
compress = Compress()
compress.init_app(app)

app.logger.addHandler(file_handler_error_logs)
app.logger.addHandler(file_handler_critical_logs)
app.logger.addHandler(file_handler_warning_logs)
app.jinja_env.globals.update(
    status_date_published_post_blog=General().status_date_published_post_blog)
app.jinja_env.globals.update(convert_timestamp=General().convert_timestamp)
app.jinja_env.globals.update(
    smart_description_preview_splitted_by_word=General(
    ).smart_description_preview_splitted_by_word)
app.jinja_env.globals.update(price_beautifier=General().price_beautifier)
app.jinja_env.globals.update(html_to_text=General().html_to_text)
app.secret_key = setting.secret_key
app.config["DEBUG"] = setting.debug_mode
app.config.update({
    "RECAPTCHA_ENABLED": setting.recaptcha_enabled,
    "RECAPTCHA_DATA_ATTRS": {
        "theme": setting.recaptcha_theme
    },
    "RECAPTCHA_SITE_KEY": setting.recaptcha_public_key,
    "RECAPTCHA_SECRET_KEY": setting.recaptcha_secret_key,
Esempio n. 28
0
def generate_post():

    return render_template("admin/admin_generate_instagram_post.html",
                           templates=General().open_json_file(
                               "static/assets/instagram/posts.json"))
Esempio n. 29
0
        def form_handler(request):
            slug = request.form.get("slug")
            day = request.form.get("day")
            name_day = request.form.get("name_day")
            description_status_existence = request.form.get(
                "description-status")
            description = request.form.get("description")
            price_status = request.form.get("price-status")

            if is_not_empty(slug):
                return {
                    "Result": False,
                    "Message": "نام انگلیسی دوره را وارد کنید."
                }
            if is_not_empty(day) == "":
                return {"Result": False, "Message": "روز دوره را وارد کنید."}
            if is_not_empty(name_day):
                return {"Result": False, "Message": "اسم روز را وارد کنید."}
            if description_status_existence == "With-Description" and is_not_empty(
                    description):
                return {
                    "Result": False,
                    "Message": "توضیحات روز را وارد کنید."
                }

            if price_status == "None-Free":
                freeness = False
            else:
                freeness = True

            if is_numeric(day):
                return {"Result": False, "Message": "روز دوره باید عدد باشد."}
            try:
                uploaded_file = request.files["cover"]
            except:
                return {"Result": False, "Message": "تصویر را آپلود کنید."}
            if Database().get_courses_data_from_db(
                    request.form.get("slug")) is False:
                return {
                    "Result": False,
                    "Message": "همچین دوره ای وجود ندارد."
                }

            uploaded_image = request.files.get("cover")
            uploaded_image_bytes = uploaded_image.read()

            hash_image = General().sha256_hash_bytes(uploaded_image_bytes)

            format_file = General().format_recognizer(uploaded_image_bytes)
            file_name = "cover_of_day_of_course_" + str(
                hash_image) + "." + format_file

            if General().check_existence_of_a_file(
                    "static/assets/courses/{slug}/days/{day}".format(
                        slug=slug, day=day)) is False:
                General().setup_course_folder(slug)

            location_image = "static/assets/courses/{slug}/days/{day}/{file_name}".format(
                slug=slug, day=day, file_name=file_name)
            location_image_href = "/static//assets/courses/{slug}/days/{day}/{file_name}".format(
                slug=slug, day=day, file_name=file_name)
            with open(location_image, "wb") as file:
                file.write(uploaded_image_bytes)

            General().image_resizer_using_imgp(location_image, 700)
            General().image_optimizer_using_imgp(location_image)

            message = Database().add_day_essential_data_to_db(
                course_name_slug=request.form.get("slug"),
                day_num=request.form.get("day"),
                name_persian=request.form.get("name_day"),
                description=request.form.get("description"),
                image_path=location_image_href,
                freeness=freeness,
            )
            return message
Esempio n. 30
0
def addpost():
    posttype = request.form['posttype']
    post_title = request.form['posttitle']
    posted_by = request.form['postedby']
    location = request.form['postlocation']
    #file_attach = request.files['']
    content = request.form['content']

    email = current_user.email
    my_user = db.session.query(User).filter_by(email=email).first()
    if posttype == 'politics' and my_user.post_counter < 10 and my_user.daily_post < 10 and my_user.daily_post < 1000:
        post = Politics(post_type=posttype,
                        post_title=post_title,
                        posted_by=posted_by,
                        location=location,
                        content=content,
                        date_posted=datetime.now())
        db.session.add(post)
        email = current_user.email
        my_user = db.session.query(User).filter_by(email=email).first()
        if my_user is None:
            pass

        #counting =  my_user.post_counter + 1
        #counting =str(counting)
        my_user.post_counter += 1
        my_user.daily_post += 1
        my_user.user_balance += 100
        #my_user.post_counter=counts
        db.session.add(my_user)  #t
        db.session.commit()
        return "Posted" + posted_by

    #my_user.withdraw = "yes"
    #db.session.add(my_user) #t
    #db.session.commit()
    #return 'You no more eligiable please wait for the next 24hours and withdraw yor money'

    email = current_user.email
    my_user = db.session.query(User).filter_by(email=email).first()
    if posttype == 'general' and my_user.post_counter < 10 and my_user.daily_post < 10 and my_user.daily_post < 1000:
        post = General(post_type=posttype,
                       post_title=post_title,
                       posted_by=posted_by,
                       location=location,
                       content=content,
                       date_posted=datetime.now())
        db.session.add(post)
        db.session.commit()

        email = current_user.email
        my_user = db.session.query(User).filter_by(email=email).first()
        if my_user is None:
            pass

        #counting =  my_user.post_counter + 1
        #counting =str(counting)
        my_user.post_counter += 1
        my_user.daily_post += 1
        my_user.user_balance += 100
        #my_user.post_counter=counts
        db.session.add(my_user)  #t
        db.session.commit()
        return "Posted" + posted_by

    email = current_user.email
    my_user = db.session.query(User).filter_by(email=email).first()
    if posttype == 'entertainment' and my_user.post_counter < 10 and my_user.daily_post < 10 and my_user.daily_post < 1000:
        post = Entertainment(post_type=posttype,
                             post_title=post_title,
                             posted_by=posted_by,
                             location=location,
                             content=content,
                             date_posted=datetime.now())
        db.session.add(post)
        email = current_user.email
        my_user = db.session.query(User).filter_by(email=email).first()
        if my_user is None:
            pass

        #counting =  my_user.post_counter + 1
        #counting =str(counting)
        my_user.post_counter += 1
        my_user.daily_post += 1
        my_user.user_balance += 100
        #my_user.post_counter=counts
        db.session.add(my_user)  #t
        db.session.commit()
        return "Posted" + posted_by

    email = current_user.email
    my_user = db.session.query(User).filter_by(email=email).first()
    if posttype == 'sport' and my_user.post_counter < 10 and my_user.daily_post < 10 and my_user.daily_post < 1000:
        post = Sport(post_type=posttype,
                     post_title=post_title,
                     posted_by=posted_by,
                     location=location,
                     content=content,
                     date_posted=datetime.now())
        db.session.add(post)
        db.session.commit()
        return "Posted" + posted_by

    email = current_user.email
    my_user = db.session.query(User).filter_by(email=email).first()
    if posttype == 'tech' and my_user.post_counter < 10 and my_user.daily_post < 10 and my_user.daily_post < 1000:
        post = Technology(post_type=posttype,
                          post_title=post_title,
                          posted_by=posted_by,
                          location=location,
                          content=content,
                          date_posted=datetime.now())
        db.session.add(post)
        db.session.commit()

        email = current_user.email
        my_user = db.session.query(User).filter_by(email=email).first()
        if my_user is None:
            pass

        #counting =  my_user.post_counter + 1
        #counting =str(counting)
        my_user.post_counter += 1
        my_user.daily_post += 1
        my_user.user_balance += 100
        #my_user.post_counter=counts
        db.session.add(my_user)  #t
        db.session.commit()
        flash("Thank You Content Posted")
        return redirect(url_for('dashboard'))
    else:
        return 'post type is not selected or not available'