def create_thread(tid): """Create a new thread.""" form = ThreadForm() form["csrf_token"].data = request.cookies["csrf_token"] if form.validate_on_submit(): print("form", form.data) image_filename = upload_file(form["image"].data) thread = Thread( tale_id=tid, title=form["title"].data, description=form["description"].data, color=form["color"].data, icon=form["icon"].data, image=image_filename, ) db.session.add(thread) db.session.commit() # Creates effects for thread in database # effects = createEffects(request.json["effects"], thread) # Creates choices for thread in database choices = createChoicesFromString(form["choices"].data, thread) # Create locks for choices in database # locks = createLocks(request.json["locks"], thread) return jsonify(thread=thread.to_dict(), choices=choices) else: return {"errors": validation_errors_to_messages(form.errors)}, 401
def newThread(request): langCode = request.build_absolute_uri().split("/")[-4] if not request.session.has_key('username'): return redirect('/' + langCode + '/login') if request.method == 'POST': thread_form = ThreadForm(request.POST) post_form = PostForm(request.POST) if thread_form.is_valid() and post_form.is_valid(): thread = Thread() thread.title = thread_form.cleaned_data["title"] thread.description = thread_form.cleaned_data["description"] thread.save() post = Post() post.content = post_form.cleaned_data["content"] post.date = timezone.now() post.user = User.objects.get(username=request.session["username"]) post.positionInThread = 0 post.thread = thread post.save() thread.originalPost = post thread.save() return redirect("/" + langCode + "/forum/thread/" + str(thread.pk)) else: # GET return render(request, 'forum/newthread.html', { "thread_form": ThreadForm(), "post_form": PostForm() })
def create_thread(template_id=False): if template_id is not False: thread = db.session.query(Thread)\ .filter_by(id=template_id)\ .first() if thread and thread.user_id == g.user.id: form = ThreadForm(obj=thread) else: form = ThreadForm() else: form = ThreadForm() if form.validate_on_submit(): new_thread = Thread( user_id=g.user.id, title=form.title.data, body=form.body.data, subreddit=form.subreddit.data, ) db.session.add(new_thread) db.session.commit() return redirect(url_for('preview', thread_id=new_thread.id)) return render_template('create-thread.html', page_title="Create New Draft", form=form)
def messages(request, game_id, round_id, thread_id): thread = Thread.get_by_uid(thread_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) if request.method == 'GET': since = request.GET.get('since', None) return json(Message.get_activities(request.user, thread, since=since)) if request.method == 'POST': if not thread.profile_can_create(request.profile): return HttpResponse('Unauthorized', status=401) content = request.POST.get('content', None) if not content: return HttpResponse('Method Not Allowed - A message is required', status=405) # create the new message game = Game.get_by_uid(game_id) actor = Role.get_by_profile(game, request.profile) message = Message(actor=actor, content=content, thread=thread) message.put() return json(message) return HttpResponse('Method Not Allowed', status=405)
def search(): if not g.search_form.validate(): return redirect(url_for('index')) page = request.args.get('page', 1, type=int) target_index = request.args.get('index', 'thread') if target_index == 'thread': results, total = Thread.search(g.search_form.q.data, page, app.config['POSTS_PER_PAGE']) elif target_index == 'user': results, total = User.search(g.search_form.q.data, page, app.config['POSTS_PER_PAGE']) elif target_index == 'subreddit': results, total = Subreddit.search(g.search_form.q.data, page, app.config['POSTS_PER_PAGE']) else: return render_template('404.html') results = results.all() next_url = url_for( 'search', index=target_index, q=g.search_form.q.data, page=page + 1) if total > page * app.config['POSTS_PER_PAGE'] else None prev_url = url_for( 'search', index=target_index, q=g.search_form.q.data, page=page - 1) if page > 1 else None return render_template('search.html', title=_('Search'), results=results, next_url=next_url, prev_url=prev_url, query=g.search_form.q.data, query_language=guess_language(g.search_form.q.data), index=target_index)
def seed_threads(): threads = [ Thread( userId=2, jokeId=1, comment="Wow what a punny time joke!", ), Thread( userId=1, jokeId=2, comment="ahhh the drawbacks of perfectionism", ), ] db.session.bulk_save_objects(threads) db.session.commit()
def create_thread_node(tid): """Create a new thread.""" form = ThreadForm() form["csrf_token"].data = request.cookies["csrf_token"] if form.validate_on_submit(): thread = Thread( tale_id=tid, title="Untitled", color="#f9fbefff", icon="feather-alt", ) db.session.add(thread) db.session.commit() return thread.to_dict() else: return {"errors": validation_errors_to_messages(form.errors)}, 401
def list_threads(): threads = get_user_threads(session['login']) if threads is None: return render_template('list.html', threads=None) else: with db_session: threads = Thread.select(lambda c: c.id in threads)[:] return render_template('list.html', threads=threads)
def post(self): currentUser = get_jwt_identity(); requestData = request.get_json() thread = Thread(title=requestData['title'], body=requestData['body'], user_id=currentUser['id']) db.session.add(thread) db.session.commit() result = thread_schema.dump(thread) return jsonify(result.data)
def seed_threads(): threads = [] with open("./app/seeds/threads.json") as f: data = json.load(f) for thread in data: new_thread = Thread(**thread) threads.append(new_thread) db.session.add_all(threads) db.session.commit()
def add_thread(user, group, title, content): thread = Thread(group=group, timestamp=datetime.now(), title=title) db.session.add(thread) db.session.flush() post = save_post(user, content, thread.id) db.session.add(post) db.session.commit() return thread
def create_joke(): """ Create new joke """ form = CreateThreadForm() form["csrf_token"].data = request.cookies["csrf_token"] if form.validate_on_submit(): new_thread = Thread( userId=form.data["userId"], jokeId=form.data["jokeId"], comment=form.data["comment"], ) db.session.add(new_thread) db.session.commit() print("----------newthread----", new_thread) return new_thread.to_dict() errors = validation_errors_to_error_messages(form.errors) return {"errors": errors}
def activities(request, game_id, round_id, thread_id): thread = Thread.get_by_uid(thread_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) if request.method == 'GET': return json(list(Activity.get_activities(request.user, thread))) # no POSTs here, return 404 raise Http404
def createthread(): form = ThreadForm() if form.validate_on_submit(): thread = Thread(title=form.threadname.data, author=current_user) post = Post(body=form.post.data, author=current_user, thread=thread) db.session.add(thread) db.session.add(post) db.session.commit() flash('your post is now live!') return redirect(url_for('forum')) return render_template("createthread.html", title="Write a post", form=form)
def create_thread(board_title): board = Board.query.filter(Board.title == board_title).one() form = CreateThreadForm() if form.validate_on_submit(): thread = Thread( title=form.name.data, description = form.description.data, \ board=board, author=current_user) db.session.add(thread) db.session.commit() flash(_('Your post has been created.')) return redirect(url_for('main.board', title=board_title)) return render_template('create_thread.html', _title=('Create Thread'), form=form)
def createthread(id): form = CreateThreadForm() form.id.data = id if form.validate_on_submit(): topic = Topic.query.filter_by(id=form.id.data).first() if not topic: flash('Invalide Topic') return redirect(url_for('main.index')) thread = Thread(title=form.title.data, body=form.description.data, author=current_user, topic=topic) db.session.add(thread) db.session.commit() return redirect(url_for('main.thread', id=thread.id)) return render_template('createtopic.html', id=id, form=form)
def new_thread(specialty_id): specialty2 = session.get('specialty') threadform = ThreadForm() specialty = Specialty.query.get(specialty_id) if threadform.validate_on_submit(): thread = Thread(body=threadform.body.data, author=current_user, title=threadform.title.data, specialty=Specialty.query.get(specialty_id)) db.session.add(thread) db.session.commit() flash(_('Your thread is now live!')) return redirect(url_for('main.threads', specialty_id=specialty_id)) return render_template('new_thread.html', specialty2=specialty2, specialty=specialty, threadform=threadform)
def add_thread(): if request.method == 'POST': data = request.get_json description = data.get("description") username = data.get("username") password = data.get("password") user = User.query.filter_by(username=username).first() if user.verify_password(password): thread = Thread( description=description, user_id=user.id, ) db.session.add(thread) db.session.commit() return jsonify({"msg": "创建新板块成功!"}), 200 else: return jsonify({"msg": "用户验证失败!"})
def create_comment(post_id): post = Post.query.get(post_id) form = CreateComment() if form.validate_on_submit(): comment = Comment() if not form["comment_id"].data: thread = Thread(post_id=post.id) db.session.add(thread) db.session.commit() form["thread_id"].data = thread.id form["path"].data = f"{post.id}" form["level"].data = 1 form.populate_obj(comment) db.session.add(comment) db.session.commit() return comment.to_dict() return {"errors": validation_errors_to_error_messages(form.errors)}
def stream(request, game_id, round_id, thread_id, message_id): thread = Thread.get_by_uid(thread_id) since = Activity.get_by_uid(message_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) if request.method != 'GET': return HttpResponse('Method Not Allowed', status=405) activities = Activity.get_activities(request.user, thread, since=since) return json(list(activities.run()))
def create_thread(): form = CreateThreadForm() if form.validate_on_submit(): thread_language = guess_language(form.body.data) if thread_language == 'UNKNOWN' or len(thread_language) > 5: thread_language = '' thread = Thread(title=form.title.data, body=form.body.data, user=current_user, language=thread_language, subreddit=Subreddit.query.filter_by( name=form.subreddit.data).first()) db.session.add(thread) db.session.commit() return redirect(session['prior_thread_create_page']) return render_template('create_thread.html', form=form, page_title=_('Reddit - Create Thread'))
def vote_summary(request, game_id, round_id, thread_id): thread = Thread.get_by_uid(thread_id) game = Game.get_by_uid(game_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) # only deals with GET requests if not request.method == 'GET': raise Http404 summaries = VoteSummary.all().filter('thread', thread) summaries = summaries.order('-total') data = [] total_votes = 0 for s in summaries: data.append(dict(profile=s.role.player, total=s.total, updated=s.updated)) total_votes += s.total chart_data = dict(chxr="0,0,%s" % len(data), chxt='y', chbh='a', chs='200x200', cht='bhs', chco='4D89F9', chds="0,%s" % total_votes) player_labels = [s['profile'].name for s in data] player_labels.reverse() chart_data['chx1'] = "0:|%s" % "|".join(player_labels) chart_data['chd'] = "t:%s" % ",".join([str(s['total']) for s in data]) chart_url = "http://chart.apis.google.com/chart?%s" chart_url = chart_url % urlencode(chart_data) return json(dict(thread=thread, summaries=data, chart_url=chart_url))
def create_thread(category_id): category = Category.query.filter_by(id=category_id).first() if category is None: flash('category {} not found.'.format(category_id)) return redirect(url_for('main.index')) form = CreateThreadForm(category.title) if form.validate_on_submit(): thread = Thread(title=form.title.data, author=current_user, category=category) db.session.add(thread) db.session.commit() post = Post(body=form.post.data, author=current_user, thread=thread) db.session.add(post) db.session.commit() flash('Your thread {} has been created! Make a first post!'.format( form.title.data)) return redirect(url_for('main.thread', thread_id=thread.id)) return render_template('create_thread.html', title='Create a new thread', category=category, form=form)
def create_thread(category_title): #todo - update to include an initial post? category = Category.query.filter_by(title=category_title).first() if category is None: flash('category {} not found.'.format(category_title)) return redirect(url_for('main.index')) form = CreateThreadForm(category_title) if form.validate_on_submit(): thread = Thread(title=form.title.data, author=current_user, category=category) db.session.add(thread) db.session.commit() flash('Your thread {} has been created! Make a first post!'.format( form.title.data)) return redirect( url_for('main.thread', category_title=category_title, thread_title=form.title.data)) return render_template('create_thread.html', title='Create thread', category_title=category_title, form=form)
def thread_page(t_id): if t_id not in get_user_threads(session['login']): return "This tread is blocked for you", 403 with db_session: threads = Thread.select(lambda t: t.id == t_id)[:] if not threads: return "Thread not found", 404 thread = threads[0] if request.method == 'POST': text = request.form.get('text') if not text: return "All fields are required" author = list(User.select(lambda u: u.id == session['id']))[0] app.logger.info("New message from %s: %s" % (author.login, text)) Message(text=text, thread=thread, author=author) u_id = session['id'] hash = calc_hash(t_id, u_id) return render_template('thread_page.html', thread=thread, u_id=u_id, t_id=t_id, hash=hash)
def create_post(user_id): """ Создает новую тему и первый пост в ней """ data = request.json section_id = data.get('section_id') thread_id = data.get('thread_id') thread_name = data.get('thread_name') text = data.get('text') if not thread_id: thread = Thread(name=thread_name, user_id=user_id, views=0, section_id=section_id) session.add(thread) session.commit() thread_id = thread.id post = Post(user_id=user_id, text=text, thread_id=thread_id) session.add(post) session.commit() return make_response(str(thread_id), 201)
def create_thread(): form = ThreadForm() if form.validate_on_submit(): new_thread = Thread( user_id=g.user.id, title=form.title.data, body=form.body.data, link_facebook=form.link_facebook.data, link_twitter=form.link_twitter.data, link_youtube=form.link_youtube.data, link_soundcloud=form.link_soundcloud.data, link_bandcamp=form.link_bandcamp.data, link_website=form.link_website.data, link_label_website=form.link_label_website.data, verification=form.verification.data, subreddit=form.subreddit.data, ) db.session.add(new_thread) db.session.commit() return redirect(url_for('preview', thread_id=new_thread.id)) return render_template('create-thread.html', page_title="Create a New AMA", form=form)
def create_chronicle(): """Create a new chronicle for a user.""" form = ChronicleForm() form["csrf_token"].data = request.cookies["csrf_token"] if form.validate_on_submit(): image_filename = upload_file(form["image"].data) chronicle = Chronicle( user_id=current_user.id, title=form["title"].data, description=form["description"].data, color=form["color"].data, icon=form["icon"].data, image=image_filename, ) tale = Tale(chronicle=chronicle, title=f"{chronicle.title}'s First Tale") thread = Thread( tale=tale, title=f"Untitled", description="Edit this scene and link threads with choices!") db.session.add(chronicle) db.session.add(tale) db.session.add(thread) db.session.commit() tale.first_thread_id = thread.id db.session.commit() return chronicle.to_dict() # jsonify( # chronicle={chronicle.id: chronicle.to_dict()}, # tale={tale.id: tale.to_dict()}, # thread={thread.id: thread.to_dict()} # ) else: return {"errors": validation_errors_to_messages(form.errors)}, 401
def generate(): spec = Specialty.query.filter_by(name='Surgery').first() wb = openpyxl.load_workbook(request.files['file']) ws = wb.active for row in ws.iter_rows(min_row=1): if row[0].value: thread_body = row[0].value thread = Thread(body=thread_body, author=current_user, specialty=spec) db.session.add(thread) db.session.commit() response_list = row[1].value if response_list: responses = list( map( lambda x: Post(body=x, author=current_user, thread_id=thread.id), response_list.split("XXXXX"))) for response in responses: db.session.add(response) db.session.commit() yield (str(row[0].row))
def post_bot_message(package: Package, title: str, message: str): system_user = get_system_user() thread = package.threads.filter_by(author=system_user).first() if not thread: thread = Thread() thread.package = package thread.title = "Bot messages for {}".format(package.title) thread.author = system_user thread.private = True thread.watchers.append(package.author) db.session.add(thread) db.session.flush() reply = ThreadReply() reply.thread = thread reply.author = system_user reply.comment = "**{}**\n\n{}".format(title, message) db.session.add(reply) addNotification(thread.watchers, system_user, NotificationType.BOT, title, thread.getViewURL(), thread.package) thread.replies.append(reply)
def review(package): if current_user in package.maintainers: flash("You can't review your own package!", "danger") return redirect(package.getDetailsURL()) review = PackageReview.query.filter_by(package=package, author=current_user).first() form = ReviewForm(formdata=request.form, obj=review) # Set default values if request.method == "GET" and review: form.title.data = review.thread.title form.recommends.data = "yes" if review.recommends else "no" form.comment.data = review.thread.replies[0].comment # Validate and submit elif request.method == "POST" and form.validate(): was_new = False if not review: was_new = True review = PackageReview() review.package = package review.author = current_user db.session.add(review) review.recommends = form.recommends.data == "yes" thread = review.thread if not thread: thread = Thread() thread.author = current_user thread.private = False thread.package = package thread.review = review db.session.add(thread) thread.watchers.append(current_user) reply = ThreadReply() reply.thread = thread reply.author = current_user reply.comment = form.comment.data db.session.add(reply) thread.replies.append(reply) else: reply = thread.replies[0] reply.comment = form.comment.data thread.title = form.title.data db.session.commit() package.recalcScore() notif_msg = None if was_new: notif_msg = "New review '{}'".format(form.title.data) else: notif_msg = "Updated review '{}'".format(form.title.data) addNotification(package.maintainers, current_user, notif_msg, url_for("threads.view", id=thread.id), package) db.session.commit() return redirect(package.getDetailsURL()) return render_template("packages/review_create_edit.html", \ form=form, package=package, review=review)
def seed_threads(): """Seed a series of connected threads for Demo Tale.""" # Creating the threads, which will be connected via 'choices' next. thread0 = Thread( # 0 title="The Beginning", description= "At the beginning, there were two doors. A red door and a blue door.", color="rgb(70,60,70)", icon="sign", image= "https://res.cloudinary.com/peerspace-inc/image/upload/q_80,c_crop,g_custom/w_2048/hztukpx3k9m3qbezy0ik.jpg", tale_id=1, ) thread1 = Thread( # 1 title="The Red Room", description= "In the red door, there is a room with a bowl of candy and a vase full of lilies, as well as another red door at the far wall.", color="#e05265ff", icon="door-closed", tale_id=1, ) thread2 = Thread( # 2 title="The Blue Room", description= "In the blue door, there is a small red key on the table, as well as another blue door at the far wall.", color="#5a70ccff", icon="door-open", tale_id=1, ) thread3 = Thread( # 3 title="The Joined Room", description= "Looking behind you, you see both a red and blue door. It seems both rooms eventually led to the same destination. In here, you see a glowing fairy angrily throwing a tennis ball at the wall.", color="#4f4686ff", tale_id=1, ) thread4 = Thread( # 4 title="Take Candy", description= "You take the candy and pocket it. They look very delicious.", color="#964a70ff", icon="candy-cane", tale_id=1, ) thread5 = Thread( # 5 title="Smell the Lilies", description="*sniff sniff* They're quite fragrant. How lovely.", color="#f9fbefff", icon="seedling", image= "https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/easter-lily-royalty-free-image-1583439719.jpg", tale_id=1, ) thread6 = Thread( # 6 title="Take Key", description= "You take the little red key and put it in your pocket. This should help you out.", color="#e05265ff", icon="key", tale_id=1, ) thread7 = Thread( # 7 title="Talk to the Sweet Fairy", description= "The fairy bemoans about how hungry it is, and it really wants something sweet to eat.", color="#57768aff", icon="comment", tale_id=1, ) thread8 = Thread( # 8 title="Give Candy", description= "The sweet fairy is very happy, and thanks you with a smile.", color="#e05265ff", icon="candy-cane", tale_id=1, ) thread9 = Thread( # 9 title="Lecture Sweet Fairy About a Healthy Diet", description= "You give the little fairy a stern talking-to about eating its vegetables to grow up healthy and strong. It seems very unhappy with you, and lapses into silence, throwing its ball with even more gusto.", color="#8cb15eff", icon="carrot", tale_id=1, ) thread10 = Thread( title="Look around", description="You look around. Nice.", color="rgb(70,60,70)", icon="eye", image= "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTHWvp2ZW7nv-Kor5411yZ45_iLhmDKphgrTw&usqp=CAU", tale_id=1, is_sequitur=False, ) # thread10 = Thread( # tale_id=1, # title="", # description="") db.session.add(thread0) db.session.add(thread1) db.session.add(thread2) db.session.add(thread3) db.session.add(thread4) db.session.add(thread5) db.session.add(thread6) db.session.add(thread7) db.session.add(thread8) db.session.add(thread9) db.session.add(thread10) db.session.commit() threads = [ thread0, thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8, thread9, thread10 ] # Adding choice-links between threads with choice-thread default titles. choices = ((0, 1), (0, 2), (1, 4), (1, 5), (2, 6), (3, 7), (7, 8), (7, 9)) for choice in choices: new_choice = Choice(title=threads[choice[1]].title, prev_thread=threads[choice[0]], next_thread=threads[choice[1]]) db.session.add(new_choice) # Adding choices with unique titles new_choice5 = Choice(title="Go through second red door", prev_thread=threads[1], next_thread=threads[3]) new_choice6 = Choice(title="Go through second blue door", prev_thread=threads[2], next_thread=threads[3]) db.session.add(new_choice5) db.session.add(new_choice6) db.session.commit()
def votes(request, game_id, round_id, thread_id): thread = Thread.get_by_uid(thread_id) game = Game.get_by_uid(game_id) if thread is None: raise Http404 if not thread.profile_can_view(request.profile): return HttpResponse('Unauthorized', status=401) if request.method == 'GET': since = request.GET.get('since', None) return json(Vote.get_activities(request.user, thread, since=since)) if request.method == 'POST': if not thread.profile_can_create(request.profile): return HttpResponse('Unauthorized', status=401) # find the target target_id = request.POST.get('target_id', None) if target_id is None: raise Exception('No target') target_profile = Profile.get_by_uid(target_id) target = Role.all().filter('player', target_profile) target = target.filter('game', game) target = target.fetch(1)[0] # find the last vote this user made (if any) game = Game.get_by_uid(game_id) actor = Role.get_by_profile(game, request.profile) last_vote = Vote.all().filter("thread", thread) last_vote = last_vote.filter("actor", actor) last_vote = last_vote.order("-created") try: last_vote = last_vote.fetch(1)[0] except IndexError, e: last_vote = None # if we found a vote, decrement that vote's counter if last_vote is not None: last_vote.decrement() # create the new vote vote = Vote(actor=actor, target=target, thread=thread) vote.put() # increment the counter vote.increment() if thread.name == role_vanillager: vote_count = Vote.all().filter('thread', thread).count() if not vote_count: # First vote in round c = Client(settings.BDM_SECRET, settings.BDM_KEY) eul = "profile:%s" % request.profile.uid c.post("named_transaction_group/613301/execute/%s" % eul) if thread.round.number == 1: # First vote in game c.post("named_transaction_group/613302/execute/%s" % eul) return json(vote)
firstname = user.split(" ")[0] lastname = user.split(" ")[1] except: firstname = "Unknown" lastname = "User" u = User.objects.create_user(first_name = firstname, last_name = lastname, username = user, password="******", email="*****@*****.**") u.save() with open('commotion-discuss.txt_sorted.csv', 'rb') as csvfile: forum_data_reader = csv.reader(csvfile, delimiter=',', quotechar='"') # Add threads threads = [] for index, row in enumerate(forum_data_reader): if index >0: if row[2] not in threads: threads.append(row[2]) creator = User.objects.filter(username = row[5]).first() forum = Forum.objects.filter(title=row[1]).first() title = row[2] t = Thread(title =title, creator = creator, forum = forum) t.save() # Add posts with open('commotion-discuss.txt_sorted.csv', 'rb') as csvfile: forum_data_reader = csv.reader(csvfile, delimiter=',', quotechar='"') for index, row in enumerate(forum_data_reader): if index >0: creator = User.objects.filter(username = row[5]).first() thread = Thread.objects.filter(title = row[2]).first() p = Post(creator=creator, thread=thread, title="", body=row[6]) p.save()