Ejemplo n.º 1
0
    def post(self, id):
        title = self.get_request("post_title","untitled")
        content = self.get_request("post_content","")
        post_status = self.get_request("post_status","public")
        post_status = getPostStatus(post_status)
        post_password = self.get_request("post_password","")
        post_delete = self.get_int_request("p_delete",0)
        content = pyUtility.html_purify(content)
        permalink = self.get_request("post_permalink","")

        nextmove = self.get_request("nextmove","")

        if not pyUtility.isPermaLinkLegal(permalink) or permalink =="":
            dic=dict()
            dic['title'] = "Page Edit"
            dic['error'] = "Permalink is not legal."
            dic['isAdd'] = False
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("page/add_edit.html", **dic)
            return

        user = self.get_current_user()
        r = None
        dic = dict()
        if id !=0:
            if (user['role'] == pyEnum.AccountRole.Admin or user['role'] == pyEnum.AccountRole.Manager):
                r=Post().getByPageID(id, 0, True, False)
            else:
                r=Post().getByPostID(id, user['ID'], False)
        if r == None:
            dic['title'] = "Page Edit"
            dic['error'] = "The record can not be found or you don't have permission to edit it."
            dic['isAdd'] = False
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("page/add_edit.html", **dic)
            return

        if post_status == 'protect':
            r.post_password = pyUtility.md5(post_password)

        r.post_title = title
        r.post_content = content
        r.post_status = post_status
        r.post_modified = str(datetime.datetime.now())
        r.deleted = post_delete
        r.permalink = permalink
        if not r.update():
            dic['error'] = "Page Edit Failed!!"
            dic['isAdd'] = False
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("topic/add_edit.html", **dic)
            return
        if nextmove:
            self.redirect(self.webroot_url(nextmove))
        else:
            self.redirect(self.webroot_url("page/"+permalink))
Ejemplo n.º 2
0
def new_post():
    data_from_client = request.json
    post = Post(title = data_from_client['title'],
                content = data_from_client['content'],
                emitDate = data_from_client['emitDate'],
                expireDate = data_from_client['expireDate'])
    post.save()
    
    return _jsonify(200, 'Postagem salva com sucesso!')
Ejemplo n.º 3
0
def add_post():
    print("addpost")
    text = request.form.get("post")
    lec = Lecture.objects.get(id=request.form.get("lec_id"))
    print lec
    p = Post()
    p.content = text
    p.save()
    lec.posts.append(p)
    lec.save()
    posts = lec.posts
    return render("post.html", lec=lec, posts=posts, isUser=True)
Ejemplo n.º 4
0
    def post(self):
        title = self.get_request("post_title","untitled")
        t = self.get_request("post_content","")
        content = pyUtility.html_purify(t)
        t = self.get_request("post_status","public")
        post_status = getPostStatus(t)
        post_password = self.get_request("post_password","")
        permalink = self.get_request("post_permalink","")

        nextmove = self.get_request("nextmove","")
        if not pyUtility.isPermaLinkLegal(permalink) or permalink =="":
            dic=dict()
            dic['title'] = "Page Add"
            dic['error'] = "Permalink is not legal."
            dic['isAdd'] = True
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("page/add_edit.html", **dic)
            return
        # check
        if not Post().isPageSlugUnique(permalink):
            dic=dict()
            dic['title'] = "Page Add"
            dic['error'] = "Permalink has been used."
            dic['isAdd'] = True
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("page/add_edit.html", **dic)
            return
        ndata = Post()
        if post_status == 'protect':
            ndata.post_password = pyUtility.md5(post_password)
        ndata.post_title = title
        ndata.post_type = 'page'
        ndata.post_author = self.userID
        ndata.post_content = content
        ndata.permalink = permalink
        ndata.post_status = post_status
        ndata.comment_status = "close"
        if ndata.save()<=0:
            dic=dict()
            dic['title'] = "Page Add"
            dic['error'] = "Post Add Failed!!"
            dic['isAdd'] = True
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("page/add_edit.html", **dic)
            return
        if nextmove:
            self.redirect(self.webroot_url(nextmove))
        else:
            self.redirect(self.webroot_url("page/"+permalink))
