def add_to_analysis(): table, id = request.json['data'] id = int(id) try: if table == 'delete': if (id in current_user.analysis_cart): current_user.analysis_cart.remove(id) else: if table == 'selection': sele = Selection.query.get(id) ids = [i.id for i in sele.rounds] elif table == 'round': ids = [id] ids = [i for i in ids if i not in current_user.analysis_cart] current_user.analysis_cart.extend(ids) current_user.save_data() db.session.commit() except: flash( 'An Error occured during editing analysis cart. Please refresh page.', 'warning') return jsonify({ 'analysis_count': current_user.analysis_cart_count(), 'remaining': current_user.analysis_cart })
def user_settings_ajax(): data = request.json.get('setting') current_user.user_setting.update(data) current_user.save_data() db.session.commit() messages = [('success', "Setting <{}> set to <{}>.".format(k, i)) for k, i in data.items()] return jsonify( html=render_template('flash_messages.html', messages=messages))
def remove_all_slide_cart(): mode = request.args.get('mode', None) if mode == 'slide_cart': current_user.slide_cart = [] elif mode == 'bookmarked_ppt': current_user.bookmarked_ppt = [] current_user.save_data() db.session.commit() flash('All slides in {} was deleted'.format(mode), 'info') return redirect(url_for('ppt.index'))
def add_to_bookmark(): new = [ i for i in current_user.slide_cart if i not in current_user.bookmarked_ppt ] current_user.bookmarked_ppt.extend(new) current_user.save_data() db.session.commit() messages = [('success', "Bookmarked <{}> slides.".format(len(new)))] return jsonify( html=render_template('flash_messages.html', messages=messages))
def show_publication(id_): # Показ публикации form = ShowPublicationForm() db_sess = db_session.create_session() # Берем публикацию и загружаем ее дополнительные данные publication = db_sess.query(Publication).filter( Publication.id == int(id_)).first() publication.__init__() current_user.load_data() user = db_sess.query(User).filter(User.id == publication.user_id).first() date = get_date(publication.created_date) if form.validate_on_submit(): if form.like_submit.data: if publication.id in current_user.other_data['likes']: # Удаление лайка файлах пользователя и публикации if current_user.id in publication.other_data['likes']: publication.other_data['likes'].remove(current_user.id) current_user.other_data['likes'].remove(publication.id) # Удаление уведомления notification = db_sess.query(Notification).filter( Notification.publication_id == publication.id, Notification.sender_id == current_user.id, Notification.recipient_id == user.id).first() if notification is not None: db_sess.delete(notification) db_sess.commit() else: # Добавление лайка файлах пользователя и публикации if current_user.id not in publication.other_data['likes']: publication.other_data['likes'].append(current_user.id) current_user.other_data['likes'].append(publication.id) # Добавление уведомления notification = Notification() notification.publication_id = publication.id notification.sender_id = current_user.id notification.recipient_id = user.id db_sess.add(notification) db_sess.commit() current_user.save_data() publication.save_data() return render_template('publication.html', title='Публикация', theme=get_theme(), form=form, user=user, publication=publication, date=date)
def add_publication(): # Добавление публикации form = AddPublicationForm() if form.submit_view.data or form.submit.data: current_user.load_data() # Загрузка дополнительных данных пользователя photo_name = current_user.other_data.get('pub_filename', '') # Сохранение фотографии if request.files and request.files['file']: # Если загружены неправильные данные if form.file.data.filename.split('.')[-1] not in ('png', 'jpg'): return render_template( 'add_publication.html', title='Добавить новость', theme=get_theme(), form=form, message='Загрузите фотографию формата .png или .jpg') # Создание пути к файлу photo_name = f'user_data/publications/{random_name()}.png' current_user.other_data['pub_filename'] = photo_name current_user.save_data() # Сохранение фотографии image_size(request.files['file'], photo_name) # Если нажата кнопка "Опубликовать" if form.submit.data: # Создание публикации... db_sess = db_session.create_session() publication = Publication() publication.user_id = current_user.id publication.filename_photo = photo_name publication.about = form.about.data db_sess.add(publication) db_sess.commit() return redirect(f'/profile/{current_user.name}') # Иначе (Нажата кнопка "Просмореть") else: # Показ фотографии return render_template('add_publication.html', title='add_publication', theme=get_theme(), form=form, photo_name=photo_name) return render_template('add_publication.html', title='Добавить новость', theme=get_theme(), form=form)
def add_analysis(): if request.method == 'POST': cart = current_user.analysis_cart name = request.form['name'] note = request.form['note'] analysis = Analysis( name=name, note=note, ) analysis._rounds = cart analysis.user = current_user analysis.save_data() db.session.add(analysis) current_user.analysis_cart = [] current_user.save_data() db.session.commit() flash(f'Analysis <{analysis}> added.', 'success') return redirect(url_for('ngs.analysis', id=analysis.id))
def edit_link(): form = request.form delete = request.args.get('delete', None) if form and request.method == 'POST': idx = int(form.get('id')) name = form.get('name') url = parse_url_path(form.get('url')) if idx == -1: current_user.quick_link.append((name, url)) else: current_user.quick_link[idx] = (name, url) current_user.save_data() db.session.commit() if delete != None: current_user.quick_link.pop(int(delete)) current_user.save_data() db.session.commit() return redirect(url_for('main.index'))
def add_to_slide_cart(): try: current_user.remove_dead_ppt_link() id = int(request.json.get('slide_id')) action = request.json.get('action') mode = request.json.get('mode', 'slide_cart') slide = Slide.query.get(id) if action == 'delete': if mode == 'slide_cart' or mode == 'bookmarked_ppt': toedit = getattr(current_user, mode) if id in toedit: toedit.remove(id) else: ppt_id = slide.ppt_id if current_user.follow_ppt.get(str(ppt_id), []): if id not in current_user.follow_ppt.get(str(ppt_id)): current_user.follow_ppt[str(ppt_id)].append(id) messages = [] else: if (id not in current_user.slide_cart) and slide: current_user.slide_cart.append(id) messages = [('success', "{} was added to your comparison.".format(slide))] else: messages = [ ('info', "Side {} don't exist anymore or is already added.".format( id)) ] current_user.save_data() db.session.commit() except Exception as e: messages = [('danger', "Error occurred: {}.".format(e))] count = 0 if mode == 'slide_cart': count = len(current_user.slide_cart) elif mode == 'follow_ppt': count = current_user.follow_ppt_update_count return jsonify(count=count, notice=bool(messages), html=render_template('flash_messages.html', messages=messages))
def read_allslides(): try: ppt_id = request.args.get('ppt_id', 0, int) print(ppt_id) if ppt_id: ppt = PPT.query.get(ppt_id) slides = [i.id for i in ppt.slides] current_user.follow_ppt.update({ppt_id: slides}) else: for k in list(current_user.follow_ppt.keys()): ppt = PPT.query.get(k) if ppt: slides = [i.id for i in ppt.slides] current_user.follow_ppt.update({k: slides}) else: current_user.follow_ppt.pop(k, None) current_user.save_data() db.session.commit() flash('All updates are marked as read.', 'info') except Exception as e: flash('Error during updating {}: {}'.format(ppt_id, e), 'warning') return redirect(url_for('main.index'))
def add_ppt_to_follow(): try: id = request.json.get('ppt_id') action = request.json.get('action') ppt = PPT.query.get(id) if action == 'Follow': slides = [i.id for i in ppt.slides] current_user.follow_ppt.update({id: slides}) messages = [('success', "You are now following <{}>.".format(ppt.name))] else: current_user.follow_ppt.pop(id, None) messages = [('success', "You unfollowed <{}>.".format(ppt.name))] current_user.save_data() db.session.commit() except Exception as e: messages = [ ('danger', "Error occurred during {} PPT_id <{}>: {}.".format(action, id, e)) ] return jsonify(status=current_user.is_following_ppt(id), html=render_template('flash_messages.html', messages=messages))
def profile(name): # Страница профиля db_sess = db_session.create_session() user = db_sess.query(User).filter(User.name == name).first() if user is None: # Если пользователя не существует return render_template('profile.html', title='profile', theme=get_theme(), user_data=False) current_user.load_data() # Загрузка дополнительных данных пользователя curr_user_data = current_user.other_data user.__init__() # Загрузка дополнительных данных данного пользователя user_data = user.other_data # Берем публикации данного пользователся и сортируем их по дате загрузки publications = db_sess.query(Publication).filter( Publication.user_id == user.id).all() publications = sorted(publications, key=lambda p: p.created_date, reverse=True) # Берем оттуда только id и путь к файлу publications = [[pub.id, pub.filename_photo] for pub in publications] len_pubs = len(publications) form = ProfileForm() if form.validate_on_submit(): # Если нажата кнопка отписатся if user.id in current_user.other_data['subscriptions']: # Удаление пользователя из подписок и удаление текущего пользовтеля из его подписчиков current_user.other_data['subscriptions'].remove(user.id) if current_user.id in user.other_data['followers']: user.other_data['followers'].remove(current_user.id) # Удаление уведомления notification = db_sess.query(Notification).filter( Notification.publication_id == -1, Notification.sender_id == current_user.id, Notification.recipient_id == user.id).first() if notification is not None: db_sess.delete(notification) db_sess.commit() # Инача (нажата кнопка подписатся) else: # Добавление пользователя в подписки и добавление текущего пользователся в его подписки current_user.other_data['subscriptions'].append(user.id) if current_user.id not in user.other_data['followers']: user.other_data['followers'].append(current_user.id) # Добавление уведомления notification = Notification() notification.publication_id = -1 notification.sender_id = current_user.id notification.recipient_id = user.id db_sess.add(notification) db_sess.commit() # Сохрание данных обэих пользователей user.save_data() current_user.save_data() return render_template('profile.html', title='profile', theme=get_theme(), form=form, user=user, user_data=user_data, curr_user_data=curr_user_data, pubs=publications, len_pubs=len_pubs)