Example #1
0
def create_new_comment():
    photo_id = request.json['photo_id']
    content = request.json['content']
    user = request.json['user']

    new_comment = Comment(photo_id=photo_id, content=content, username=user)
    new_comment.save_to_mongo()

    return jsonify(get_comments(photo_id))
Example #2
0
 def post(self):
     user = users.get_current_user()
     comment = Comment(
         email=user.nickname(),
         time=datetime.now(),
         content=self.request.get('comment'),
         type=self.request.get('type'),
     )
     comment.put()
     time.sleep(.2)
     self.redirect('/studentforum')
     template = env.get_template('studentforum.html')
     self.response.write(template.render())
Example #3
0
	def post(self, comment_id):
		self.response.headers["Content-Type"] = "application/json"
		try:
			user_id = self.request.POST["user"]
			comment = Comment()
			comment.add_flag(comment_id, user_id)
		except Exception:
			logging.exception("Failed to report comment %s" % comment_id)
			out = {"success": 0}
			self.response.write(json.dumps(out))
		else:
			logging.info("Comment reported successfully")
			out = {"success": 1}
			self.response.write(json.dumps(out))
Example #4
0
	def get(self, video_id):
		self.response.headers["Content-Type"] = "application/json"
		try:
			user_id = self.request.get("user")
			comment = Comment()
			comment_list = comment.get_comments(video_id, user_id)
		except Exception:
			logging.exception("Failed getting comments")
			out = {"success": 0}
			self.response.write(json.dumps(out))
		else:
			logging.info("Comments retrieved successfully")
			out = {"success": 1, "comments": comment_list}
			self.response.write(json.dumps(out))
Example #5
0
	def post(self, video_id):
		self.response.headers["Content-Type"] = "application/json"
		try:
			user_id = self.request.POST["user"]
			text = self.request.POST["comment"]
			comment = Comment()
			id = comment.add_comment(text, video_id, user_id)
		except Exception:
			logging.exception("Failed to add a comment")
			out = {"success": 0}
			self.response.write(json.dumps(out))
		else:
			logging.info("Comment added successfully")
			out = {"success": 1, "comment_id":id}
			self.response.write(json.dumps(out))
def load_script(data_path, characters, max_length):
    c_map = {c.name: c for c in characters}
    comments = []
    current_line = []
    previous_character = None

    with open(data_path) as f:
        lines = list(f)
        for line in tqdm(lines, desc='reading script'):
            if line.startswith('    ' * 9):
                current_character = c_map[line.strip().lower().capitalize()]

                if previous_character is not None and previous_character != current_character:
                    text = ' '.join(current_line)
                    comment = Comment(body=text, author=previous_character)
                    comments.append(comment)

                    if max_length is not None and len(comments) >= max_length:
                        break

                    current_line.clear()
                previous_character = current_character
            elif line.startswith('    ' * 7):
                pass
            elif line.startswith('    ' * 6):
                line = line.strip()

                if line != '':
                    current_line.append(line)

    return comments
Example #7
0
 def get(self):
     query = Comment.query()
     query_result = query.order(-Comment.time)
     query_result = query_result.fetch()
     var = {"comments": query_result}
     template = env.get_template('studentforum.html')
     self.response.write(template.render(var))
Example #8
0
 def get_comments(self):
     alist = []
     for i in self.cmtids:
         item = Comment.get_comment_by_cmtid(i)
         if item.status == 1:
             alist.append(item)
     alist = sorted(alist, key=lambda cmt : cmt.like-cmt.unlike, reverse=True)
     return alist
Example #9
0
    def load_comment_options(self, data=None):
        print(data)
        try:
            if data is None:
                file, _ = QFileDialog.getOpenFileName(self, 'Open file')
                with open(file, 'r') as f:
                    data = f.read()

            self.comment_options = Comment.parse_options(data)
            self.__setup_ui()
        except ValueError:
            QMessageBox.information(self, 'Error', 'Parsing failed')
Example #10
0
 def add_comment(cid, comment, author):
     cmtid = Comment.insert_comment(comment, author)
     item = db["course"].find_one({"_id": cid})
     alist = item["cmtids"]
     alist.append(cmtid)
     db["course"].find_and_modify(
         {"_id": cid},
         update={
             "$set":{
                 "cmtids": alist
             }
         }
     )
     return cmtid
from comments import Comment
from language import Python, CPP

options = {
    'filling': '=',
    'filling2': '-',
    'right-char': True,
    'capitalize': True,
    'length': 30
}

lang = Python()
print(Comment.gen_comment('header', lang, options))

data = """dummy text
# ===================================== 
# ================= d ================= 
# ===================================== 
other dummy text"""
print()
print(Comment.parse_options(data))

data = """# ============= #
# --- DUMMY --- #
# ============= #"""
print()
print(Comment.parse_options(data))
def deserialize_comment(comment: str) -> Comment:
    json_data = json.loads(comment)
    return Comment(json_data.title, json_data.comment, deserialize_time(json_data.time))
    def test_create_comments_with_correct_details(self):
        results = Comment(self.comment, self.author).create_comment()

        self.assertEqual(results, "comment succesfully created")
