Example #1
0
 def post(self, tag):
     group = Group.objects(tag=tag)[0]
     title = self.get_argument('title')
     content = self.get_argument('content')
     now = datetime.datetime.now()
     mode = self.get_argument('type').decode()
     if mode == 'new':
         try:
             if not title:
                 raise Exception('title is none')
             post = Post(group=group,
                         author=self.get_curent_user_model(),
                         title=title,
                         content=content,
                         create_at=now,
                         update_at=now)
             post.save()
             return self.redirect("/group/" + tag + "/" + str(post.id))
         except Exception as ex:
             app_log.error(ex)
             return self.redirect("/group/" + tag)
     elif mode == 'update':
         id = self.get_argument('id')
         try:
             app_log.debug(id)
             app_log.debug(title)
             app_log.debug(content)
             post = Post.objects(id=id)[0]
             post.title = title
             post.content = content
             post.save()
         except Exception as ex:
             app_log.error(ex)
         return self.redirect("/group/" + tag + "/" + id)
Example #2
0
	def new_post(self):
		title  = input("Enter post title: ")
		content  = input("Enter post content: ")
		date  = input("Enter post date (in format DDMMYY) or leave blank or today: ")
		post = Post(blog_id = self.id,
					title = title,
					content = content,
					author = self.author,
					date = datetime.datetime.utcnow() if date == "" else datetime.datetime.strptime(date, "%d%m%Y")
					#strotime -- parses string to date format as mentioned
					)	
		post.save_to_mongo()
Example #3
0
def save_share():
    if request.method == "GET":
        return render_template("save_share.html")
    else:
        form = request.form
        des = form["description"]
        img = form["image"]
        share = form["share"]
        if share == "yes":
            post = Post(img=img, user=session["token"], descript=des)
            post.save()
        All_history(img=img, user=session["token"], des=des).save()
        return redirect(url_for("home"))
Example #4
0
def save_share():
    if request.method == "GET":
        user = User.objects(username=session["token"]).first()
        return render_template("save_share.html",name = session["token"],avt=user.avt)
    else:
        form = request.form
        des = form["description"]
        img = form["image"]
        share = form["share"]
        if share == "yes":
            post = Post(img=img,user=session["token"],descript=des) 
            post.save()
        All_history(img=img,user=session["token"],des=des).save()
        return redirect(url_for("ca_nhan"))
Example #5
0
 def post(self, tag):
     group = Group.objects(tag=tag)[0]
     title = self.get_argument('title')
     content = self.get_argument('content')
     now = datetime.datetime.now()
     mode = self.get_argument('type').decode()
     if mode == 'new':
         try:
             if not title:
                 raise Exception('title is none')
             post = Post(group=group,
                         author=self.get_curent_user_model(),
                         title=title,
                         content=content,
                         create_at=now,
                         update_at=now
             )
             post.save()
             return self.redirect("/group/" + tag + "/" + str(post.id))
         except Exception as ex:
             app_log.error(ex)
             return self.redirect("/group/" + tag)
     elif mode == 'update':
         id = self.get_argument('id')
         try:
             app_log.debug(id)
             app_log.debug(title)
             app_log.debug(content)
             post = Post.objects(id=id)[0]
             post.title = title
             post.content = content
             post.save()
         except Exception as ex:
             app_log.error(ex)
         return self.redirect("/group/" + tag + "/" + id)
Example #6
0
 def new_post(self):
     title = input("Enter Post Title: ")
     content = input("Enter Post Content: ")
     date = input(
         "Enter Post Date or leave blank for today (in format DDMMYYYY): ")
     if date == "":
         date = datetime.datetime.utcnow()
     else:
         date = datetime.datetime.strptime(date, "%d%m%Y")
     post = Post(blog_id=self.id,
                 title=title,
                 content=content,
                 author=self.author,
                 created_date=date)
     post.save_to_mongo()
Example #7
0
    def new_post(self):
        title = input("enter post title")
        content = input("enter post content")
        date = input(
            "enter the date or leave blank for today (in format DDMMYYYY)")

        if date == "":
            date = datetime.datetime.utcnow()
        else:
            date = datetime.datetime.strptime(date, "%d%m%Y")
        post = Post(blog_id=self.id,
                    title=title,
                    content=content,
                    author=self.author,
                    date=date)
        post.save_to_mongo()
