def GET(self, post_id): post_id = int(post_id) cur_user_id = model.User().current_id() post = model.Post().view(post_id) # 只有作者(已登录)才能删除自己的文章 if post and post['user_id'] == cur_user_id: # 删除文章的同时也会删除相关的所有评论 model.Comment(post_id).ddel() model.Post().ddel(post_id) raise web.seeother('/account/posts') elif cur_user_id: # 用户已登录,但不是作者 return titled_render().failed('操作受限,你无权删除其他人的文章') else: # 用户未登录 return titled_render().failed('操作受限,请先<a href="/login">登录</a>')
def generate(self, user, when): return model.Post( when, '{}: {} {} {}'.format(random.choice(self.INTRODUCTION), random.choice(self.NAME), random.choice(self.VERB), random.choice(self.END)), None, random.choice(self.sources), None)
def POST(self): i = web.input(title='', content='') post_id = model.Post().new(i.title, i.content, model.User().current_id()) if post_id: raise web.seeother("/view/%d" % post_id) else: return titled_render().failed('你不应该到达这里')
def generate(self, user, date): (a, b), c = getRandomGossip() news_outlet = choice(self.sources) post = model.Post(date, a, model.Image(c), news_outlet, None) comment = model.Comment(b, user, post) post.comments.append(comment) return post
def resource_upload(): form = PostUpdateForm() if form.validate_on_submit(): img_ids_list = [ int(id) for id in form.image.data.split(';') if id != '' ] post_db = model.Post(user_key=auth.current_user_key(), title=form.title.data, content=form.content.data, keywords=form.keywords.data, image_ids_string=form.image.data, img_ids=img_ids_list, image_url=get_img_url(img_ids_list[0])) post_db.put() flask.flash('New post was successfully created!', category='success') return flask.redirect(flask.url_for('post_list', order='-created')) return flask.render_template( 'resource/resource_upload.html', title='Resource Upload', html_class='resource-upload', get_upload_url=flask.url_for('api.resource.upload'), has_json=True, form=form, upload_url=blobstore.create_upload_url( flask.request.path, gs_bucket_name=config.CONFIG_DB.bucket_name or None, ), )
def user(): user_id = request.args.get("user_id") if user_id == None: user_id = current_user.id # enable registration link current_cycle = model.session.query(model.SeasonCycle).\ order_by(model.SeasonCycle.id.desc()).\ first() #print current_cycle.cyclename users = model.session.query(model.User) user = users.get(user_id) form = PostForm() if form.validate_on_submit(): new_post = model.session.\ add(model.Post(body=form.post.data, user_id= g.user.id)) model.session.commit() flash('Your post is live!') return redirect('user') return render_template('user.html', title='Profile', users=users, user=user, current_cycle=current_cycle, form=form)
def POST(self, post_id): i = web.input(title='', content='') post_id = int(post_id) if model.Post().update(post_id, i.title, i.content): raise web.seeother("/view/%d" % post_id) else: return titled_render().failed('你不应该到达这里')
def add_post(self, boardname, title, owner, content, fromhost): p = model.Post(bid=model.Board.get_bid_by_name(boardname), title=title, owner=owner, content=content, fromhost=fromhost) p.save() print "Add post %s to %s DONE." % (title, boardname)
def GET(self, post_id): post_id = int(post_id) post = model.Post().view(post_id) if post: comment = model.Comment(int(post_id)) comments = comment.quote(comment.list()) comment_lis = util.comments_to_lis(comments) return titled_render(post.title).view(post, comment_lis) else: raise web.seeother('/')
def GET(self, post_id): post_id = int(post_id) cur_user_id = model.User().current_id() post = model.Post().view(post_id) # 只有作者(已登录)才能编辑自己的文章 if post and post['user_id'] == cur_user_id: return titled_render().edit(post) elif cur_user_id: # 用户已登录,但不是作者 return titled_render().failed('操作受限,你无权编辑其他人的文章') else: # 用户未登录 return titled_render().failed('操作受限,请先<a href="/login">登录</a>')
def generate(self, user, when): if random.random() < 0.1: driver = webdriver.Chrome(r'chromedriver') driver.get('https://tomforth.co.uk/guardiancomments/') comment = driver.find_element_by_class_name('commentBody') comment = Translator().translate(comment.text, dest='he').text driver.close() return model.Post(when, comment, None, user, None) else: image = requests.get( requests.get('http://inspirobot.me/' 'api?generate=true').content).content path = os.path.join( model.IMAGE_DIR, 'generated', '{}.jpg'.format(str(random.randint(0, 0xffffffff)))) open(path, 'wb').write(image) return model.Post( when, random.choice(self.IMAGE_COMMENTS).format( good_day=random.choice(self.GOOD_DAY)), model.Image(path), user, None)
def GET(self): i = web.input(page='1') page = int(i.page) page_posts, page_count = model.Post().list(page) #计算分页 grace = 5 range = grace * 2 start = page - grace if page - grace > 0 else 1 end = start + range if end > page_count: end = page_count start = end - range if end - range > 0 else 1 return titled_render().list(page_posts, page_count, page, start, end)
def do_post(message, place, route_id, route_step, session): success = hh.create_pano(hh.get_pano_id(place.lat, place.lon)) new_post = model.Post(route_id=route_id, route_step=route_step) mapper.map_places(model.current_route().places_visited()) if success: post = fb_client.create_360_photo_post(message=message, image_path='pano.jpg') new_post.fb_post_id = post['post_id'].split('_')[-1] else: new_post.fb_post_id = fb_client.create_post( message='Failed to do street view ' + CONFIG['messages']['suffix'], image_path='map.png')['post_id'] session.add(new_post) return new_post
def create_post( blog_name: str, post_title: str, tags: List[str], uow: AbstractUnitOfWork ): with uow: blog = uow.repo.get(name=blog_name) if not blog: blog = model.Blog(blog_name) uow.repo.add(blog) # create a post post = model.Post(post_title) post.blog = blog # create tags tag_list = [model.Tag(t) for t in tags] post.tags.extend(tag_list)
def GET(self, part): # 获取当前登录用户的状态 cur_user_id = model.User().current_id() status = model.User().status(cur_user_id) # 已登录用户才能进行账户管理 if cur_user_id: dispatch = {'posts': titled_render('文章').account_posts(model.Post().digest_list(cur_user_id)), 'settings': titled_render('设置').account_settings(status['username'], status['picture'], status['description'], status['email'])} if part in dispatch: return dispatch[part] else: # 无法访问 raise web.notfound() # 用户未登录 return titled_render().failed('操作受限,请先<a href="/login">登录</a>')
def post(self, username): # TODO: authorize # find author user author_user = model.User.query.filter_by(username=username).first() if author_user == None: raise NotFoundException() # create post args = post_parser["request_parser"].parse_args() post = model.Post(title=args["title"], body=args["body"]) # link to user author_user.posts.append(post) model.db.session.add(post) model.db.session.commit() return post
def new_post(): req_or_off = request.form.get("req_or_off") amt_milk = request.form.get("amt_milk") recurring = request.form.get("recurring") blurb = request.form.get("blurb") p = model.Post() p.user_id = session['id'] p.req_or_off = req_or_off p.date = datetime.strptime(str(datetime.now()).split()[0], "%Y-%m-%d") p.amt_milk = amt_milk p.recurring = recurring p.blurb = blurb model.session.add(p) model.session.commit() #return render_template("newpost.html") return redirect(url_for("milk_exchange_board"))
def load_posts(session): with open('seed_data/posts.csv') as csvfile: cluster_info = csv.reader(csvfile, delimiter='|') for row in cluster_info: try: parent_cluster = row[0] feature_vector = eval(row[1]) url = row[2] title = row[3] excerpt = row[4] blog = session.query(model.Blog).filter_by(url=row[5]).first() post = model.Post(cluster_id=parent_cluster, blog_id=blog.id, url=url, excerpt=excerpt, title=title, feature_vector=feature_vector) session.add(post) session.commit() except: session.rollback() continue
def POST(self): i = web.input(title='', content='', upload_file={}, bankuai='', url='') fn = '' subpath = 'static/video2/' if i['upload_file'].filename == '': if i.url == '': return titled_render().failed('没有视频不能发表新帖') else: fn = i.url else: fn = subpath + i['upload_file'].filename f = open(fn, 'w') f.write(i['upload_file'].file.read()) f.close() bn = 1 u = 'https://35.231.12.128:8888/' if bn == 1 and i['upload_file'].filename.split('.')[-1] != 'mkv': cmd = 'ffmpeg -i ' + fn + ' -vcodec h264 -s 320*240 -f mp4 ' + 'static/%s' % i[ 'upload_file'].filename + '.mp4' '''r=os.system(cmd) if r!=0: print '转码失败' os.system('rm -rf '+'static/%s'%i['upload_file'].filename) return titled_render().failed('似乎是不支持的视频格式或文件格式损坏,请使用编解码工具确认文件信息') ''' thr = Thread(target=os.system, args=cmd) thr.start() #call_cmd(cmd) fn = u + fn + '.mp4' else: fn = u + fn post_id = model.Post().new(i.title, i.bankuai, i.content, fn, model.User().current_id()) if post_id: raise web.seeother("/view/%d" % post_id) else: return titled_render().failed('你不应该到达这里')
def test_callback(call): if call.data == "create_post": bot.answer_callback_query(call.id, "Criando postagem!") post = model.Post() post_dict[call.message.chat.id] = post msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "Criando postagem. Enviar uma Frase Sera Postada No Canal @DextyOficial 📝😻." ) bot.register_next_step_handler(msg, process_word_name) if call.data == "add_definition": bot.answer_callback_query(call.id, "Adicionando definição!") post = post_dict[call.message.chat.id] word = post.words[-1] definition_number = len(word.definitions) + 1 msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="Criando definição {0}.Enviar definição.".format( definition_number)) bot.register_next_step_handler(msg, process_adding_definition) if call.data == "add_synonyms": bot.answer_callback_query(call.id, "Adicionando sinônimos!") msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "Adicione alguns sinônimos neste formato: sinônimo, sinônimo, sinônimo." ) bot.register_next_step_handler(msg, process_synonyms) if call.data == "add_tags": bot.answer_callback_query(call.id, "Adicionando tags!") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Adicionando tags!") msg = bot.send_message( chat_id=call.message.chat.id, text='Escolha um conjunto de tags nas opções abaixo.', reply_markup=tags_markup(call.message)) bot.register_next_step_handler(msg, process_adding_tags) if call.data == "add_links": bot.answer_callback_query(call.id, "Adicionando links!") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Adicionando links!") msg = bot.send_message( chat_id=call.message.chat.id, text='Adicionar link para Oxford Dictionary! Você pode pular ' 'pressionando o botão "Pular"', reply_markup=skip_markup()) bot.register_next_step_handler(msg, process_adding_links_oxford) if call.data == "add_new_word": bot.answer_callback_query(call.id, "Adicionando nova palavra!") msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "Adicionando nova palavra! Enviar palavra para postagem de vocabulário." ) bot.register_next_step_handler(msg, process_word_name) if call.data == "cancel": bot.answer_callback_query(call.id, "[ ❎ ] Cancelando a criação da postagem!") post_dict.pop(call.message.chat.id) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="📝Crie uma nova postagem aqui.", reply_markup=main_menu_markup()) if call.data == "finish": bot.answer_callback_query(call.id, "[ ❓ ] Esta é a sua postagem!") post = post_dict[call.message.chat.id] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=post.print_post(), parse_mode="Markdown") links = post.print_links() if links: bot.send_message(call.message.chat.id, links, parse_mode="Markdown") bot.send_message( call.message.chat.id, "Você pode enviar essas postagens para o armazenamento ou editá-las manualmente e depois " "Envie isto. Pressione o botão 'Cancelar' para não fazer isso.", reply_markup=send_to_storage_markup()) if call.data == "send_to_storage": bot.answer_callback_query(call.id, "[ ⬇️ ] Enviando para armazenamento!") post = post_dict[call.message.chat.id] bot.send_message(storage_channel_id, post.print_post(), parse_mode="Markdown") links = post.print_links() if links: bot.send_message(storage_channel_id, links, parse_mode="Markdown") post_dict.pop(call.message.chat.id) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="📝Crie uma nova postagem aqui.", reply_markup=main_menu_markup()) if call.data == "edit_before_sending": bot.answer_callback_query(call.id, "Editando!") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="[ 📝 ] Envie a postagem editada manualmente aqui.") post = post_dict[call.message.chat.id] msg = bot.send_message(call.message.chat.id, post.print_post()) bot.register_next_step_handler(msg, process_edited_post) if call.data == "cancel_sending_to_storage": post_dict.pop(call.message.chat.id) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="📝Crie uma nova postagem aqui.", reply_markup=main_menu_markup())
def GET(self): i = web.input(page='1') page = int(i.page) page_posts, page_count = model.Post().list(page) return titled_render().list(page_posts, page_count, page)
def post_from_praw_submission(submission): return model.Post(r_id=submission.id, content=submission.selftext, title=submission.title, created=datetime.utcfromtimestamp( submission.created_utc))
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import model from orm import Backend import db db.setup({'host': 'localhost', 'user': '******', 'passwd': 'test', 'db': 'blog'}) user = Backend('user').find_by_username('username') if user and user.check('password'): print('auth') user = model.User('username', 'email', 'real_name', 'password', 'bio', 'status', 'role') if Backend('user').create(user): print('fine') user = Backend('user').find(12) user.real_name = 'blablabla....' if Backend('user').save(user): print('user saved') if Backend('user').delete(user): print('delete user failed') post = model.Post('title', 'slug', 'description', 'html', 'css', 'js', 'category', 'status', 'comments', 'author') if not Backend('post').create(post): print('created failed')
def test_callback(call): if call.data == "create_post": bot.answer_callback_query(call.id, "Criando postagem!") post = model.Post() post_dict[call.message.chat.id] = post msg = bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Envie sua Postagem🖍️.") bot.register_next_step_handler(msg, process_word_name) if call.data == "cancel": bot.answer_callback_query(call.id, "Cancelando a criação da postagem!") post_dict.pop(call.message.chat.id) bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "CRIE UMA NOVA POSTAGEM AQUI ✅\n\nNAO POSTE COISAS PROIBIDAS COMO PORNOGRAFIA ❌ \n\nVOCE PODE SER BANIDO DO BOT 😱", reply_markup=main_menu_markup()) if call.data == "finish": bot.answer_callback_query(call.id, "Esta é a sua postagem!") post = post_dict[call.message.chat.id] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=post.print_post(), parse_mode="Markdown") links = post.print_links() if links: bot.send_message(call.message.chat.id, links, parse_mode="Markdown") bot.send_message( call.message.chat.id, "Você pode enviar essas postagens para o armazenamento ou editá-las manualmente e depois " "Envie isto. Pressione o botão 'Cancelar' para não fazer isso.", reply_markup=send_to_storage_markup()) if call.data == "send_to_storage": bot.answer_callback_query(call.id, "Enviando pro Canal✔️!") post = post_dict[call.message.chat.id] bot.send_message(storage_channel_id, post.print_post(), parse_mode="Markdown") links = post.print_links() if links: bot.send_message(storage_channel_id, links, parse_mode="Markdown") post_dict.pop(call.message.chat.id) bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "CRIE UMA NOVA POSTAGEM AQUI ✅\n\nNAO POSTE COISAS PROIBIDAS COMO PORNOGRAFIA ❌ \n\nVOCE PODE SER BANIDO DO BOT 😱", reply_markup=main_menu_markup()) if call.data == "edit_before_sending": bot.answer_callback_query(call.id, "Editando!") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="Envie uma postagem editada manualmente aqui.") post = post_dict[call.message.chat.id] msg = bot.send_message(call.message.chat.id, post.print_post()) bot.register_next_step_handler(msg, process_edited_post) if call.data == "cancel_sending_to_storage": post_dict.pop(call.message.chat.id) bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "CRIE UMA NOVA POSTAGEM AQUI ✅\n\nNAO POSTE COISAS PROIBIDAS COMO PORNOGRAFIA ❌ \n\nVOCE PODE SER BANIDO DO BOT 😱", reply_markup=main_menu_markup())
def post_create(): form = PostUpdateForm() form.recommender.choices = get_recommenders() if form.validate_on_submit(): img_ids_list = [int(id) for id in form.image.data.split(';') if id != ''] if len(img_ids_list) > 0: first_img_id = img_ids_list[0] else: first_img_id = None keyword_list = split_keywords(form.keywords) loc_keyword_list = split_keywords(form.location_keywords) # differentiate between existing and new keywords existing_keywords = model.Keyword.query( model.Keyword.keyword.IN(keyword_list + loc_keyword_list) ).fetch() existing_keywords_str = [keyword.keyword for keyword in existing_keywords] new_keywords = [item for item in keyword_list if item not in existing_keywords_str] new_loc_keywords = [item for item in loc_keyword_list if item not in existing_keywords_str] post_db = model.Post( user_key=auth.current_user_key(), title=form.title.data, content=form.content.data, keywords=form.keywords.data, location_keywords=form.location_keywords.data, image_ids_string=form.image.data, img_ids=img_ids_list, image_url=get_img_url(first_img_id), recommender=form.recommender.data, recommender_lower=form.recommender.data.lower(), website=form.website.data, adress=form.adress.data, keyword_list=keyword_list, location_keyword_list=loc_keyword_list, ) post_db_key = post_db.put() create_new_keywords(new_keywords, post_db_key, is_location=False) create_new_keywords(new_loc_keywords, post_db_key, is_location=True) add_to_keywords(existing_keywords, new_keywords + new_loc_keywords, post_db_key) # add content to index: search_document = create_document(post_db, post_db_key.id()) _ = add_document_to_index(search_document) flask.flash('New post was successfully created!', category='success') return flask.redirect(flask.url_for('post_list', order='-created')) return flask.render_template( 'post_create.html', title='Create New Post', html_class='post-create', get_upload_url=flask.url_for('api.resource.upload'), has_json=True, form=form, upload_url=blobstore.create_upload_url( flask.request.path, gs_bucket_name=config.CONFIG_DB.bucket_name or None, ), )
def test_callback(call): if call.data == "create_post": bot.answer_callback_query(call.id, "Creating post!") post = model.Post() post_dict[call.message.chat.id] = post msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="Creating post. Send word for vocabulary post.") bot.register_next_step_handler(msg, process_word_name) if call.data == "add_definition": bot.answer_callback_query(call.id, "Adding definition!") post = post_dict[call.message.chat.id] word = post.words[-1] definition_number = len(word.definitions) + 1 msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="Creating definition #{0}.Send definition.".format( definition_number)) bot.register_next_step_handler(msg, process_adding_definition) if call.data == "add_synonyms": bot.answer_callback_query(call.id, "Adding synonyms!") msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "Add some synonyms in this format: synonym1, synonym2, synonym3.") bot.register_next_step_handler(msg, process_synonyms) if call.data == "add_tags": bot.answer_callback_query(call.id, "Adding tags!") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Adding tags!") msg = bot.send_message( chat_id=call.message.chat.id, text='Chose one set of tags from options down below.', reply_markup=tags_markup(call.message)) bot.register_next_step_handler(msg, process_adding_tags) if call.data == "add_links": bot.answer_callback_query(call.id, "Adding links!") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Adding links!") msg = bot.send_message( chat_id=call.message.chat.id, text='Add link for Oxford Dictionary! You can skip by ' 'pressing button "Skip"', reply_markup=skip_markup()) bot.register_next_step_handler(msg, process_adding_links_oxford) if call.data == "add_new_word": bot.answer_callback_query(call.id, "Adding new word!") msg = bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="Adding new word! Send word for vocabulary post.") bot.register_next_step_handler(msg, process_word_name) if call.data == "cancel": bot.answer_callback_query(call.id, "Canceling creating post!") post_dict.pop(call.message.chat.id) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Create new post here.", reply_markup=main_menu_markup()) if call.data == "finish": bot.answer_callback_query(call.id, "This is your post!") post = post_dict[call.message.chat.id] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=post.print_post(), parse_mode="Markdown") links = post.print_links() if links: bot.send_message(call.message.chat.id, links, parse_mode="Markdown") bot.send_message( call.message.chat.id, "You can send this posts to storage, or edit them manually and then " "send it. Press 'Cancel' button to not do it.", reply_markup=send_to_storage_markup()) if call.data == "send_to_storage": bot.answer_callback_query(call.id, "Sending to storage!") post = post_dict[call.message.chat.id] bot.send_message(storage_channel_id, post.print_post(), parse_mode="Markdown") links = post.print_links() if links: bot.send_message(storage_channel_id, links, parse_mode="Markdown") post_dict.pop(call.message.chat.id) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Create new post here.", reply_markup=main_menu_markup()) if call.data == "edit_before_sending": bot.answer_callback_query(call.id, "Editing!") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Send manually edited post here.") post = post_dict[call.message.chat.id] msg = bot.send_message(call.message.chat.id, post.print_post()) bot.register_next_step_handler(msg, process_edited_post) if call.data == "cancel_sending_to_storage": post_dict.pop(call.message.chat.id) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Create new post here.", reply_markup=main_menu_markup())
def on_post(self, req, resp): try: if not req.context['user'].is_logged_in(): resp.status = falcon.HTTP_400 return user = req.context['user'] data = json.loads(req.stream.read().decode('utf-8'))['post'] if len(data['body']) > MAX_POST_LEN: resp.status = falcon.HTTP_413 req.context['result'] = { 'errors': [{ 'status': '413', 'title': 'Payload too large', 'detail': ('Tělo příspěvku může mít maximálně ' + str(MAX_POST_LEN) + ' znaků.') }] } return thread_id = data['thread'] thread = session.query(model.Thread).get(thread_id) if thread is None: resp.status = falcon.HTTP_400 return if req.context['year_obj'].sealed: resp.status = falcon.HTTP_403 req.context['result'] = { 'errors': [{ 'status': '403', 'title': 'Forbidden', 'detail': 'Ročník zapečetěn.' }] } return task_thread = session.query(model.Task).\ filter(model.Task.thread == thread_id).\ first() solution_thread = session.query(model.SolutionComment).\ filter(model.SolutionComment.thread == thread_id, model.SolutionComment.user == user.id).\ first() if task_thread: prog_modules = session.query(model.Module).\ filter(model.Module.task == task_thread.id, model.Module.type == model.ModuleType.PROGRAMMING).\ all() # Podminky pristupu: # 1) Do vlakna ulohy neni mozne pristoupit, pokud je uloha pro # uzivatele uzavrena. # 2) K vlaknu komentare nemohou pristoupit dalsi resitele. # 3) Do obecnych neverejnych vlaken muhou pristupovat orgove -- # tato situace nastava pri POSTovani prnviho prispevku # k opravovani, protoze vlakno opravovani jeste neni sprazeno # s evaluation. if (task_thread and util.task.status(task_thread, user) == util.TaskStatus.LOCKED) or \ (solution_thread and (solution_thread.user != user.id and not user.is_org())) or \ (not thread.public and not solution_thread and not user.is_org()): resp.status = falcon.HTTP_400 return user_class = session.query(model.User).get(user.id) # Kontrola existence rodicovskeho vlakna parent = session.query(model.Post).\ filter(model.Post.id == data['parent'], model.Post.thread == thread_id).\ first() if data['parent'] and not parent: resp.status = falcon.HTTP_400 return # Aktualizace navstivenosti vlakna visit = util.thread.get_visit(user.id, thread_id) if visit: visit.last_last_visit = visit.last_visit visit.last_visit = text( 'CURRENT_TIMESTAMP + INTERVAL 1 SECOND') else: time = text('CURRENT_TIMESTAMP + INTERVAL 1 SECOND') visit = model.ThreadVisit(thread=thread_id, user=user.id, last_visit=time, last_last_visit=time) session.add(visit) session.commit() # Tady si pamatujeme, komu jsme email j*z odeslali sent_emails = set() # ------------------------------------------ # Odesilani emailu orgum if user.role == 'participant' or user.role == 'participant_hidden': if task_thread: # Vlakno k uloze -> posilame email autoru ulohy, # spoluautoru ulohy a garantovi vlny. task_author_email = session.query(model.User.email).\ filter(model.User.id == task_thread.author).\ scalar() recipients = [task_author_email] wave_garant_email = session.query(model.User.email).\ join(model.Wave, model.Wave.garant == model.User.id).\ join(model.Task, model.Task.wave == model.Wave.id).\ filter(model.Task.id == task_thread.id).scalar() sent_emails.add(task_author_email) sent_emails.add(wave_garant_email) if task_thread.co_author: task_co_author_email = session.query(model.User.email).\ filter(model.User.id == task_thread.co_author).\ scalar() sent_emails.add(task_co_author_email) recipients.append(task_co_author_email) try: body = ('<p>Ahoj,<br/>k tvé úloze <a href="' + config.ksi_web() + '/ulohy/' + str(task_thread.id) + '">' + task_thread.title + '</a> na <a href="' + config.ksi_web() + '/">' + config.ksi_web() + '</a> byl přidán nový komentář:</p><p><i>' + user_class.first_name + ' ' + user_class.last_name + ':</i></p>' + data['body'] + '<p><a href="' + config.ksi_web() + '/ulohy/' + str(task_thread.id) + '/diskuse">Přejít do diskuze.</a> ' + '<a href="' + config.ksi_web() + '/admin/opravovani?participant_=' + str(user_class.id) + '&task_=' + str(task_thread.id) + '">Přejít na opravení.</a>') if len(prog_modules) > 0: body += (' <a href="' + config.ksi_web() + '/admin/execs?user='******'&module=' + str(prog_modules[0].id) body += '">Přejít na spuštění.</a></p>' body += '</p>' body += config.karlik_img() util.mail.send(recipients, '[KSI-WEB] Nový příspěvek k úloze ' + task_thread.title, body, cc=wave_garant_email) except BaseException: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr) elif solution_thread: # Vlakno k oprave -> posilame email autoru opravy correctors = [ r for r, in session.query(distinct(model.User.email)). join(model.Evaluation, model.Evaluation.evaluator == model.User.id).join( model.Module, model.Evaluation.module == model.Module.id). join(model.Task, model.Task.id == model.Module.task).filter( model.Task.id == solution_thread.task).all() ] for corr_email in correctors: sent_emails.add(corr_email) if correctors: task = session.query(model.Task).\ get(solution_thread.task) try: util.mail.send( correctors, '[KSI-WEB] Nový komentář k tvé korektuře úlohy ' + task.title, '<p>Ahoj,<br/>k tvé <a href="' + config.ksi_web() + '/admin/opravovani?task_=' + str(task.id) + '&participant_=' + str(user_class.id) + '">korektuře</a> úlohy <a href="' + config.ksi_web() + '/ulohy/' + str(task.id) + '">' + task.title + '</a> na <a href="' + config.ksi_web() + '/">' + config.ksi_web() + '</a> byl přidán nový komentář:<p><p><i>' + user_class.first_name + ' ' + user_class.last_name + ':</i></p><p>' + data['body'] + config.karlik_img()) except BaseException: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr) else: # Obecna diskuze -> email na [email protected] try: sent_emails.add(config.ksi_conf()) util.mail.send( config.ksi_conf(), '[KSI-WEB] Nový příspěvek v obecné diskuzi', '<p>Ahoj,<br/>do obecné diskuze na <a href="' + config.ksi_web() + '/">' + config.ksi_web() + '</a> byl přidán nový příspěvek:</p><p><i>' + user_class.first_name + ' ' + user_class.last_name + ':</i></p>' + data['body'] + '<p><a href=' + config.ksi_web() + '/forum/' + str(thread.id) + '>Přejít do diskuze.</a></p>' + config.karlik_img()) except BaseException: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr) # ------------------------------------------ # Pridani prispevku post = model.Post(thread=thread_id, author=user.id, body=data['body'], parent=data['parent']) session.add(post) session.commit() # ------------------------------------------ # Odesilani emailu v reakci na muj prispevek: if parent: parent_user = session.query(model.User).get(parent.author) parent_notify = util.user_notify.get(parent.author) if (parent_user.email not in sent_emails and parent_notify.notify_response): try: sent_emails.add(parent_user.email) body = ( '<p>Ahoj,<br>do diskuze <a href="%s">%s</a> byl ' 'přidán nový příspěvek.</p>' % (util.config.ksi_web() + "/forum/" + str(thread.id), thread.title)) body += util.post.to_html(parent, parent_user) body += ("<div style='margin-left: 50px;'>%s</div>" % (util.post.to_html(post))) body += util.config.karlik_img() util.mail.send( parent_user.email, ('[KSI-WEB] Nový příspěvek v diskuzi %s' % (thread.title)), body, unsubscribe=util.mail.Unsubscribe( email_type=util.mail.EMailType.RESPONSE, user_id=parent_user.id, ), ) except BaseException: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr) req.context['result'] = {'post': util.post.to_json(post, user.id)} except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_user_post(self, text: str, image: Optional[model.Image]) -> model.Post: post = model.Post(datetime.datetime.now(), text, image, model.User.main_user(), None) model.user_feed.append(post) if True: upset_birthday_boys = model.friends #[u for u in model.User.all() # if 0 < u.birthday_upsetness < model.User.MAX_BIRTHDAY_UPSETNESS] if upset_birthday_boys: def send_angry_replies(): try: post_topic = topic.detect.get_topic(post.text) except ValueError: return time.sleep(random.randint(5, 10)) first_commenter = upset_birthday_boys[0] first_comment_text = random.choice([ 'יש לך זמן לכתוב על {topic}, אבל להגיד מזל טוב לא נכנס בלו"ז. נחמד לראות את סדר העדיפויות' .format(topic=post_topic), 'אני מבי{} שמאוד חשוב לך {topic}, יותר ממני אפילו (מה התאריך היום?)' .format('ן' if first_commenter.gender == model.User.GENDER_MALE else 'נה', topic=post_topic), 'יש לך זמן לכתוב על {topic}, אבל להגיד מזל טוב לא נכנס בלו"ז. חבר חרא' .format(topic=post_topic), 'יש לך זמן לחפור על {topic}, אבל להגיד מזל טוב לא נכנס בלו"ז. אין בעיה.' .format(topic=post_topic) ]) self.react(first_commenter, post, random.choice(model.Reaction.NEGATIVE_TYPES)) first_comment = self.comment(first_commenter, post, first_comment_text) if len(upset_birthday_boys) > 1: time.sleep(random.randint(10, 30)) second_commenter = random.choice( upset_birthday_boys[1:]) self.react( second_commenter, post, random.choice(model.Reaction.NEGATIVE_TYPES)) self.react(second_commenter, first_comment, model.Reaction.LIKE) second_comment_text = random.choice([ 'גם לי {him} לא כתב{} כלום... '.format( '' if second_commenter.gender == model.User.GENDER_MALE else 'ה', him='הוא' if second_commenter.gender == model.User.GENDER_MALE else 'היא'), 'אנחנו באותה סירה. אפס אכפתיות', 'גם אני אותו דבר, חרא חבר באמת' ]) self.comment(second_commenter, first_comment, second_comment_text) threading.Thread(target=send_angry_replies).start() if True: def girlify(word): return word + word[-1] * random.randint(1, 10) # Image post def reply_positively_to_image(): liking_friends = random.sample( model.friends, min(len(model.friends), random.randint(10, 80))) for friend in liking_friends: time.sleep(random.randint(1, 2)) self.react( friend, post, random.choice( [model.Reaction.LIKE, model.Reaction.LOVE])) if random.random() < 0.5: target_is_male = model.User.main_user().is_male() self.comment(friend, post, (girlify( random.choice([ 'מהמם' if target_is_male else 'מהממת', 'מושלם' if target_is_male else 'מושלמת', ('הורס' if target_is_male else 'הורסת') + ('את הבריאות' if random.random() < .5 else ''), ('חתיך' if target_is_male else '') + ('את הבריאות' if random.random() < .5 else ''), 'יפה שלי', ('לא' if random.random() < .5 else '') + 'אני מתה', ('לא' if random.random() < .5 else '') + 'אין דברים כאל' + random.choice(['ה', 'ו']), girlify('לפרופיל') ])) if not friend.is_male() else random.choice([ 'תמונה יפה ' + (random.choice(['חיים', 'מאמי']) if not target_is_male else random. choice(['גבר', 'אחי'])) + ' שלי', 'לא רע', 'נדירה' ] + (['אחלה אופי'] if not target_is_male else [ 'אח יקר', 'אחי' + ''.join('י' if random.random() < .9 else 'ע' for i in range(random.randint(1, 10))), ])))) def reply_negatively_to_image(): liking_friends = random.sample( model.friends, min(len(model.friends), random.randint(10, 150))) for friend in liking_friends: time.sleep(random.randint(1, 2)) self.react( friend, post, random.choice( [model.Reaction.THROW_UP, model.Reaction.HAHA])) if random.random() < 0.5: target_is_male = model.User.main_user().is_male() self.comment(friend, post, (random.choice([ 'ח' * random.randint(10, 20) + random.choice([ '', ' פיגוע ' + random.choice(['מוצלח', 'טוב']) ]), 'חחחחחחח מה קרה' + random.choice(['', '?']), random.choice(['', 'לפחות ']) + 'יש לך אופי ' + random.choice(['סביר', 'סבבה', 'טוב']), 'הכל בסדר' + random.choice(['', '?']), random.choice([ '', 'בוא ל' if target_is_male else 'בואי ל' ]) + 'פרטי' + random.choice(['', girlify(' דחוף'), 'עכשיו']), 'מה זה מה קרה לך לפנים' + random.choice(['?', '']) ]))) threading.Thread(target=random.choice([ reply_positively_to_image, reply_negatively_to_image ])).start() return post
a.id = 2 a.email = "*****@*****.**" a.password = "******" a.cell_phone = "6462891899" a.first_name = "Linda" a.last_name = "Zhou" a.baby_dob = datetime.strptime("2014-09-29", "%Y-%m-%d") a.zip_code = "94108" a.no_dairy = True a.no_wheat = True a.no_soy = True a.no_caffeine = True a.no_alcohol = True a.has_health_info = True p = model.Post() p.id = 1 p.user_id = 1 p.req_or_off = "request" p.date = datetime.strptime("2014-11-14", "%Y-%m-%d") p.amt_milk = "2 gallons" p.recurring = True m = model.Message() m.id = 1 m.sender_id = 1 m.recipient_id = 2 m.date = datetime.strptime("2014-11-14", "%Y-%m-%d") m.subject = "Hi!" m.message = "This is spam."