Ejemplo n.º 5
0
def post_form(post_id):
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        content = form.content.data

        post = Post(user_id=current_user.id,title=title, content=content)
        post.save()
        return redirect(url_for('index'))
    else:
        post = Post.get_by_id(post_id)
        print(post)
        # form.content = post.content
    return render_template("admin/post_form.html", form=form)
Ejemplo n.º 6
0
def del_post(id_post):
    try:
        post_from_db = Post.get(id = id_post)
        post_from_db.delete_instance()

        return _jsonify(200, 'Postagem excluída com sucesso!')
    except Post.DoesNotExist:
        abort(404)
Ejemplo n.º 7
0
    def post(self):
        """ New post class - post method """
        subject = self.request.get("subject")
        content = self.request.get("content")
        author = User.by_name(self.user.name)
        error = ""

        if subject and content:
            to_post = Post(parent=utils.blog_key(),
                           subject=subject,
                           content=content,
                           author=author)
            to_post.put()
            self.redirect('/blog/%s' % str(to_post.key().id()))
        else:
            error = "subject and content, please!"
            self.render("newpost.html",
                        title="New Post",
                        username=self.user.name,
                        subject=subject,
                        content=content,
                        error=error)
Ejemplo n.º 8
0
 def getPosts(self, id=None):
     conn = Connection().getConnection()
     cursor = conn.cursor()
     sql = 'SELECT Id, Text, EngPOS, FilPOS FROM post'
     if id != None:
         sql += ' WHERE id >= ' + str(id)
     cursor.execute(sql)
     row = cursor.fetchone()
     posts = []
     while row is not None:
         posts.append(
             Post(row['Id'], row['Text'], row['EngPOS'], row['FilPOS']))
         row = cursor.fetchone()
     return posts
Ejemplo n.º 9
0
def lecture(slg):
    lec = Lecture.objects.get(slug=slg)

    if request.args.get("addPost"):
        text = request.form.get("post")
        lec = Lecture.objects.get(id=request.form.get("lec_id"))
        u = User.objects.get(id=request.form.get("user_id"))
        p = Post()
        p.content = text
        print u == is_user()
        p.user = u
        p.save()
        lec.posts.append(p)
        lec.save()
        posts = lec.posts
        return redirect("/lecture/"+slg)

    if len(lec.posts) > 0:
        posts = lec.posts
    else:
        posts = 0
    print posts
    return render("post.html", lec=lec, posts=posts, isUser=True)
Ejemplo n.º 10
0
def edit_post(id_post):
    data_from_client = request.json

    try:
        post_from_db = Post.get(id = id_post)
    except Post.DoesNotExist:
        abort(404)

    post_from_db.title = data_from_client['title']
    post_from_db.content = data_from_client['content']
    post_from_db.emitDate = data_from_client['emitDate']
    post_from_db.expireDate = data_from_client['expireDate']
    post_from_db.save()

    return _jsonify(200, 'Postagem salva com sucesso!')
Ejemplo n.º 11
0
def _extract_useful_info(posts):
    filtered = []
    for post in posts:
        is_ad = post['marked_as_ads']
        if is_ad:
            continue
        text = post['text']
        if len(text) > 1000:
            continue
        views = post['views']['count']
        likes = post['likes']['count']
        date = datetime.utcfromtimestamp(post['date'])
        try:
            img = post['attachments'][0]['photo']['sizes'][4]['url']
        except KeyError:
            continue
        filtered.append(Post(text, img, date, views, likes))
    return filtered
Ejemplo n.º 12
0
def create_post(thread: Thread, args: dict) -> Post:
    "Creates a new post from the given data."

    board_id = thread.board
    validate_captcha(board_id, args)

    ip = get_ip_address()
    poster, flooding = get_or_update_poster(thread.id, ip)

    update_poster_slip(poster, args)

    media_id = get_media_id(board_id)

    post = Post(
        body=args["body"],
        subject=args["subject"],
        thread=thread.id,
        poster=poster.id,
        media=media_id,
        spoiler=args["spoiler"],
    )
    db.session.add(post)
    db.session.flush()

    replies = get_replies(post.id, post.body)
    for reply in replies:
        db.session.add(reply)

    if not flooding:
        # bump the thread if the last poster isn't the same
        thread.last_updated = post.datetime
        db.session.add(thread)

    db.session.flush()
    db.session.commit()

    publish_thread(thread, post, replies)
    invalidate_posts(thread, replies)
    # import here to prevent a circular import
    # TODO: fix circular import with NewPost
    from thread import invalidate_board_cache
    invalidate_board_cache(board_id)

    return post