Example #8
0
def update_draft(slug):
    form = PostForm()

    #grap post data
    draft = Draft.query.filter_by(slug=slug).first_or_404()

    #populate form with data
    form.title.data = draft.title
    form.slug.data = draft.slug
    form.category.data = draft.category
    form.body.data = draft.body

    the_id = current_user.get_id()
    the_name = current_user.name

    if form.validate_on_submit():
        #Update the draft on submit
        if form.update_draft.data:
            draft.title = request.form['title']
            draft.slug = request.form['slug']
            draft.category = request.form['category']
            draft.body = request.form['body']
            db.session.commit()
            return redirect(url_for('dashboard'))
        #Create as post and delete draft on submit
        elif form.create_post.data:
            post = Post(request.form['title'], request.form['slug'],
                        request.form['body'], request.form['category'],
                        the_name, the_id)
            db.session.delete(draft)
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('index'))
    return render_template('posts/update_draft.html', form=form, admin=True)
def render_admin_hub(uri):
    if session['email'] is None:
        return redirect("https://kcbootcampers-api-heroku.herokuapp.com/login")
    cookie_uri = request.cookies.get('login_id')
    if cookie_uri == uri:
        users = Admin.get_all()
        posts = Post.get_all()
        posts.reverse()
        assignments = Assignment.get_all()
        assignments.reverse()
        others = Other.get_all()
        others.reverse()
        videos = Video.get_all()
        videos.reverse()
        books = Book.get_all()
        books.reverse()
        return render_template(
            "admin_hub.html",
            href="https://kcbootcampers-api-heroku.herokuapp.com/admin/hub/" +
            cookie_uri,
            acc=session['email'],
            posts=posts,
            users=users,
            assignments=assignments,
            others=others,
            videos=videos,
            books=books,
            uri=uri,
            display='all')
    else:
        return render_template(
            "expired.html",
            acc="Account" if session['email'] is None else session['email'])
def render_post(uri, post_id):
    post = Post.get_by_id(post_id)
    if request.method == 'GET':
        return render_template("admin_posts.html",
                               post=post,
                               acc=session['email'])
    else:
        title = request.form['title']
        content = request.form['content']
        post = Post.get_by_id(post_id)
        post.update("title", title)
        post.update("content", content)
        post = Post.get_by_id(post_id)
        return render_template("admin_posts.html",
                               post=post,
                               acc=session['email'])
Example #11
0
def handle_bs_and_create_hilights(hilights: Dict[str, List[Post]],
                                  post_bs: BeautifulSoup,
                                  email: Email) -> None:
    post_title_element = post_bs.find("div", {"class": "structItem-title"})
    if len(post_title_element.find_all("a")) == 2:
        post_link = post_title_element.find_all("a")[1]
    else:
        post_link = post_title_element.find_all("a")[0]
    post_url = post_link["href"].split("/")
    post_url = "/".join(post_url[:-1])
    post_id = int(post_url.split(".")[-1].split("/")[0])
    post_title = post_link.text.lower()
    post_datetime = parse(post_bs.find("time", {"class": "u-dt"})["datetime"])

    existing_post = Post.query.get(post_id)
    if email.email in hilights:
        existing_post = existing_post or next(
            (x for x in hilights[email.email] if x.id == post_id), None)
    if not existing_post:
        post = Post(
            id=post_id,
            url=settings.BASE_URL + post_url,
            title=post_title,
            time=post_datetime,
        )
        db.session.add(post)
        add_hilight(post, hilights, email)
    else:
        add_hilight(existing_post, hilights, email)
def render_hub(uri=None):
    if session['email'] is None:
        return redirect("https://kcbootcampers-api-heroku.herokuapp.com/login")
    posts = Post.get_all()
    posts.reverse()
    others = Other.get_all()
    others.reverse()
    books = Book.get_all()
    books.reverse()
    videos = Video.get_all()
    videos.reverse()
    assignments = Assignment.get_all()
    assignments.reverse()
    user = User.get_by_email(session['email'])
    password = "******" * randint(5, 12)
    cellphone = user.cellphone
    fname = user.fname
    lname = user.lname
    if user.status == "*":
        display = "all"
    else:
        display = "none"
    return render_template("hub.html",
                           acc=session['email'],
                           posts=posts,
                           others=others,
                           videos=videos,
                           books=books,
                           assignments=assignments,
                           fname=fname,
                           lname=lname,
                           password=password,
                           cellphone=cellphone,
                           display=display)
