def _create_list_keyboard(list, lang, uuid=None) -> list: conn = database.get_connection() keyboard = [[]] option_votes = [] # In some cases, we haven't created the list yet, so we need to use an id to a to be created list. if uuid: list_id = str(uuid) else: list_id = list.id for vote_option in list.vote_options: cur = conn.execute("SELECT count(*) FROM user_votes WHERE list_id=? AND vote=?", [list_id, vote_option]) option_votes.append((cur.fetchone(), vote_option)) keyboard[0].append(InlineKeyboardButton(lang.get_text("vote_%s_keyboard" % vote_option), callback_data="vote*%s*%s" % (vote_option, list_id))) if max(option_votes)[0][0] > const.NAMES_PER_VOTE_TYPE: new_row = [] link = "t.me/%s?start=%s" % (const.aux.BOT_USERNAME, list_id) for votes in option_votes: new_row.append(InlineKeyboardButton("(%s)" % votes[0][0], url=link + "_%s" % votes[1])) keyboard.append(new_row) new_row = [InlineKeyboardButton(lang.get_text("forward_list"), switch_inline_query="id*%s" % list_id)] keyboard.append(new_row) conn.close() return keyboard
def save(self): conn = database.get_connection() exists = conn.execute("SELECT * FROM users WHERE id=?", [self.id]).fetchone() if exists: # Parse the values sql = """UPDATE users SET 'id'=?, 'first_name'=?, 'last_name'=?, 'username'=?, 'full_name'=?, 'full_name_simple'=?, 'language_code'=?, 'expiration_date'=? WHERE 'id'=? """ values = list(self.__dict__.values()) values.append(self.id) conn.execute(sql, values) else: # Parse the key and values d = self.__dict__ conn.execute("INSERT INTO users VALUES (?,?,?,?,?,?,?,?)", list(d.values())) conn.commit() conn.close()
def put_mold(wikia_name, mold_name): if request.content_type != 'application/json': response.status = 400 response.body = "Only Content-Type: application/json is permitted for this resource" return response if request.json is None: response.status = 400 response.body = "invalid json in request" return response db_connection = get_connection(CONFIG) wikia = Wikia() try: wikia.load_by_name(db_connection, wikia_name) except WikiaNotFoundException: response.status = 404 response.body = "Wikia not found" return response mold = Mold() try: mold.init_from_data(db_connection, wikia, mold_name, request.json) except MoldIncompleteException: response.status = 400 response.body = "Incomplete mold data given for PUT" return response mold.save(db_connection) response.status = 201 response.headers['Location'] = request.url return response
def _create_list_message(list, lang) -> str: conn = database.get_connection() text = "*%s*" % list.title for vote_option in list.vote_options: sql = r"SELECT full_name FROM users WHERE id IN " \ r"(SELECT * FROM " \ r"(SELECT user_id FROM user_votes WHERE list_id=? AND vote=? ORDER BY vote_timestamp DESC) LIMIT ?)" cur = conn.execute(sql, [list.id, vote_option, const.NAMES_PER_VOTE_TYPE]) names = cur.fetchall() sql = "SELECT count(*) FROM user_votes WHERE list_id=? AND vote=?" cur = conn.execute(sql, [list.id, vote_option]) n_votes = int(cur.fetchone()[0]) if not names: continue text += "\n\n" + lang.get_text("vote_%s_message_line" % vote_option) for name in names: text += "\n" + name[0] if n_votes > const.NAMES_PER_VOTE_TYPE: text += "\n+%s" % (n_votes - const.NAMES_PER_VOTE_TYPE) conn.close() return text
def save(self): conn = database.get_connection() exists = conn.execute("SELECT * FROM lists WHERE id=?", [self.id]).fetchone() if exists: sql = """ UPDATE lists SET 'id'=?, 'from_user_id'=?, 'title'=?, 'expiration_date'=? WHERE 'id'=? """ values = list(self.__dict__.values()) values.append(self.id) conn.execute(sql, values) else: # Parse the key and values d = self.__dict__ keys = str(list(d.keys())[0]) for k in list(d.keys())[1:]: keys += ", %s" % k values = str(list(d.values())[0]) for v in list(d.values())[1:]: values += ", %s" % v conn.execute("INSERT INTO lists VALUES (?,?,?,?)", list(d.values())) conn.commit() conn.close()
def delete_expired_users(): conn = database.get_connection() t = time() conn.execute("DELETE FROM user_votes WHERE user_id IN (SELECT id FROM users WHERE expiration_date <= ?)", [t]) conn.execute("DELETE FROM users WHERE expiration_date <= ?", [t]) conn.commit() conn.close()
def is_exist(self): connection = database.get_connection() job_key = self.make_unique_key() exist_name = connection.hexists(job_key, 'title') if exist_name == 0: return False return True
def is_exist(self): connection = database.get_connection() key = self.make_unique_key() exist_email = connection.hexists(key, 'email') if exist_email == 0: return False return True
def save(self): connection = database.get_connection() company_key = self.make_unique_key() print "saving company %s" % company_key connection.hset(company_key, 'name', self.name) connection.hset(company_key, 'href', self.href) connection.hset(company_key, 'scale', self.scale) connection.hset(company_key, 'industry', self.industry) connection.hset(company_key, 'nature', self.nature) connection.hset(company_key, 'introduction', self.introduction)
def get_lists_from_user(self, user_id: int) -> list: conn = database.get_connection() cur = conn.execute("SELECT id FROM lists WHERE from_user_id=?", [user_id]) results = [] for list_id in cur.fetchall(): results.append(self.get_list_by_id(list_id[0])) conn.close() return results
def save(self): connection = database.get_connection() job_key = self.make_unique_key() print "saving job %s" % job_key connection.hset(job_key, 'title', self.title) connection.hset(job_key, 'location', self.location) connection.hset(job_key, 'company', self.company) connection.hset(job_key, 'date', self.date) connection.hset(job_key, 'detail', self.detail) connection.hset(job_key, 'salary', self.salary) welfare_list_key = self.make_unique_welfare_key() for e in self.welfare: connection.sadd(welfare_list_key, e)
def load(self): connection = database.get_connection() object_key = self.email connection.hexists(object_key, 'email') connection.hget(object_key, 'email') connection.hget(object_key, 'nick') connection.hget(object_key, 'password') search_list_id = self.make_unique_search_list_id() search_list_len = connection.llen(search_list_id) search_list = connection.lrange(search_list_id, 0, -1) for l in search_list: self.search_list.append(l)
def _create_complete_list_message(list, vote_option, lang): conn = database.get_connection() text = "*%s*\n%s\n" % (list.title, lang.get_text("vote_%s_message_line" % vote_option)) sql = "SELECT full_name FROM users WHERE id IN " \ "(SELECT user_id FROM user_votes WHERE list_id=? AND vote=? ORDER BY vote_timestamp)" cur = conn.execute(sql, [list.id, vote_option]) names = cur.fetchall() if not names: text += "\n" + lang.get_text("vote_option_empty", vote_option=lang.get_text("vote_%s_keyboard" % vote_option)) else: for name in names: text += "\n%s" % name[0] conn.close() return text
def _create_complete_list_keyboard(list, lang): conn = database.get_connection() keyboard = [[],[]] option_votes = [] for vote_option in list.vote_options: cur = conn.execute("SELECT count(*) FROM user_votes WHERE list_id=? AND vote=?", [list.id, vote_option]) votes = cur.fetchone() keyboard[0].append(InlineKeyboardButton(lang.get_text("vote_%s_keyboard" % vote_option), callback_data="get_clist*%s*%s" % (vote_option, list.id))) keyboard[1].append(InlineKeyboardButton("(%s)" % votes[0], callback_data="get_clist*%s*%s" % (vote_option, list.id))) conn.close() return keyboard
def get_user_by_id(self, user_id: int): # Get the user if it's active if user_id in self.active_sessions: self.session_expire_time[user_id] = time() + SESSION_IDLE_LIFESPAN self.active_sessions[user_id].refresh_expiration_date() return self.active_sessions[user_id] # Get the user from the database conn = database.get_connection() user_dict = database.get_one_fetched_as_dict(conn.execute("SELECT FROM users WHERE id=?", conn.close() [user_id])) if user_dict: new_session = User(**user_dict) self.active_sessions[new_session.id] = new_session self.session_expire_time[new_session.id] = time() + SESSION_IDLE_LIFESPAN new_session.refresh_expiration_date() return new_session # User does not exist in the database return None
def cast_vote(bot, update): user = user_manager.get_user(update.effective_user) lang = get_lang(user.language_code) vote, list_id = update.callback_query.data.split("*")[1:3] list = list_manager.get_list_by_id(list_id) if list: conn = database.get_connection() # Check if the user has voted before this list cur = conn.execute("SELECT vote FROM user_votes WHERE user_id=? AND list_id=?", [user.id, list.id]) past_vote = cur.fetchone() if past_vote: # If it is a new vote type, we change the vote type. if past_vote[0] != vote: conn.execute("UPDATE user_votes SET vote=?, vote_timestamp=? WHERE user_id=? AND list_id=?", [vote, time(), user.id, list.id]) # If it is the same, we remove the vote else: conn.execute("DELETE FROM user_votes WHERE user_id=? AND list_id=?", [user.id, list.id]) else: conn.execute("INSERT INTO user_votes VALUES (?, ?, ?, ?)", [user.id, list.id, vote, time()]) conn.commit() conn.close() message, keyboard = _create_list_message(list, lang), _create_list_keyboard(list, lang) bot.edit_message_text(text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(keyboard), inline_message_id=update.callback_query.inline_message_id) update.callback_query.answer("okay 👍") else: update.callback_query.answer(lang.get_text("warning_list_does_not_exist"), shot_alert=True) bot.edit_message_reply_markup(inline_message_id=update.callback_query.inline_message_id, reply_markup=InlineKeyboardMarkup([[]]))
def delete_fragment(wikia_name, title): db_connection = get_connection(CONFIG) wikia = Wikia() try: wikia.load_by_name(db_connection, wikia_name) except WikiaNotFoundException: response.status = 200 return response fragment = Fragment() try: fragment.load_by_title(db_connection, wikia, title) except FragmentNotFoundException: response.status = 200 return response fragment.delete(db_connection) response.status = 204 return response
def delete_mold(wikia_name, mold_name): db_connection = get_connection(CONFIG) wikia = Wikia() try: wikia.load_by_name(db_connection, wikia_name) except WikiaNotFoundException: response.status = 200 return response mold = Mold() try: mold.load_by_name(db_connection, wikia, mold_name) except MoldNotFoundException: response.status = 200 return response mold.delete(db_connection) response.status = 204 return response
def get_mold(wikia_name, mold_name): db_connection = get_connection(CONFIG) wikia = Wikia() try: wikia.load_by_name(db_connection, wikia_name) except WikiaNotFoundException: response.status = 404 response.body = "Wikia not found" return response mold = Mold() try: mold.load_by_name(db_connection, wikia, mold_name) except MoldNotFoundException: response.status = 404 response.body = "Mold not found" return response view = MoldView(mold) return view.render_json()
def get_list_by_id(self, list_id): # Get the list if it's active if list_id in self.active_sessions: self.session_expire_time[list_id] = time() + SESSION_IDLE_LIFESPAN self.active_sessions[list_id].refresh_expiration_date() return self.active_sessions[list_id] # Get the list from the database conn = database.get_connection() list_dict = database.get_one_fetched_as_dict( conn.execute("SELECT * FROM lists WHERE id=?", [list_id])) conn.close() if list_dict: new_session = List(**list_dict) self.active_sessions[new_session.id] = new_session self.session_expire_time[ new_session.id] = time() + SESSION_IDLE_LIFESPAN new_session.refresh_expiration_date() return new_session # List does not exist in the database return None
def get_article(wikia_name, title): db_connection = get_connection(CONFIG) wikia = Wikia() try: wikia.load_by_name(db_connection, wikia_name) except WikiaNotFoundException: response.status = 404 response.body = "Wikia not found" return response fragment = Fragment() try: fragment.load_by_title(db_connection, wikia, title) except FragmentNotFoundException: response.status = 404 response.body = "Fragment not found" return response view = FragmentView(fragment) return view.render_json()
def get_user(self, telegram_user): # Get the user from active sessions if telegram_user.id in self.active_sessions: self.session_expire_time[telegram_user.id] = time() + SESSION_IDLE_LIFESPAN self.active_sessions[telegram_user.id].refresh_expiration_date() return self.active_sessions[telegram_user.id] # If the user isn't active, get it from the database conn = database.get_connection() user_dict = database.get_one_fetched_as_dict(conn.execute("SELECT * FROM users WHERE id=?", [telegram_user.id])) conn.close() if user_dict: new_session = User(**user_dict) self.active_sessions[new_session.id] = new_session self.session_expire_time[new_session.id] = time() + SESSION_IDLE_LIFESPAN new_session.refresh_expiration_date() return new_session # If the user is not in the database, register it. new_user = User(**telegram_user.__dict__) self.active_sessions[new_user.id] = new_user self.session_expire_time[new_user.id] = time() + SESSION_IDLE_LIFESPAN return new_user
def serve(request: bytes) -> str: """ Handle the peer request Parameters: request - the list containing the request parameters Returns: str - the response """ command = request[0:4].decode('UTF-8') if command == "LOGI": if len(request) != 64: return "0" * 16 ip = request[4:59].decode('UTF-8') port = request[59:64].decode('UTF-8') try: conn = database.get_connection(db_file) conn.row_factory = database.sqlite3.Row except database.Error as e: print(f'Error: {e}') return "0" * 16 try: peer = peer_repository.find_by_ip(conn, ip) # if the peer didn't already logged in if peer is None: session_id = str(uuid.uuid4().hex[:16].upper()) peer = peer_repository.find(conn, session_id) # while the generated session_id exists while peer is not None: session_id = str(uuid.uuid4().hex[:16].upper()) peer = peer_repository.find(conn, session_id) peer = Peer(session_id, ip, port) peer.insert(conn) conn.commit() conn.close() except database.Error as e: conn.close() print(f'Error: {e}') return "0" * 16 return "ALGI" + peer.session_id elif command == "ADDF": if len(request) != 152: return "Invalid request. Usage is: ADDF<your_session_id><file_md5><filename>" session_id = request[4:20].decode('UTF-8') md5 = request[20:52].decode('UTF-8') name = request[52:152].decode('UTF-8').lower() try: conn = database.get_connection(db_file) conn.row_factory = database.sqlite3.Row except database.Error as e: print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." try: peer = peer_repository.find(conn, session_id) if peer is None: conn.close() return "Unauthorized: your SessionID is invalid" file = file_repository.find(conn, md5) if file is None: file = File(md5, name, 0) file.insert(conn) file_repository.add_owner(conn, md5, session_id) else: file.file_name = name file.update(conn) if not file_repository.peer_has_file(conn, session_id, md5): file_repository.add_owner(conn, md5, session_id) num_copies = file_repository.get_copies(conn, md5) conn.commit() conn.close() except database.Error as e: conn.rollback() conn.close() print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." return "AADD" + str(num_copies).zfill(3) elif command == "DELF": if len(request) != 52: return "Invalid request. Usage is: DELF<your_session_id><file_md5>" session_id = request[4:20].decode('UTF-8') md5 = request[20:52].decode('UTF-8') try: conn = database.get_connection(db_file) conn.row_factory = database.sqlite3.Row except database.Error as e: print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." try: peer = peer_repository.find(conn, session_id) if peer is None: conn.close() return "Unauthorized: your SessionID is invalid" if not file_repository.peer_has_file(conn, session_id, md5): conn.close() return "ADEL999" peer_repository.file_unlink(conn, session_id, md5) copy = file_repository.get_copies(conn, md5) if copy == 0: file = file_repository.find(conn, md5) file.delete(conn) conn.commit() conn.close() except database.Error as e: conn.rollback() conn.close() print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." return "ADEL" + str(copy).zfill(3) elif command == "FIND": if len(request) != 40: return "Invalid command. Usage is: FIND<your_session_id><query_string>" session_id = request[4:20].decode('UTF-8') query = request[20:40].decode('UTF-8').lower().lstrip().rstrip() if query != '*': query = '%' + query + '%' try: conn = database.get_connection(db_file) conn.row_factory = database.sqlite3.Row except database.Error as e: print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." try: peer = peer_repository.find(conn, session_id) if peer is None: conn.close() return "Unauthorized: your SessionID is invalid" total_file = file_repository.get_files_count_by_querystring(conn, query) if total_file == 0: return 'AFIN' + str(total_file).zfill(3) result = str(total_file).zfill(3) file_list = file_repository.get_files_with_copy_amount_by_querystring(conn, query) for file_row in file_list: file_md5 = file_row['file_md5'] file_name = file_row['file_name'] copies = file_row['copies'] result = result + file_md5 + file_name + str(copies).zfill(3) peer_list = peer_repository.get_peers_by_file(conn, file_md5) for peer_row in peer_list: peer_ip = peer_row['ip'] peer_port = peer_row['port'] result = result + peer_ip + peer_port conn.commit() conn.close() except database.Error as e: conn.rollback() conn.close() print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." return "AFIN" + result elif command == "DREG": if len(request) != 52: return "Invalid request. Usage is: DREG<your_session_id><file_md5>" session_id = request[4:20].decode('UTF-8') md5 = request[20:52].decode('UTF-8') try: conn = database.get_connection(db_file) conn.row_factory = database.sqlite3.Row except database.Error as e: print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." try: peer = peer_repository.find(conn, session_id) if peer is None: conn.close() return "Unauthorized: your SessionID is invalid" file = file_repository.find(conn, md5) if file is None: return "File not found." file.download_count += 1 file.update(conn) conn.commit() conn.close() except database.Error as e: conn.rollback() conn.close() print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." return "ADRE" + str(file.download_count).zfill(5) elif command == "LOGO": if len(request) != 20: return "Invalid request. Usage is: LOGO<your_session_id>" session_id = request[4:20].decode('UTF-8') try: conn = database.get_connection(db_file) conn.row_factory = database.sqlite3.Row except database.Error as e: print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." try: peer = peer_repository.find(conn, session_id) if peer is None: conn.close() return "Unauthorized: your SessionID is invalid" deleted = file_repository.delete_peer_files(conn, session_id) peer.delete(conn) conn.commit() conn.close() except database.Error as e: conn.rollback() conn.close() print(f'Error: {e}') return "The server has encountered an error while trying to serve the request." return "ALGO" + str(deleted).zfill(3) else: return "Command \'" + request.decode('UTF-8') + "\' is invalid, try again."