Ejemplo n.º 13
0
def suppressionPost(request):
    idPost = request.form.get('idPost')

    return Post.suppressionPost(idPost)
Ejemplo n.º 14
0
def post(id_post):
    try:
        post = Post.get(id=id_post)
        return jsonify(post.to_dict())
    except Post.DoesNotExist:
        abort(404)
Ejemplo n.º 15
0
def posts_():
    return jsonify([post.to_dict() for post in Post.select()])
Ejemplo n.º 16
0
def miseAjourPost(request):
    idPost = request.form.get('idPost')
    content = request.form.get('content')
    return Post.miseAjourPost(idPost, content)
Ejemplo n.º 17
0
def creationPost(request):
    content = request.form.get('content')
    idTopic = request.form.get('idTopic')
    idUser = request.form.get('idUser')

    return Post.creationPost(content, idTopic, idUser)
Ejemplo n.º 18
0
 def post(self, thread_id):
     parser = reqparse.RequestParser()
     parser.add_argument("subject", type=str)
     parser.add_argument("body", type=str, required=True)
     parser.add_argument("useslip", type=inputs.boolean)
     parser.add_argument("spoiler", type=inputs.boolean)
     # check captcha cooldown
     on_cooldown = cooldown.on_captcha_cooldown()
     # only check of captcha if the client is not on cooldown
     if on_cooldown is False:
         if app.config.get("CAPTCHA_METHOD") == "RECAPTCHA":
             parser.add_argument("recaptcha-token", type=str, required=True)
         elif app.config.get("CAPTCHA_METHOD") == "CAPTCHOULI":
             parser.add_argument("captchouli-id", type=str, required=True)
             for img_num in range(0, 9):
                 # don't bother validating too closely since captchouli takes care of
                 # that for us
                 parser.add_argument("captchouli-%d" % img_num,
                                     type=str,
                                     default=False)
     args = parser.parse_args()
     ip = None
     # reverse proxy support
     if 'X-Forwarded-For' in request.headers:
         ip = request.headers.getlist("X-Forwarded-For")[0].rpartition(
             ' ')[-1]
     else:
         ip = request.environ["REMOTE_ADDR"]
     # check captcha if necessary
     board_id = db.session.query(Thread).filter_by(id=thread_id).one().board
     if on_cooldown is False:
         if app.config.get("CAPTCHA_METHOD") == "RECAPTCHA":
             google_response = requests.post(
                 "https://www.google.com/recaptcha/api/siteverify",
                 data={
                     "secret": app.config["RECAPTCHA_SECRET_KEY"],
                     "response": args["recaptcha-token"]
                 }).json()
             if google_response["success"] is False:
                 raise CaptchaError("Problem getting reCAPTCHA", board_id)
             if google_response["score"] < app.config["RECAPTCHA_THRESHOLD"]:
                 raise CaptchaError("reCAPTCHA threshold too low", board_id)
         elif app.config.get("CAPTCHA_METHOD") == "CAPTCHOULI":
             captchouli_form = {"captchouli-id": args["captchouli-id"]}
             for img_num in range(0, 9):
                 key = "captchouli-%d" % img_num
                 captchouli_form[key] = args[key]
             if not captchouli.valid_solution(captchouli_form):
                 raise CaptchaError("Incorrect CAPTCHA response", board_id)
     cooldown.refresh_captcha_cooldown()
     poster = db.session.query(Poster).filter_by(thread=thread_id,
                                                 ip_address=ip).first()
     body = args["body"]
     should_bump = False
     if poster is None:
         poster_hex = gen_poster_id()
         poster = Poster(hex_string=poster_hex,
                         ip_address=ip,
                         thread=thread_id)
         db.session.add(poster)
         db.session.flush()
         # bump thread if the poster hasn't posted in this thread before
         should_bump = True
     else:
         # bump thread if this poster isn't the same as the one who posted last in the thread
         last_post = db.session.query(Post).filter_by(
             thread=thread_id).order_by(Post.id.desc()).first()
         if last_post.poster != poster.id:
             should_bump = True
     if args.get("useslip") is True:
         slip = get_slip()
         if slip and (slip.is_admin or slip.is_mod):
             poster.slip = slip.id
             db.session.add(poster)
     media_id = None
     if "media" in request.files and request.files["media"].filename:
         uploaded_file = request.files["media"]
         mimetype = uploaded_file.content_type
         board = db.session.query(Board).filter_by(id=board_id).one()
         expected_mimetypes = board.mimetypes
         if re.match(expected_mimetypes, mimetype) is None:
             db.session.rollback()
             raise InvalidMimeError(mimetype, board_id)
         media = storage.save_attachment(uploaded_file)
         media_id = media.id
     post = Post(body=body,
                 subject=args["subject"],
                 thread=thread_id,
                 poster=poster.id,
                 media=media_id,
                 spoiler=args["spoiler"])
     db.session.add(post)
     db.session.flush()
     replying = re.finditer(REPLY_REGEXP, body)
     replies = set()
     if replying:
         for match in replying:
             raw_reply_id = match.group(2)
             reply_id = int(raw_reply_id)
             replies.add(reply_id)
         for reply_id in replies:
             reply = Reply(reply_from=post.id, reply_to=reply_id)
             db.session.add(reply)
     if should_bump:
         thread = db.session.query(Thread).filter_by(id=thread_id).one()
         thread.last_updated = post.datetime
         db.session.add(thread)
     db.session.flush()
     db.session.commit()
     pubsub_client = keystore.Pubsub()
     pubsub_client.publish(
         "new-post", json.dumps({
             "thread": thread_id,
             "post": post.id
         }))
     for reply_id in replies:
         pubsub_client.publish(
             "new-reply",
             json.dumps({
                 "post": post.id,
                 "thread": post.thread,
                 "reply_to": reply_id
             }))