Example #13
0
    def new_post(self, title, content, date=datetime.datetime.utcnow()):
        """new_post(str, str, str) -> return(None)

        title  : The title of the new post
        content: The content regarding the new post
        date   : The date the post was created
        Return : None

        New post method enables the user to create a new blog post.
        """
        new_post = Post(blog_id = self._id,
                        title   = title,
                        content = content,
                        author  = self._author,
                        created_date = date)
        new_post.save() # save post
Example #14
0
def hoat_dong_sx_ttt(sort):
    if request.method == "GET":
        act_list = Activities.objects()
        return render_template("hoat_dong_sx_ttt.html", acts = act_list, sort = sort,name = session["token"],avt="https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png")
    else:
        if "token" in session:        
            user = session["token"]
            form = request.form
            att_list = Attribute.objects(username = user).first()
            act_list = Activities.objects()    
            toan_bo = form.get("all")

            if toan_bo != None:
                return redirect("/hoat-dong")
                
            for att in att_list:
                if att in form:
                    return redirect("/hoat-dong-sx-ttt-" + att)
                else:
                    pass
            for act in act_list:
                act_tit = form.get(act["tit"])
                if act_tit != None:
                    hstr_list = All_history.objects(user = user)
                    des = form["description"]
                    img = form["image"]
                    share = form["share"]
                    for att in att_list :
                        if att in act and att != "id":
                            att_list[att] = att_list[att] + act[att]
                            if att_list[att] < 0:
                                att_list[att] = 0
                        st = act["st"]
                        cre = act["cre"]
                        soc = act["soc"]
                        knl = act["knl"]
                        per = act["per"]

                    att_list.save()
                    All_history(tit = act["tit"], img=img,user=session["token"], des = des, soc = soc, cre = cre, knl = knl, st = st, per = per, time = str(datetime.now().strftime("%Y%m%d"))).save()
                    if share == "yes":
                        post = Post(tit = act["tit"] ,img = img, user = session["token"], descript = des)
                        post.save()
                    break
            return render_template("hoat_dong_sx_ttt.html", acts = act_list)
        else:
            return redirect(url_for("sign_in"))
Example #15
0
async def start_proccess(db, post):
    hashtag = await db.get(Hashtag, name=post.tag)

    posts_db = list(await db.execute(
        Post.select(Post, Hashtag).join(Hashtag).where(
            Hashtag.name == post.tag).order_by(Post.published_at)))

    dates = [i.published_at for i in posts_db]

    newest = True

    if dates:
        newest = post.published_at > max(dates)

    if newest:
        point = Point(post.location.lat, post.location.lng, srid=4326)
        data = {
            'hashtag_id': hashtag.id,
            'published_at': post.published_at,
            'url': post.url,
            'location': post.location.name,
            'point': point
        }
        await db.get_or_create(Post, **data)

        if not posts_db:
            return

        hashtag.total_posts += 1

        total_distance = hashtag.total_distance

        last_point_in_db = posts_db[0].point

        distance_between_last_points = await db.execute(
            Post.raw(
                """
        SELECT ST_Distance(
                'SRID=4326;POINT(%s %s)'::geography,
                'SRID=4326;POINT(%s %s)'::geography
        )/1000 as distance
        """, *point.coords, *last_point_in_db.coords))

        distance_between_last_points = distance_between_last_points[0].distance
        hashtag.total_distance = total_distance + distance_between_last_points

        await db.update(hashtag)
Example #16
0
 def get(self, tag):
     group = Group.objects(tag=tag)[0]
     posts = Post.objects(group=group)
     self.render("group/_groups.html",
                 page_heading=group.name,
                 _group=group,
                 posts=posts,
                 groups=self.get_groups())
Example #17
0
def social():
    user = Friend.objects(username=session["token"]).first()
    friends = user.friend
    friend_post = []
    posts = Post.objects()
    for post in posts:
        if post.user in friends:
            friend_post.append(post)
    return render_template("social.html", posts=friend_post)
