def ajax_groups_delete_action(id): try: group = Group.query.get(id) db.session.delete(group) db.session.commit() showNotify('Успешно!', 'Группа {} удалена!'.format(group.name), type='success') except Exception: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'При удалении группы возникли проблемы.' }]) calendar_id = '*****@*****.**' try: get_service('calendar', 'v3').events().delete(calendarId=calendar_id, eventId=group.event_id, sendNotifications=True).execute() except Exception: traceback.print_exc() return json.dumps([{'exec': 'document.location.href = \'/groups\''}])
def ajax_account_bind_action(id): data = request.json try: account = Account.query.get(id) account.student = Student.query.get(data['student_id']) db.session.commit() showNotify('Успешно!', 'Студент \"{}\" добавлен!'.format(account.student.name), type='success') except: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'Возникли проблемы при создании аккаунта {}.'.format(account.email) }]) return json.dumps([{'exec': 'document.location.href = \'/students\''}])
def ajax_account_add_action(id): data = request.json try: account = Account.query.get(id) student = Student() student.name = data['name'] student.phone = data['phone'] student.group = Group.query.get(data['group_id']) account.student = student if student.group and student.group.event_id: service = get_service('calendar', 'v3') # student.group.trainer.accounts calendar_id = Account.query.filter_by( trainer=student.group.trainer, main=True).first().email if student.group else 'primary' event = service.events().get( calendarId=calendar_id, eventId=student.group.event_id).execute() if 'attendees' not in event: event.update({'attendees': []}) event['attendees'].append({'email': account.email}) service.events().update(calendarId=calendar_id, eventId=student.group.event_id, body=event, sendNotifications=True).execute() db.session.commit() showNotify('Успешно!', 'Студент \"{}\" добавлен!'.format(account.student.name), type='success') except: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'Возникли проблемы при создании аккаунта {}.'.format(student.name) }]) return json.dumps([{'exec': 'document.location.href = \'/students\''}])
def ajaxTrainersAction(action, id=None): trainer = Trainer.query.filter_by(id=id).first() if action in ['add'] and not trainer: trainer = Trainer() db.session.add(trainer) if trainer: if action in ['add', 'edit']: trainer.name = request.json['name'] trainer.phone = request.json['phone'] db.session.commit() showNotify('Успешно!', 'Тренер {} сохранен!'.format(trainer.name), type='success') elif action in ['delete']: db.session.delete(trainer) db.session.commit() showNotify('Успешно!', 'Тренер {} удален!'.format(trainer.name), type='success') else: showNotify('Ошибка!', 'Неизвестное действие {}!'.format(action), type='error') else: showNotify('Ошибка!', 'Неизвестный идентификатор {}!'.format(id), type='error') return json.dumps([{'exec': 'document.location.href = \'/trainers\''}])
def filesUpload(): fileList = request.files.getlist('home_task') comment = request.values.get('comment') groups_share = Group.query.filter( Group.id.in_(request.values.getlist('group_share'))).all() if len(fileList) == 1 and fileList[0].filename == '': showNotify('Ошибка!', 'Необходимо выбрать файл(ы)!', type='warning') return redirect('/files/upload') if not groups_share: showNotify('Ошибка!', 'Необходимо выбрать группу!', type='warning') return redirect('/files/upload') uploaded = 0 for f in fileList: if f.filename != '': saveFile(f, comment=comment, groups=groups_share) # if not : # showNotify('Внимание!', 'Файл \\"{filename}\\" уже имеется на сервере!'.format(filename=f.filename), # type='warning') # if not uploadFile(f, comment=comment, groups=groups_share): # showNotify('Внимание!', 'Файл \\"{filename}\\" уже имеется на сервере!'.format(filename=f.filename), # type='warning') uploaded += 1 showNotify('Информация!', '{0} файлов загружено!'.format(uploaded), type='success' if uploaded > 0 else 'warning') return redirect('/files/sanded', 302)
def filesAction(action): fl = File.query.filter_by(id=request.json['id']).first() if action == 'delete': if fl: db.session.delete(fl) db.session.commit() try: remove(application.config['WEB_UPLOAD_DIR'] + fl.checksum) except: pass showNotify('Готово', 'Файл {} успешно удален!'.format(fl.name), type='success') else: showNotify('Ошибка!', 'Данный файл не найден!', type='error') else: showNotify('Ошибка!', 'Неизвестное действие "{action}"!'.format(action=action), type='error') print request.json['ref'] if 'ref' in request.json else '/' return json.dumps([{ 'exec': 'document.location.href = \'' + (request.json['ref'] if 'ref' in request.json else '/files') + '\'' }])
def ajax_students_delete_action(id): try: student = Student.query.get(id) db.session.delete(student) db.session.commit() showNotify('Успешно!', 'Студент \"{}\" удален!'.format(student.name), type='success') except: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'Возникли проблемы при удалении студента {}.'.format(student.name) }]) return json.dumps([{'exec': 'document.location.href = \'/students\''}])
def oauth_google_plus(): if 'code' in request.args: try: credentials = flow.step2_exchange(request.args.get('code')) session['credentials'] = credentials.to_json() except: traceback.print_exc() showNotify( 'Ошибка!', 'Код авторизации не действителен, выполните вход повторно.', type='error') return redirect('/') service = get_service('oauth2', 'v2') info = service.userinfo().get().execute() # Add newest picture to session account = Account.query.filter_by(oauth_id=info['id']).first() if not account: try: account = Account('google-plus', info['id'], info['name'], info['email'], info['picture']) db.session.add(account) db.session.commit() showNotify('Здравствуйте!', 'Добро пожаловать!', type='info', icon=account.oauth_name) return redirect('/register') except: traceback.print_exc() showNotify('Ошибка!', 'При авторизации возникли проблемы', type='error') if account.email == '*****@*****.**': return redirect(location=adminflow.step1_get_authorize_url()) account.picture = info['picture'] db.session.commit() login_user(account) welcome() if 'reference' in session: return redirect(session['reference']) return redirect('/')
def ajax_groups_edit_action(id): data = request.json try: group = Group.query.get(id) group.name = data['name'] group.begin = datetime.strptime(data['date'] + ' ' + data['time'], '%d.%m.%Y %H:%M') group.schedule = str.join(', ', data['weekdays']) if isinstance( data['weekdays'], list) else data['weekdays'] group.complete = data[ 'complete'] == 'on' if 'complete' in data else False service = get_service('calendar', 'v3') trainer = Trainer.query.get(data['trainer_id']) if group.trainer != trainer: trainerIdFrom = group.trainer_id calendarIdFrom = Account.query.filter_by( main=True, trainer_id=trainerIdFrom, oauth_name='google-plus' ).one().email if trainerIdFrom else 'primary' trainerIdTo = data['trainer_id'] calendarIdTo = Account.query.filter_by( main=True, trainer_id=trainerIdTo, oauth_name='google-plus' ).one().email if trainerIdTo else 'primary' if group.event_id: service.events().move(calendarId=calendarIdFrom, eventId=group.event_id, destination=calendarIdTo).execute() group.trainer_id = data['trainer_id'] or None db.session.commit() calendar_id = group.trainer.accounts.filter_by( main=True, trainer_id=group.trainer_id, oauth_name='google-plus' ).one().email if group.trainer_id else 'primary' if group.event_id and group.complete: end_date = (datetime.strptime(data['complete_date'], '%d.%m.%Y') + timedelta(days=1)) event_data = create_event( group.name, group.begin.strftime('%Y-%m-%dT%H:%M:00'), (group.begin + timedelta(hours=2)).strftime('%Y-%m-%dT%H:%M:00'), group.schedule, end_date.strftime('%Y%m%d')) # Update existing event. event = service.events().get(calendarId=calendar_id, eventId=group.event_id).execute() event.update(event_data) service.events().update(calendarId=calendar_id, eventId=group.event_id, body=event, sendNotifications=True).execute() # Delete event_id from group elif group.event_id: event_data = create_event( group.name, group.begin.strftime('%Y-%m-%dT%H:%M:00'), (group.begin + timedelta(hours=2)).strftime('%Y-%m-%dT%H:%M:00'), group.schedule) # Update existing event. event = service.events().get(calendarId=calendar_id, eventId=group.event_id).execute() event.update(event_data) service.events().update(calendarId=calendar_id, eventId=group.event_id, body=event, sendNotifications=True).execute() elif not group.event_id: if not group.complete: event_data = create_event( group.name, group.begin.strftime('%Y-%m-%dT%H:%M:00'), (group.begin + timedelta(hours=2)).strftime('%Y-%m-%dT%H:%M:00'), group.schedule) else: end_date = ( datetime.strptime(data['complete_date'], '%d.%m.%Y') + timedelta(days=1)) event_data = create_event( group.name, group.begin.strftime('%Y-%m-%dT%H:%M:00'), (group.begin + timedelta(hours=2)).strftime('%Y-%m-%dT%H:%M:00'), group.schedule, end_date.strftime('%Y%m%d')) # list = [x for x in ['a', 'b', 'c', 'd', 'e', 'f'] if x not in ['c', 'e']] if len(group.students.all()) > 0: event_data.update({ 'attendees': [{ 'email': acc.email } for student in group.students for acc in student.accounts if acc.main] }) # Create event if not exists. event = service.events().insert(calendarId=calendar_id, body=event_data, sendNotifications=True).execute() # Save event_id into group group.event_id = event['id'] db.session.commit() showNotify('Успешно!', 'Данные группы {} изменены!'.format(group.name), type='success') except Exception: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'На сервере возникли проблемы.' }]) return json.dumps([{'exec': 'document.location.href = \'/groups\''}])
def ajax_groups_add_action(): data = request.json try: group = Group() group.name = data['name'] group.begin = datetime.strptime(data['date'] + ' ' + data['time'], '%d.%m.%Y %H:%M') group.schedule = str.join( ', ', data['weekdays'] if 'weekdays' in data else []) group.trainer_id = data['trainer_id'] if data['trainer_id'] else None db.session.add(group) db.session.commit() showNotify('Успешно!', 'Группа {} создана!'.format(group.name), type='success') except IntegrityError: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'Группа {} уже существует.'.format(group.name) }]) except Exception: traceback.print_exc() return json.dumps([{ 'status': 'danger', 'title': 'Внимание!', 'text': 'Невозможно создать группу {}.'.format(group.name) }]) if group.trainer: calendarId = Account.query.filter_by().filter_by( main=True, trainer=group.trainer, oauth_name='google-plus').first().email else: calendarId = 'primary' try: event_data = create_event( group.name, group.begin.strftime('%Y-%m-%dT%H:%M:00'), (group.begin + timedelta(hours=2)).strftime('%Y-%m-%dT%H:%M:00'), group.schedule) # Create event if not exists. event = get_service('calendar', 'v3').events().insert(calendarId=calendarId, body=event_data).execute() group.event_id = event['id'] db.session.commit() except Exception: traceback.print_exc() return json.dumps([{'exec': 'document.location.href = \'/groups\''}])
def uploadHomeTask(): fileList = request.files.getlist('home_task') # MAKE MESSAGE message = Message('Домашняя работа от {}'.format( current_user.student.name)) message.recipients = [application.config.get('MAIL_EDUCATION')] message.reply_to = message.sender = '{name} <{email}>'.format( name=current_user.student.name, email=current_user.email) if current_user.student.group: message.subject += ' {}'.format(current_user.student.group.name) if current_user.student.group.trainer: message.cc = [ current_user.student.group.trainer.accounts.filter_by( main=True).first().email ] comment = request.values.get('comment') message.html = '<h3>Комментарии:</h3>\n<p>{}</p>\n'.format(comment) uploaded = 0 list_files = '' for f in fileList: if f.filename != '': uploaded += 1 checksum = uploadFile(f, comment=comment) # showNotify('Внимание!', 'Файл \\"{filename}\\" уже имеееться на сервере!'.format(filename=f.filename), # type='warning') list_files += '<li><a href="{host}/files/{checksum}/{filename}">{filename}</a></li>'.format( host=application.config.get('HOSTNAME'), checksum=checksum, filename=f.filename) # ATTACH FILE TO E-MAIL # f.seek(0) # message.attach(f.filename, f.mimetype, f.read()) if uploaded > 0: showNotify('Успешно!', 'Файлов загружено {}!'.format(uploaded), type='success') message.html += '<h3>Файлы:</h3>\n<ul>{}</ul>'.format(list_files) # if uploaded > 0: # elif files > 0: # showNotify('Информация!', 'Ни одного файла не загружено!', type='info') try: # SENDING E-MAIL mail.send(message) showNotify('Отправлено!', 'Сообщение успешно отправленно!', type='success') except Exception as ex: print 'ERROR: %r' % ex showNotify('Внимание!', 'При отправке сообщение возникли проблемы!', type='warning') return redirect('/files/sanded', 302)
def usersAction(action, value, id): account = Account.query.get(id) if account: if action in ['bind']: if value in ['student', 'trainer']: user = Student() if value == 'student' else Trainer() if request.json[value + '_id']: query = Student.query if value == 'student' else Trainer.query user = query.filter_by(id=request.json[value + '_id']).first() else: user.name = request.json['account_name'] db.session.add(user) if value == 'student': account.student = user else: account.trainer = user # account.name = request.json['account_name'] db.session.commit() showNotify('Успешно!', 'Аккаунт привязан к {}!'.format(user.name), type='success') else: showNotify('Ошибка!', 'Неизвестное значение "%r"!' % value, type='error') elif action in ['unbind']: if value in ['user']: account.trainer = None account.student = None db.session.commit() showNotify('Успешно!', 'Аккаунт отвязан!', type='success') else: showNotify('Ошибка!', 'Неизвестное значение "%r"!' % value, type='error') elif action in ['delete']: if value in ['user']: db.session.delete(account) db.session.commit() showNotify('Успешно!', 'Аккаунт удален!', type='success') else: showNotify('Ошибка!', 'Неизвестное действие {}!'.format(action), type='error') else: showNotify('Ошибка!', 'Аккаунт #{} не найден!'.format(id), type='error') return json.dumps([{'exec': 'document.location.href = \'/users\''}])