Ejemplo n.º 19
0
def index():
    posts = Post.get_all()
    return render_template("index.html", posts=posts)
Ejemplo n.º 20
0
def listePost(request):
    idTopic = request.form.get('idTopic')

    return Post.listePost(idTopic)
Ejemplo n.º 21
0
 def update(self, response):
     for train in response['train']:
         self.trains[train['idx']].update(train)
     self.posts = {post['idx']: Post(post) for post in response['post']}
Ejemplo n.º 22
0
    def post(self):
        title = self.get_request("post_title","untitled")
        content = self.get_request("post_content","")
        content = pyUtility.html_purify(content)
        post_status = self.get_request("post_status","public")
        post_status = getPostStatus(post_status)
        post_password = self.get_request("post_password","")
        post_tags = self.get_request("post-tags","")
        catgory_array = self.get_arguments("post-category","") # array
        comment_status = self.get_request("p_feedback","")
        nextmove = self.get_request("nextmove","")
        if comment_status !="open":
            comment_status ="close"


        ndata = Post()
        if post_status == 'protect':
            ndata.post_password = pyUtility.md5(post_password)
        ndata.post_title = title
        ndata.post_type = 'post'
        ndata.post_author = self.userID
        ndata.post_content = content
        ndata.post_status = post_status
        ndata.comment_status = comment_status
        newID = ndata.save()
        if newID <= 0:
            dic=dict()
            dic['title'] = "Post Add"
            dic['error'] = "Post Add Failed!!"
            dic['isAdd'] = False
            dic['data'] = None
            dic['nextmove'] = nextmove
            self.render("topic/add_edit.html", **dic)
            return

        # add tags and add relations
        tags = post_tags.split(',')
        tags_array=[]
        for tag in tags:
            tag = tag.strip()
            if tag == "":
                continue
            tags_array.append(tag)

        termsIDs = []
        if tags_array:
            TermTaxonomy().insertTags(tags_array)
            tagIDs = TermTaxonomy().getTagIDsByArray(tags_array)
            termsIDs = termsIDs + tagIDs
        if catgory_array:
            termsIDs = termsIDs + catgory_array
        termsIDs = list(set(termsIDs))
        if termsIDs:
            TermRelationships().removeAllByPostID(newID)
            TermRelationships().addPostTermRelations(newID,termsIDs)
            # ReCalculate Count
            TermTaxonomy().calculatePostCountByTermIDs(termsIDs)
        if nextmove:
            self.redirect(self.webroot_url(nextmove))
        else:
            self.redirect(self.webroot_url("topic/show/"+str(newID)))