Example #18
0
 def get(self, tag):
     group = Group.objects(tag=tag)[0]
     posts = Post.objects(group=group)
     self.render(
         "group/_groups.html",
         page_heading=group.name,
         _group=group,
         posts=posts,
         groups=self.get_groups()
     )
Example #19
0
def handle_bs_and_create_hilight(
    hilights: List[Post],
    post_bs: BeautifulSoup,
    saved_posts: List[Post],
) -> None:
    remove_expand_block_quotes(post_bs)

    post_id = int(post_bs["data-content"].split("-")[-1])
    post_url = post_bs.find("a", {"class": "u-concealed"})["href"]

    post_content = post_bs.find("div", {"class": "bbWrapper"})
    post_content_html = str(post_content).strip()[:8000]

    has_links = replace_links(post_content)
    if not has_links:
        return

    remove_blockquotes(post_content)

    post_content_plain = post_content.text.strip()[:8000]
    post_datetime = parse(post_bs.find("time", {"class": "u-dt"})["datetime"])

    reactions_link = post_bs.find("a", {"class": "reactionsBar-link"})
    reactions_count = 0

    if reactions_link:
        reactions_text = reactions_link.text
        p = re.compile(" ja (.*) muuta")
        reactions = p.findall(reactions_text)
        if reactions:
            reactions_count += int(reactions[0]) + 3
        elif " ja " in reactions_text:
            reactions_count = 2

    existing_post = next((x for x in saved_posts if x.id == post_id), None)
    if not existing_post:
        post = Post(
            id=post_id,
            likes=reactions_count,
            time=post_datetime,
            url=settings.BASE_URL + post_url,
            content=post_content_html,
            content_plain=post_content_plain,
            is_sent=False,
        )
        db.session.add(post)
        add_hilight(post, hilights)
        return post
    else:
        existing_post.content = post_content_html
        existing_post.content_plain = post_content_plain
        existing_post.likes = reactions_count
        add_hilight(existing_post, hilights)
        return existing_post
Example #20
0
 def post(self, tag, uuid):
     content = self.get_argument('content')
     now = datetime.datetime.now()
     comment = Comment(content=content,
                       author=self.get_curent_user_model(),
                       create_at=now,
                       update_at=now)
     post = Post.objects(id=uuid)[0]
     post.comments.append(comment)
     post.save()
     self.redirect("/group/" + tag + "/" + uuid)
Example #21
0
 def get(self, tag, uuid):
     try:
         post = Post.objects(id=uuid)[0]
         self.render(
             "group/_post.html",
             page_heading=post.title,
             post=post,
             groups=self.get_groups()
         )
     except Exception as ex:
         app_log.error(ex)
         self.redirect('/group/' + tag)
Example #22
0
def social():
    user = Friend.objects(username=session["token"]).first()
    us = User.objects(username=session["token"]).first()
    friends = user.friend
    friend_post = []
    posts = Post.objects()
    # commentss = []
    for post in posts:
        if post.user in friends or post.user == session["token"]:
            friend_post.append(post)
    print(friend_post)
    # for post in friend_post:
    #     commentss.append(post.comments)
    if request.method == "GET":
        return render_template("social.html",
                               posts=friend_post,
                               avt=us.avt,
                               name=session["token"])
    else:
        form = request.form
        for i in form:
            if "like" in i:
                like = form[i]
                if like != None:
                    for j in range(len(friend_post)):
                        if str(j + 1) in i:
                            p = friend_post[j]
                            print(p.like)
                            if session["token"] not in p.wholike:
                                p.like += 1
                                p.wholike.append(session["token"])
                            else:
                                p.like -= 1
                                p.wholike.remove(session["token"])

            else:
                comments = []
                comment = {}
                comment["contain"] = form[i]
                comment["owner"] = session["token"]
                if comment["contain"] != None:
                    for j in range(len(friend_post)):
                        if str(j + 1) in i:
                            p = friend_post[int(j)]
                            p.comments.append(comment)
            p.save()
    return redirect(url_for("social"))
