def upload( yd, log, photo, local_path, chat_title, ): uploaded = False with open(local_path, "rb") as f: if not Chat.is_exists(photo.chat_id): try: Chat.save_to_db(photo.chat_id, chat_title) except BaseException as e: log.error('{0}'.format(e)) yd_path = photo.get_yd_path(yd) if not yd.exists(yd_path): start = time.time() yd.upload(f, yd_path) end = time.time() log.info("YD uploaded: {0} ({1}s)".format( yd_path, str(end - start))) if not Photo.is_exists(photo.chat_id, local_path): db.session.add(photo) db.session.commit() log.info("DB added: " + yd_path) uploaded = True os.remove(local_path) return uploaded
def test_get_chat(self): self.assertEqual(Chat.get_chat([self.bob, self.arthur]), self.chat_bob_arthur) self.assertEqual(Chat.get_chat([self.clair, self.bob]), self.chat_bob_clair) self.assertEqual(Chat.get_chat([self.arthur, self.morgana]), self.chat_morgana_arthur)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() database.create_all() Role.insert_roles() self.client = self.app.test_client(use_cookies=True) self.bob = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.arthur = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.clair = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.chat_bob_arthur = Chat() self.chat_bob_arthur.add_users([self.bob, self.arthur]) database.session.add_all( [self.bob, self.arthur, self.clair, self.chat_bob_arthur]) database.session.commit()
class TestChatRoom(unittest.TestCase): def setUp(self): self.new_chat=Chat(username='******', message='wagwan') self.new_chat.save_chat() def test_chat_saved(self): self.assertTrue(len(Chat.query.all())>0)
def init_chat(message): with app.app_context(): if not is_initialized(message): if not Chat.is_exists(message.chat.id): try: ch = Chat.save_to_db(message.chat.id, message.chat.title) except BaseException as e: self.l.error('{0}'.format(e)) ch.get_yd_folder(self.y)
def test_from_json(self): json_chat = {'chat_name': None, 'users': ['morgana']} chat = Chat.from_json(json_chat, self.clair) self.assertEqual(chat.name, None) self.assertEqual(chat.get_name(self.clair), self.morgana.username) self.assertEqual(chat.get_name(self.morgana), self.clair.username) self.assertIn(self.clair, chat.users.all()) self.assertIn(self.morgana, chat.users.all()) json_chat = {'chat_name': None, 'users': ['morgana', 'bob']} with self.assertRaises(ValidationError): Chat.from_json(json_chat, self.clair)
def admin_index_view(): stats = {'all_active_users': User.count(), 'today_active_users': User.today_all_active_users(), 'all_chats': Chat.count(), 'today_chats': Chat.today_new_count(), 'all_messages': sum(u.msg_count for u in UserStat.all()), 'today_messages': Message.today_all_count(), 'last_chats': Chat.last_chats_list()} return render_template('admin/index.html', stats=stats, entities=Entity.generate_list()[0], format_time=format_time)
def chat_create_new(telegram_chat_id: int, session=None) -> Chat: """ Создает новый чат :param telegram_chat_id: Идентификатор чата в телеграме :param session: Сессия БД :return: Созданный чат """ chat = Chat() chat.telegram_chat_id = telegram_chat_id session.add(chat) session.flush() return chat
def test_search_chats_query(self): chats = Chat.search_chats_query('mor', self.bob).all() self.assertIn(self.chat_morgana_bob, chats) self.assertEqual(len(chats), 1) self.chat_morgana_bob.name = 'chat' chats = Chat.search_chats_query('chat', self.bob).all() self.assertIn(self.chat_morgana_bob, chats) self.assertEqual(len(chats), 1) chats = Chat.search_chats_query('wrong', self.bob).all() self.assertEqual(len(chats), 0) chats = Chat.search_chats_query('art', self.bob).all() self.assertIn(self.chat_bob_arthur, chats) self.assertIn(self.chat_bob_artorias, chats) self.assertEqual(len(chats), 2)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() database.create_all() Role.insert_roles() self.bob = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.arthur = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.clair = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.morgana = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.ophelia = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.artorias = User(username='******', password='******', email='*****@*****.**', confirmed=True) self.chat_bob_arthur = Chat() self.chat_bob_artorias = Chat() self.chat_bob_clair = Chat() self.chat_morgana_arthur = Chat() self.chat_morgana_bob = Chat(name='chat_morgana_bob_') self.chat_bob_arthur.add_users([self.bob, self.arthur]) self.chat_bob_artorias.add_users([self.bob, self.artorias]) self.chat_bob_clair.add_users([self.bob, self.clair]) self.chat_morgana_arthur.add_users([self.arthur, self.morgana]) self.chat_morgana_bob.add_users([self.bob, self.morgana]) database.session.add_all([ self.bob, self.arthur, self.ophelia, self.artorias, self.clair, self.morgana, self.chat_bob_arthur, self.chat_bob_artorias, self.chat_bob_clair, self.chat_morgana_arthur, self.chat_morgana_bob ]) database.session.commit()
def add_chat(): if request.method == 'POST': data = request.form.to_dict() chat_context = data['comment_context'] new_chat = Chat(chat_context, current_user.id) db.session.add(new_chat) db.session.commit() all_chats = Chat.query.all() result_list = [] # TODO limit 두기 for chat in all_chats: author = db.session.query(User).filter(User.id == chat.user_id).first() result_list.append({ "id": chat.id, "comment_context": chat.chat_context, "comment_creDate": chat.chat_creDate, "author": author.username, "author_id": author.id, "author_thumbnail": "http://127.0.0.1:5000/static/image/user/" + author.thumbnail }) return jsonify(result_list)
def create_chat(): raw_chat = request.get_json(True) chat = Chat(name=raw_chat['name'], created_by=current_user.id) db.session.add(chat) db.session.commit() first_chat_member = ChatMember(user_id=current_user.id, chat_id=chat.id, chat_role_id=2) chat_members = [] for raw_member in raw_chat['members']: user = None print(raw_member) if 'id' in raw_member.keys(): user = User.query.get(raw_member['id']) else: user = User.query.filter_by( username=raw_member['username']).first() if user: chat_members.append( ChatMember(chat_id=chat.id, user_id=user.id, chat_role_id=(raw_member['role'] if 'role' in raw_member.keys() else 1))) db.session.add_all([first_chat_member] + chat_members) db.session.commit() return ({ 'success': True, 'id': chat.id, 'firtsMemberId': first_chat_member.id })
def chat_info(chat_id): chat = Chat.get(Chat.id == chat_id) users = [ model_to_dict(x.user) for x in Participation.select().where(Participation.chat == chat_id) ] return dict(chat=model_to_dict(chat), users=users)
def update_chat(chat_id): # TODO: Add authentication allowing any member of the chat to use data = request.get_json() chat_name = data.get("chat_name") background = data.get("background") chat = Chat.get(Chat.id == chat_id) if chat_name: query = Chat.update(name=chat_name).where(Chat.id == chat_id) query.execute() elif background: query = Chat.update(background=background).where(Chat.id == chat_id) query.execute() chat = Chat.get(Chat.id == chat_id) return jsonify(model_to_dict(chat)), 200
def create_chat(): """ Creates a chat specified by a client Client must post json including: "chat_name": name for the chat "users": a list of users to add on creation of the chat """ # TODO: Add authentication allowing any logged in user to use data = request.get_json() chat_name = data.get("chat_name") try: new_chat = Chat.create(name=chat_name) except Exception as e: return str(e), 400 if data.get("users") is not None: try: for phone_number in data.get("users"): user = User.select().where( User.phone_number == phone_number).get() Participation.create(chat=new_chat, user=user, rank="member") except Exception as e: return str(e), 400 return jsonify(model_to_dict(new_chat)), 201
def mute(bot: Bot, update: Update, chat: Chat): if not chat.muted: chat.muted = True bot.send_message( chat.id, '👌 вернуть обратно - /start') # OK emoji :)))) return
def post_chats(): """ Create chat """ form = ChatForm() if request.content_type != 'application/x-www-form-urlencoded': error_msg = 'Invalid content type' response = make_response({"error": error_msg}, 400) return response if not form.validate_on_submit(): error_msg = 'Invalid form data' response = make_response({"error": error_msg}, 400) return response data = form.title.data chat_ = Chat(title=data) db.session.add(chat_) db.session.commit() user_id = request.cookies.get('user_id') user = User.query.get(user_id) user.chats.append(chat_) db.session.commit() response = make_response({"status": "ok"}, 201) response.headers[ "Location"] = f"http://{request.host}/api/chats/{chat_.id}" return response
def get_chats(): """ Returns chats for a given user_id """ result_proxy = db.session.execute( ''' SELECT c.id ,c.name ,c.created_at ,c.updated_at FROM chats AS c INNER JOIN chat_users AS cu ON cu.chat_id = c.id WHERE cu.user_id = :user_id ORDER BY c.updated_at DESC ''',dict(user_id=request.args['user_id']) ) result = [Chat.from_dict(r).to_dict() for r in result_proxy] return jsonify(result)
def db_setting(): db.session.add(User(name='김수완', gcn='1103', image_path='profile1')) db.session.add(User(name='조호원', gcn='1118', image_path='profile2')) db.session.add( Club(club_name='세미콜론', total_budget=3000, current_budget=2000, banner_image='banner image', hongbo_image='hongbo image', profile_image='profile_image')) db.session.add(ClubHead(user_id=1, club_id=1)) db.session.add(Room(user_id=2, club_id=1)) db.session.add(Chat(room_id=1, msg='첫번째 채팅', user_type='U')) db.session.add(Chat(room_id=1, msg='두번째 채팅', user_type='C')) db.session.commit()
def test_models(self): Chat.save_to_db(1, "test1") ch = Chat.get_chat(1) self.assertEqual(1, ch.id) self.assertEqual("test1", ch.name) o = ch.options.all() self.assertTrue(len(o) == 2) ch.add_option("test_key", "test_val") o = ch.options.all() self.assertTrue(len(o) == 3) self.assertEqual("test_key", o[2].key) self.assertEqual("test_val", o[2].value) self.assertIsNotNone(o[2].chat) self.assertIsNotNone(ChatOption.get_val(ch.id, "test_key")) self.assertIsNone(ChatOption.get_val(ch.id, "test_val")) with self.assertRaises(Exception): ch.add_option("test_key", "exception")
def help(message): with app.app_context(): bot.send_message(message.chat.id, 'Привет! Я фото-бот. Зачем я нужен? Мне всегда очень жаль, когда у Пети одни фотки, у Кати другие, у Стёпы третьи. Уже несколько лет назад было дано обещание обменяться фотками, но до дела так и не дошло. Потому что муторно :-\\' + '\n\nЯ же соберу все фото из этого чата и залью их на яндекс-диск, чтобы у всех друзей к концу отпуска был одинаковый набор фото. Также я их рассортирую по дате и времени, чтобы можно было посмотреть на моменты отпуска с разного ракурса' + '\n\nПри этом я хочу чтобы все фото из альбома можно было легко отретушировать и распечатать без потери в четкости, поэтому я их сохраняю в максимальном качестве' + '\n\nЧто нужно мне, чтобы я смог сделать всё обещанное? Просто отправлять в этом чате все фотки ФАЙЛАМИ. Сейчас покажу как.') if ChatOption.get_val(1, "android_how_to_video_id"): bot.send_video(message.chat.id, ChatOption.get_val(1, "android_how_to_video_id")) else: f = open(basedir + '/android_how_to.mp4', 'rb') msg = bot.send_document(message.chat.id, f, None) Chat.get_chat(1).add_option("android_how_to_video_id", msg.video.file_id) bot.send_message(message.chat.id, '6 шагов: \n1) скрепка\n2) тянем вверх\n3) галерея\n4) camera\n5) отмечаем фото\n6) без сжатия')
def event_send_chat(json): logger.info('JSON: ' + str(json)) emit('recv_chat', {'msg': json.get('msg')}, room=json.get('room_id')) db.session.add( Chat(room_id=json.get('room_id'), msg=json.get('msg'), user_type=json.get('user_type'))) db.session.commit()
def get_or_create_chat(self, chat_id: str): chat = self.session.query(Chat).get(str(chat_id)) if chat: return chat chat = Chat(id=str(chat_id)) self.session.add(chat) self.session.commit() return chat
def list_user_chats(user_id): """List all chats for a given user""" chats = [] raw_chats = Participation.select().where(Participation.user == user_id) for item in raw_chats: chat = Chat.get(Chat.id == item.chat) chats.append(model_to_dict(chat)) return jsonify(chats), 200
def chat_list(): user = Account(session['user']) if not user: flash('Please, fill in information about yourself', 'info') return redirect(url_for('settings')) chats = Chat.get_chats(session['user']) print(chats) return render_template('chat-list.html', cur_user=user, chats=chats)
def test_remove_users(self): chat = Chat() chat.add_users([self.bob, self.clair, self.morgana]) self.assertEqual(chat.users.count(), 3) self.assertIn(self.bob, chat.users.all()) chat.remove_users([self.bob]) self.assertEqual(chat.users.count(), 2) self.assertNotIn(self.bob, chat.users.all()) chat.remove_users([self.morgana, self.clair]) self.assertEqual(chat.users.count(), 0)
def wrapper(update: Update, context: CallbackContext, *args, **kwargs): if not update.effective_user: # bots, may be exclude in filter messages return if update.effective_chat: # we need settings for a group chats, not for a specific user # private chat id == user id chat_id = update.effective_chat.id else: # inline commands, get settings for his private chat chat_id = update.effective_user.id if update.effective_user.language_code: # chats don't have language_code, that why we take from user, not so correct yes # they will able change language later # https://en.wikipedia.org/wiki/IETF_language_tag language_code = update.effective_user.language_code.lower() else: # some users don't have locale, set default language_code = settings.LANGUAGE_CODE db_session = Session() chat = db_session.query(Chat).filter_by(id=chat_id).first() if not chat: chat = Chat( id=chat_id, locale=language_code, is_show_keyboard=True if chat_id > 0 else False, # never show keyboard for a group chats ) db_session.add(chat) try: transaction.commit() chat_created = True except IntegrityError: chat_created = False logging.exception("Error create chat, chat exists") transaction.abort() finally: chat = db_session.query(Chat).filter_by(id=chat_id).one() else: chat_created = False kwargs["chat_info"] = { "chat_id": chat.id, "created": chat_created, "locale": chat.locale, "is_subscribed": chat.is_subscribed, "is_show_keyboard": chat.is_show_keyboard, "keyboard_size": chat.keyboard_size, "default_currency": chat.default_currency, "default_currency_position": chat.default_currency_position, } return func(update, context, *args, **kwargs)
def createchat(user, bot): newchat = Chat(user_id = user, bot_id = bot, botdetail_id = 1) db.session.add(newchat) db.session.commit() response = {} instruction = getbotmessage(bot, 1, user) response['instruction'] = instruction response['id'] = newchat.id return response
def validate_name(self, name): if not name.data.isalnum(): raise ValidationError( 'Chat name must be alphanumeric (no spaces or special characters)' ) chat = Chat.get_by_name(name.data) if chat is not None: raise ValidationError('That chat name is already taken.')
def wrapper(bot, update, *args, **kwargs): s = Session() if not Chat.q.get(update.message.chat.id): chat = Chat(id=update.message.chat.id, is_private=update.message.chat.type == 'private') s.add(chat) s.commit() chat = Chat.q.get(update.message.chat.id) # type: Chat return fn(bot, update, *args, chat, **kwargs)
def create_process(): if session.get('id', '') == '': return redirect('/business/') elif not Business.check_confirmed(session.get('id', '')): return redirect('/business/unconfirmed') b_id = session['id'] form = CreateProcessForm() s_form = SelectFieldTypeForm() h = HelpForm() s_form.select_type.choices = [(p.id, p.type) for p in PossibleProcess.query.filter_by(business_id=b_id).all()] d_form = DateForm() if form.validate_on_submit() and d_form.validate_on_submit(): if Client.email_is_free(form.client_email.data): client = Client(form.client_email.data) cl_id = client.save() else: cl_id = Client.get_id(form.client_email.data) client_password = Client.random_password(10) number = Process.random_number() process = Process(s_form.select_type.data, form.description.data, b_id, cl_id, number, form.price.data, client_password, d_form.dt.data, 0) pr_id = process.save() id_stage = Stage.get_not_started(s_form.select_type.data) process = Process.query.filter_by(id=pr_id).first() process.current_stage = id_stage chat = Chat(pr_id, b_id) chat.save() process.save() Process.send_number(form.client_email.data, Business.get_name(b_id), number, client_password) # string = "Услуга была создана под номером: " + number return redirect(url_for('business.created_process', process_id=pr_id)) elif form.validate_on_submit() and not d_form.validate_on_submit(): d_form.dt.errors = ("Выберите дату", "") h.desc.choices = [(p.desc, p.desc) for p in PossibleProcess.query.filter_by(business_id=b_id).all()] h.price.choices = [(p.price, p.price) for p in PossibleProcess.query.filter_by(business_id=b_id).all()] h.pic.choices = [(p.picture, p.picture) for p in PossibleProcess.query.filter_by(business_id=b_id).all()] return render_template('create_process.html', form=form, h=h, s_form=s_form, d_form=d_form, title='Создание заказа')
def post(self, reciepent, text): reciepent = User.get_by_key_name(reciepent) sender = User.get_by_key_name(self.fb_uid) chatjoin = ChatJoin.get_chat(sender.fb_uid, reciepent.fb_uid) message = Message(chatjoin = chatjoin, sender = sender, text = text) message.put() chatjoin.put() chat = Chat(key_name = sender.fb_uid + '|' + reciepent.fb_uid, chatjoin = chatjoin, user = sender, other = reciepent, date = message.date, last_message_text = message.text, read = True) chat.put() chat = Chat(key_name = reciepent.fb_uid + '|' + sender.fb_uid, chatjoin = chatjoin, user = reciepent, other = sender, date = message.date, last_message_text = message.text, read = False) chat.put() self.send_message(reciepent.fb_uid, { 'type' : 'new-chat', 'chat' : chat, }) return True
def index(): stats = cache.get('web_stats') if not stats: stats = { 'users_count': User.all().count(), 'chats_count': Chat.all().count(), 'messages_count': sum(u.msg_count for u in UserStat.all()) } cache.set('web_stats', stats, 300) return render_template('index.html', page_title='Confstat', users_count=stats['users_count'], chats_count=stats['chats_count'], messgaes_count=stats['messages_count'])
def user_view(uid, token=True): user = User.where('uid', uid).get().first() if user: if user.public or token == cache.get('user_token_{}'.format(uid)): # Get user statistics stats = UserStat.where('uid', uid).get().all() info = {'first_act': 0, 'last_act': 0, 'total_msg': 0, 'groups': []} if stats: for stat in stats: info['total_msg'] += stat.msg_count # Generating groups list info['groups'].append({ 'title': Chat.get(stat.cid).title, 'msg_count': stat.msg_count }) # Get last activity timestamp if info['last_act'] < stat.last_activity: info['last_act'] = stat.last_activity # Generating date from timestamps info['first_act'] = datetime.fromtimestamp(stats[-1].last_activity).strftime('%d.%m.%y') info['last_act'] = datetime.fromtimestamp(info['last_act']).strftime('%d.%m.%y (%H:%M)') page_title = '{} - Confstat'.format(user.fullname) else: user = None info = None page_title = 'Confstat' return render_template('user.html', page_title=page_title, user=user, info=info, token=token) else: redirect('/')
def group(chat_hash): chat = Chat.where('hash', chat_hash).first() if chat: cid = chat.cid # Get chat statistics chat_stats = db.select('(SELECT * FROM chat_stats ' 'WHERE cid = "{}" ' 'ORDER BY id DESC LIMIT 21) ' 'ORDER BY id ASC'.format(cid)) # Chat title chat_title = chat.title # Bot add date, dd.mm.yy add_date = datetime.fromtimestamp(chat.add_time).strftime('%d.%m.%y') # Today messages NOT USED YET today_messages = Message.today_chat_count(cid) # All number of users all_users = Chat.all_chat_users(cid) # Today active users active_users = Chat.today_chat_users(cid) # Last update last_update = datetime.fromtimestamp(chat_stats[-1].last_time).strftime('%d.%m.%y (%H:%M)') # Link for public chats public_link = chat.public_link average_users = 0 chart = {'labels': [], 'msg_values': [], 'users_values': []} # Charts generator i = 0 for chat in chat_stats: average_users += chat.users_count # Dates, dd/mm d = datetime.fromtimestamp(chat.last_time).strftime('%d') chart['labels'].append(str(d)) chart['msg_values'].append(chat.msg_count) chart['users_values'].append(chat.users_count) i += 1 # Average number of users average_users = round(average_users / i) # Generating user list users = [] user_stats = UserStat.where('cid', cid).order_by('msg_count', 'desc').limit(50).get().all() for ustat in user_stats: user = User.get(ustat.uid) users.append({'name': user.fullname, 'msg_count': ustat.msg_count, 'uid': ustat.uid, 'public': user.public}) # Generating entities entities = Entity.generate_list(cid) return render_template('group.html', page_title='{} - Confstat'.format(chat_title), chat_title=chat_title, add_date=add_date, today_messages=today_messages, all_users=all_users, active_users=active_users, average_users=average_users, chart=chart, users=users, entities=entities[0], urls=entities[1], last_update=last_update, public_link=public_link) else: return redirect('/')
def group(chat_hash): # Get chat statistics chat_stats = ChatStat.where('hash', chat_hash).limit(21).get() if chat_stats: # Chat cid = chat_stats[0].cid chat = Chat.get(cid) # Chat title chat_title = chat.title # Bot add date, dd.mm.yy add_date = datetime.fromtimestamp(chat_stats[0].last_time).strftime('%d.%m.%y') # Today messages msg_count = chat_stats[-1].msg_count # Today active users active_users = chat_stats[-1].users_count # Last update last_update = datetime.fromtimestamp(chat_stats[-1].last_time).strftime('%d.%m.%y (%H:%M)') # Link for public chats public_link = chat.public_link average_users = 0 chart = {'labels': [], 'msg_values': [], 'users_values': []} # Charts generator i = 0 for chat in chat_stats: average_users += chat.users_count # Dates, dd/mm d = datetime.fromtimestamp(chat.last_time).strftime('%d') chart['labels'].append(str(d)) chart['msg_values'].append(chat.msg_count) chart['users_values'].append(chat.users_count) i += 1 # Average number of users average_users = round(average_users / i) # Generating user list users = [] user_stats = UserStat.where('cid', cid).order_by('msg_count', 'desc').limit(50).get().all() for ustat in user_stats: user = User.get(ustat.uid) users.append({'name': user.fullname, 'msg_count': ustat.msg_count, 'uid': ustat.uid, 'public': user.public}) # Generating entities entities = {'total': 0, 'photo': 0, 'audio': 0, 'video': 0, 'document': 0, 'url': 0, 'hashtag': 0, 'bot_command': 0, 'mention': 0} urls = [] i = 0 _entities = Entity.where('cid', cid).order_by('count', 'desc').get().all() for entity in _entities: if entity.type == 'voice': entities['audio'] += entity.count else: entities[entity.type] += entity.count entities['total'] += entity.count # Generating urls list if entity.type == 'url' and i < 9: urls.append({'link': entity.title, 'count': entity.count}) i += 1 return render_template('group.html', page_title='{} - Confstat'.format(chat_title), chat_title=chat_title, add_date=add_date, msg_count=msg_count, active_users=active_users, average_users=average_users, chart=chart, users=users, entities=entities, urls=urls, last_update=last_update, public_link=public_link) else: return redirect('/')