Example #14
0
    def sendMessageActivity(self, user=None):
        '''Given a User Object, or None for all,
           Send Message Activity Email to user(s)

           Send notification about Comments on Users message
           or on comments to messages user has liked or commented on
           Since the last time run

           TO DO: Implement dynamtic send interval based
                  on number of likes and comments
        '''
        data = self._getMessageComments(user.id if user else None)
        for user_id in data.keys():
            purge = []
            user = User(user_id)

            print 'Email to:', data[user_id]['email']

            posts = []
            for message in data[user_id]['messages']:
                # message data
                mUser = User(message['message_user_id'])

                # comments data
                comments = []
                for i, cid in enumerate(message['comment_ids']):
                    cUser = User(Comment(cid).user_id)
                    profile_url = 'http://%s/profile.py?u=%s' % \
                                  (self.conf.baseurl, encrypt_int(cUser.id))
                    comments.append({'name': cUser.fullname,
                                     'profile_image': getUserImage(cUser.id),
                                     'profile_url': profile_url,
                                     'text': message['comment_texts'][i]})
                    purge.append([user_id, cid])

                # activity message
                message_url = 'http://%s/main.py#message_card_%s' \
                              % (self.conf.baseurl, message['id'])
                post_link = a(b('Post', style='font-size:14px'),
                              href=message_url)
                orig_post = message['message_text'][0:119]
                if len(message['message_text']) > 120:
                    orig_post += ' ...'
                if user_id == mUser.id:
                    who = 'your'
                else:
                    who = mUser.fullname + "'s"
                activity_msg = '%s new comment%s on %s %s<p/>%s' % \
                               (len(comments),
                                's' if len(comments) > 1 else '',
                                who,
                                post_link,
                                orig_post)
                posts.append({
                    'activity_msg': activity_msg,
                    'comments': comments,
                    'message_url': 'http://%s/main.py#message_card_%s' \
                           % (self.conf.baseurl, message['id'])
                })

            html = open('%s/lib/emails/message_activity.html' % \
                        self.conf.basedir).read()
            html = Template(html)
            html = html.render(posts=posts)
            self.email.send_email(#to='*****@*****.**',
                                  to=user.email,
                                  subject='Recent activity',
                                  body='',
                                  html=html)

            # purge notify queue
            for user_id, comment_id in purge:
                # copy queue recors to queue_log
                sql = 'insert into notify_queue_log ' \
                      '(user_id, comment_id, created) ' \
                      'select user_id, comment_id, created ' \
                      'from notify_queue ' \
                      'where user_id = %s and comment_id = %s'
                self.db.execute(sql, params=(user_id, comment_id))

                # delete queue records
                sql = 'delete from notify_queue ' \
                      'where user_id = %s and comment_id = %s'
                self.db.execute(sql, params=(user_id, comment_id))
 def test_create_comment_with_no_author(self):
     results = Comment(self.comment, self.wrong_author).create_comment()
     self.assertEqual(results, "comment or author cannot be empty")
Example #16
0
 def update_comments(self, key=None, new_value=None):
     if key is not None:
         self.comment_options[key] = new_value
     text = Comment.gen_comment(self._ui.lineEdit_pretty_comment.text(), self.language,
                                self.comment_options)
     self._ui.textEdit.setText(text)
Example #17
0
 def get_posts(self):
     return Comment.from_blog(self.id)
Example #18
0
    def post(self, post_id):
        post = db.get(db.Key.from_path('Post', int(post_id),
                                       parent=blog_key()))
        #print "post_id:",post_id
        all_comments = db.GqlQuery(
            "SELECT * FROM Comment WHERE parent_post = " + post_id +
            "order by created desc")
        all_likes = db.GqlQuery("SELECT * FROM Like WHERE parent_post = " +
                                post_id)

        if not post:
            self.error(404)
            return
        """
            On posting comment, new comment tuple is created and stored,
            with relationship data of user and post.
        """
        if (self.user):
            if (self.request.get('comment')):  #Create comment tuple
                cmt = Comment(parent=blog_key(),
                              author=self.user.key().id(),
                              comment=self.request.get('comment'),
                              parent_post=int(post_id))
                cmt.put()
                self.redirect('/blog/%s' % post_id)

            if (self.request.get('like') and
                (self.request.get('like') == "true")):  #Create Like object
                liker = self.user.key().id()
                liked_by_all = db.GqlQuery(
                    "SELECT DISTINCT liked_by FROM Like WHERE parent_post = " +
                    post_id)
                liked_list = liked_by_all.fetch(limit=10000)
                likes_list = str([x.liked_by for x in liked_list])
                previous_like = str(liker) in likes_list

                if liker == post.author:
                    error_msg = "It goes without saying that you like your own post."
                    num_likes = all_likes.count()
                    self.render("permalink.html",
                                post=post,
                                comments=all_comments,
                                error=error_msg,
                                num_likes=num_likes,
                                post_id=post_id)
                    return

                elif not previous_like:
                    new_like = Like(parent=blog_key(),
                                    liked_by=self.user.key().id(),
                                    parent_post=int(post_id))
                    new_like.put()

                else:
                    error_msg = "You already liked this post."
                    num_likes = all_likes.count()
                    self.render("permalink.html",
                                post=post,
                                comments=all_comments,
                                error=error_msg,
                                num_likes=num_likes,
                                post_id=post_id)
                    return

        else:
            self.render(
                "login-form.html",
                error=
                "You need to be logged in to like posts or submit comments.")
            #return

        self.redirect('/blog/%s' % post_id)
Example #19
0
 def get_all_comments(self):
     alist = []
     for i in self.cmtids:
         alist.append(Comment.get_comment_by_cmtid(i))
     return alist
Example #20
0
 def new_comment(self, username, content, date=datetime.datetime.utcnow()):
     comment = Comment(photo_id=self.id,
                       content=content,
                       username=self.username,
                       date=date)
     comment.save_to_mongo()
Example #21
0
 def comments(self):
     comments = []
     sql = 'select id from messages where reference_id = %s'
     for row in self.db.query(sql, params=[self.id]):
         comments.append(Comment(row['id']))
     return comments