def send_obj():
    posts = []
    dict_posts = {}
    if request.method == 'POST':
        data = request.form.get('data')
        if data is not None:
            posts = Post.search(qs=data)
            for post in posts:
                post.date_created = post.date_created.isoformat()
        try:
            for i in range(len(posts)):
                dict_posts[i] = posts[i].__dict__
            return dumps(dict_posts)
        except IndexError:
            return ""
    else:
        return ""
Example #24
0
    async def get(self):
        hashtag_name = self.request.match_info.get('hashtag')

        if not hashtag_name:
            return json_response(
                {
                    'success': False,
                    'errors': 'hashtag is required'
                },
                status=400)

        db = self.request.app['objects']
        posts = await db.execute(
            Post.select().join(Hashtag).where(Hashtag.name == hashtag_name))

        data, _ = PostSerializer().dump(posts, many=True)

        return json_response(data)
Example #25
0
def add_hilight(post: Post, hilights: List[Post]) -> None:
    seconds_since_post = get_seconds_since_post(post)

    if not post.is_sent and (
        (
            post.likes >= 2
            and seconds_since_post <= 60 * 60  # >=2 likes within the first hour
        )
        or (
            post.likes >= 7
            and seconds_since_post <= 24 * 60 * 60  # >=7 likes within the first 24h
        )
        or post.likes >= 12
        and seconds_since_post
        <= 60 * 60 * 24 * 7  # >= 12 likes within the first 7 days
    ):
        post.is_sent = True
        hilights.append(post)
def social():
    user = Friend.objects(username=session["token"]).first()
    friends = user.friend
    friend_post = []
    posts = Post.objects()
    who_like  = [] 
    for post in posts:
        if post.user in friends:
            friend_post.append(post)
    if request.method == "GET":
        return render_template("social.html",posts=friend_post) 
    else:
        form = request.form
        print(form) 
        for i in form: 
            if "like" in i:
                like = form[i]
                if like != None:
                    for j in range(len(friend_post)): 
                        if str(j+1) in i: 
                            p = friend_post[j] 
                            if session["token"] not in p.wholike:
                                p.like += 1 
                                p.wholike.append(session["token"])
                            else:
                                p.like -= 1 
                                p.wholike.remove(session["token"])
                                
            else:
                comment = form[i]
                if comment != None:
                    for j in range(len(friend_post)): 
                        if str(j+1) in i: 
                            p = friend_post[int(j)] 
                            p.comment.append(comment)
            p.save()
    return redirect(url_for("social"))
Example #27
0
def handle_posts():
    if request.method == 'POST':
        try:
            if request.is_json:
                data = request.get_json()
                new_post = Post(userId=data['userId'], content=data['content'])
                db.session.add(new_post)
                db.session.commit()

                return {
                    "message":
                    f"post {new_post.id} has been created successfully."
                }
            else:
                return {"error": "The request payload is not in JSON format"}
        except Exception as e:
            return {"Error": str(e)}
    elif request.method == 'GET':
        try:
            posts = Post.query.all()
            results = [post.serialize() for post in posts]
            return {"count": len(results), "posts": results}
        except Exception as e:
            return {"error": str(e)}
def render_create(uri):
    file_dict = {}
    if request.method == 'GET':
        return render_template("create_post.html", acc=session['email'])
    else:
        title = request.form['title']
        content = request.form['content']
        if 'file' not in request.files:
            title = request.form['title']
            content = request.form['content']
            post = Post(author=session['email'], content=content, title=title)
            post.save_to_mongo()
            return redirect(
                'https://kcbootcampers-api-heroku.herokuapp.com/admin/hub/' +
                uri)
        files = request.files.getlist("file")
        #if user does not select file, browser also
        #submit an empty part without filename
        for file in files:
            if file.filename == '':
                title = request.form['title']
                content = request.form['content']
                post = Post(author=session['email'],
                            content=content,
                            title=title)
                post.save_to_mongo()
                return redirect(
                    'https://kcbootcampers-api-heroku.herokuapp.com/admin/hub/'
                    + uri)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file_dict[filename.split('.')[0]] = os.path.join(
                    "/uploads/images/", filename)
                try:
                    os.mkdir(app.config['ADMIN_UPLOAD_FOLDER'])
                except FileExistsError:
                    pass
                file.save(
                    os.path.join(app.config['ADMIN_UPLOAD_FOLDER'], filename))
                title = request.form['title']
                content = request.form['content']
                name_of_file = filename
            else:
                return render_template("create_post.html",
                                       acc=session['email'])

        post = Post(author=session['email'],
                    content=content,
                    title=title,
                    date_created=None,
                    _id=None,
                    **file_dict)
        post.save_to_mongo()
        return redirect(
            'https://kcbootcampers-api-heroku.herokuapp.com/admin/hub/' + uri)