Ejemplo n.º 23
0
 def post(self, thread_id):
     parser = reqparse.RequestParser()
     parser.add_argument("subject", type=str)
     parser.add_argument("body", type=str, required=True)
     parser.add_argument("useslip", type=inputs.boolean)
     parser.add_argument("spoiler", type=inputs.boolean)
     args = parser.parse_args()
     ip = ip_to_int(request.environ["REMOTE_ADDR"])
     poster = db.session.query(Poster).filter_by(thread=thread_id,
                                                 ip_address=ip).first()
     body = args["body"]
     should_bump = False
     if poster is None:
         poster_hex = gen_poster_id()
         poster = Poster(hex_string=poster_hex,
                         ip_address=ip,
                         thread=thread_id)
         db.session.add(poster)
         db.session.commit()
         # bump thread if the poster hasn't posted in this thread before
         should_bump = True
     if args.get("useslip") is True:
         slip = get_slip()
         if slip and (slip.is_admin or slip.is_mod):
             poster.slip = slip.id
             db.session.add(poster)
             db.session.commit()
     media_id = None
     if "media" in request.files and request.files["media"].filename:
         uploaded_file = request.files["media"]
         file_ext = uploaded_file.filename.rsplit('.', 1)[1].lower()
         media = Media(ext=file_ext)
         db.session.add(media)
         db.session.commit()
         media_id = media.id
         full_path = os.path.join(app.config["UPLOAD_FOLDER"],
                                  "%d.%s" % (media_id, file_ext))
         uploaded_file.save(full_path)
         if file_ext != "webm":
             # non-webm thumbnail generation
             thumb = Image.open(full_path)
             if thumb.mode in ("RGBA", "LA"):
                 background = Image.new(thumb.mode[:-1], thumb.size,
                                        (255, 255, 255))
                 background.paste(thumb, thumb.split()[-1])
                 thumb = background
             size = thumb.size
             scale_factor = 0
             # width > height
             if size[0] > size[1]:
                 scale_factor = 500 / size[0]
             else:
                 scale_factor = 500 / size[1]
             new_width = int(thumb.width * scale_factor)
             new_height = int(thumb.height * scale_factor)
             thumb = thumb.resize((new_width, new_height), Image.LANCZOS)
             thumb.convert("RGB").save(
                 os.path.join(app.config["THUMB_FOLDER"],
                              "%d.jpg" % media_id), "JPEG")
         else:
             # FIXME: webm thumbnail generation
             pass
     post = Post(body=body,
                 subject=args["subject"],
                 thread=thread_id,
                 poster=poster.id,
                 media=media_id,
                 spoiler=args["spoiler"])
     db.session.add(post)
     db.session.commit()
     replying = re.finditer(REPLY_REGEXP, body)
     if replying:
         for match in replying:
             for raw_reply_id in match.groups():
                 reply_id = int(raw_reply_id)
                 reply = Reply(reply_from=post.id, reply_to=reply_id)
                 db.session.add(reply)
                 db.session.commit()
     if should_bump:
         thread = db.session.query(Thread).filter_by(id=thread_id).one()
         thread.last_updated = post.datetime
         db.session.commit()
Ejemplo n.º 24
0
 def __init__(self, response):
     self.trains = {train['idx']: Train(train) for train in response['train']}
     self.posts = {post['idx']: Post(post) for post in response['post']}
Ejemplo n.º 25
0
def show_post(slug):
    post = Post.get_by_slug(slug)
    return render_template("post_view.html", post=post)