Example #29
0
def habit():
    if "token" in session:
        user = session["token"]
        habit_list = Habit.objects(username=user)
        hstr_list = All_history.objects(user=user)
        act_list = Activities.objects()
        acts = []
        habits = []
        for hstr in hstr_list:
            if hstr["tit"] not in acts:
                acts.append(hstr["tit"])

        for habit in habit_list:
            if habit["tit"] not in habit:
                habits.append(habit["tit"])

        for a in acts:
            act_in_hstr = All_history.objects(user=user, tit=a)
            combo = 1
            if a not in habits:
                if len(act_in_hstr) >= 3:
                    for i in range(len(act_in_hstr) - 1):
                        if int(act_in_hstr[i + 1].time[6:8]) != int(
                                act_in_hstr[i].time[6:8]) + 1:
                            combo = 0
                        combo += 1
                        if i == len(act_in_hstr) - 2:
                            x_data = Activities.objects(tit=a).first()
                            soc = x_data["soc"]
                            per = x_data["per"]
                            st = x_data["st"]
                            knl = x_data["knl"]
                            cre = x_data["cre"]
                            Habit(username=user,
                                  tit=a,
                                  streak=combo,
                                  soc=soc,
                                  per=per,
                                  knl=knl,
                                  st=st,
                                  cre=cre).save()
            else:
                c_habit = Habit.objects(tit=a).first()
                if c_habit["streak"] < len(act_in_hstr):
                    if len(act_in_hstr) >= 3:
                        for i in range(len(act_in_hstr) - 1):
                            if int(act_in_hstr[i + 1].time[6:8]) != int(
                                    act_in_hstr[i].time[6:8]) + 1:
                                combo = 0
                            combo += 1

                    if combo > c_habit["streak"]:
                        c_habit["streak"] = combo
                        c_habit.save()

        if request.method == "GET":
            habit_list = Habit.objects(username=user)
            return render_template("habit.html", habits=habit_list)
        else:
            att_list = Attribute.objects(username=user).first()
            form = request.form
            for act in act_list:
                act_tit = form.get(act["tit"])

                if act_tit != None:
                    hstr_list = All_history.objects(user=user)
                    des = form["description"]
                    img = form["image"]
                    share = form["share"]
                    for att in att_list:
                        if att in act and att != "id":
                            att_list[att] = att_list[att] + act[att]
                            if att_list[att] < 0:
                                att_list[att] = 0
                        st = act["st"]
                        cre = act["cre"]
                        soc = act["soc"]
                        knl = act["knl"]
                        per = act["per"]

                    att_list.save()
                    All_history(tit=act["tit"],
                                img=img,
                                user=session["token"],
                                des=des,
                                soc=soc,
                                cre=cre,
                                knl=knl,
                                st=st,
                                per=per,
                                time=str(
                                    datetime.now().strftime("%Y%m%d"))).save()
                    if share == "yes":
                        post = Post(tit=act["tit"],
                                    img=img,
                                    user=session["token"],
                                    descript=des)
                        post.save()
                    break
            return redirect("/ca_nhan")
    else:
        return redirect("/sign_in")
Example #30
0
	def get_posts(self):
		return Post.from_blog(self.id)
Example #31
0
 def get_posts(self):
     """Return all posts beloging to the user from a specific blog"""
     return Post.get_posts_by_blog_id(self._id)
def get_images(post_id):
    post = Post.get_by_id(post_id)
    if post.imgs is not None:
        return dumps(post.imgs)
    else:
        return dumps({'imgs': {}})
Example #33
0
 def delete(self, tag, uuid):
     post = Post.objects(id=uuid)[0]
     post.delete()
     self.write('success')
def remove_post(post_id):
    Post.remove_fr_mongo(post_id)
    Assignment.remove_fr_mongo(post_id)
    return "True"