def delete_user(username): db.delete_user_by_username(username) db.session().commit() if request.method == 'POST': flash("User '%s' successfully deleted." % username, category='success') return redirect(request.referrer) else: return dumps({'message': 'User %s successfully deleted' % username}) \
def edit_user_by_id(key: int): form = request.form db.edit_user_by_id(key, form) db.session().commit() message = "User with ID %r' successfully edited." % key if request.method == 'POST': flash(message, category='success') return redirect(request.referrer) else: return dumps({'message': message})
def record_message(m): """Adds a message to the database""" s = db.session() message2add = db.Message(msg_id=m.id, channel=m.channel.id, author=m.author.id, content=m.content, timestamp=m.created_at) s.add(message2add) s.flush() attachments = [] for a in m.attachments: att = db.Attachment(file_link=a.url, message_id=message2add.id) attachments.append(att) s.add_all(attachments) s.commit() report = s.query( db.Report).filter(db.Report.channel == m.channel.id).first() print(report) if report: rep_comment = db.ReportComment(message_id=message2add.id, report_id=report.id) s.add(rep_comment) s.commit() print("attached message to report") s.close()
def index(): blog_title = '我的博客' db_session = session() allblog = db_session.query(Blog).order_by(desc(Blog.post_date)).all() return render_template('index.html', blog_title=blog_title, allblog=allblog)
def post(self): user=self.get_argument("user") user_id=self.get_argument("user_id") s=session() if(s.query(User).filter(User.id==user_id,User.name==user,User.status==1).count() == 1): _files=s.query(File).filter(File.user_id==user_id,File.status==1).all() self.render('user-files.html',user=user,user_id=user_id,files=_files)
def get_references(self): if self.report: s = db.session() references = s.query(db.Message).join(db.Reference).filter(db.Reference.report_id == self.report_id) s.close() return references else: return None
def get(self): try: user=self.get_secure_cookie("user") data=json.loads(user) s=session() if(s.query(User).filter(User.id==int(data['user_id']),User.name==data['user'].encode('utf8'),User.status==1).count() == 1): self.render('user.html',user=data['user'],user_id=data['user_id']) except: self.redirect('/')
def classify_news(): s = session() news = s.query(News).filter(News.label != None).all() titles = [new.title for new in news] labels = [new.label for new in news] classificator = NaiveBayesClassifier(titles, labels) return classificator
def post(self): flag =False users=session().query(User).all()#hago la consulta a la base de datos if(len(users) > 0): for dato in users : if dato.name == self.get_argument("user") and dato.passw==self.get_argument("pass"): self.render('user.html',user=self.get_argument("user"),user_id=dato.id) break else: self.redirect('/')
def get_messages_below(msg, count): """Grabs the N messages below the message in the same channel""" s = db.session() timestamp = str(msg.timestamp) channel = str(msg.channel) results = s.execute("SELECT * FROM message WHERE message.timestamp>'" + timestamp + "' AND message.channel=" + channel + " ORDER BY timestamp LIMIT " + str(count) + ";") s.close() return results
def post(self): flag =False s=session() r=s.query(User).filter(User.passw==self.get_argument("pass"), User.name==self.get_argument("user")) if r.count() ==1: vjson={'user_id':r[0].id,'user':r[0].name} self.set_secure_cookie("user", json.dumps(vjson)) self.render('user.html',user=r[0].name,user_id=r[0].id) else: self.redirect('/')
def can_resolve_reports(ctx): s = db.session() can_do = False for r in ctx.message.author.roles: role = s.query( db.AdminRole).filter(db.AdminRole.role_id == r.id).first() if role and role.perms >= 3: can_do = True break s.close() return can_do
def is_admin(ctx): s = db.session() user_is_admin = False for r in ctx.message.author.roles: report = s.query( db.AdminRole).filter(db.AdminRole.role_id == r.id).first() if report: user_is_admin = True break s.close() return user_is_admin
def post(self): flag = False s = session() r = s.query(User).filter(User.passw == self.get_argument("pass"), User.name == self.get_argument("user")) if r.count() == 1: vjson = {'user_id': r[0].id, 'user': r[0].name} self.set_secure_cookie("user", json.dumps(vjson)) self.render('user.html', user=r[0].name, user_id=r[0].id) else: self.redirect('/')
def get_messages_above(msg, count): """Grabs the N messages above the message in the same channel""" s = db.session() timestamp = str(msg.timestamp) channel = str(msg.channel) results = s.execute( "WITH R AS (SELECT * FROM message WHERE message.timestamp<'" + timestamp + "' AND message.channel=" + channel + " ORDER BY timestamp DESC LIMIT " + str(count) + ") SELECT * FROM R ORDER BY timestamp;") s.close() return results
def recommendations(): # 1. Получить список неразмеченных новостей из БД # 2. Получить прогнозы для каждой новости # 3. Вывести ранжированную таблицу с новостями s = session() rows = s.query(News).filter(News.label == None).all() titles = [row.title for row in rows] new_labels = classify_news().predict(titles) for i in range(len(new_labels)): rows[i].label = new_labels[i] s.commit() return template('news_recommendations', rows=rows)
def can_view_reports(ctx): if isinstance(ctx.channel, discord.DMChannel): return False s = db.session() can_do = False for r in ctx.message.author.roles: role = s.query( db.AdminRole).filter(db.AdminRole.role_id == r.id).first() if role and role.perms >= 1: can_do = True break s.close() return can_do
def get(self): try: user = self.get_secure_cookie("user") data = json.loads(user) s = session() if (s.query(User).filter(User.id == int(data['user_id']), User.name == data['user'].encode('utf8'), User.status == 1).count() == 1): self.render('user.html', user=data['user'], user_id=data['user_id']) except: self.render('login.html')
def get(self): try: user = self.get_secure_cookie("user") data = json.loads(user) s = session() if (s.query(User).filter(User.id == int(data['user_id']), User.name == data['user'].encode('utf8'), User.status == 1).count() == 1): _files = s.query(File).filter(File.user_id == data['user_id'], File.status == 1).all() self.render('user-files.html', user=data['user'], files=_files) except: self.redirect('/')
def add_to_playlist(track_id: int, playlist_id: int = None, playlist_name: str = None): if not playlist_id: playlist_id = int(request.form.get('playlist_id')) if playlist_id == -1: if not playlist_name: playlist_name = request.form.get('playlist_name') playlist = db.Playlist(name=playlist_name, creator_id=get_current_user().id) else: playlist = db.get_playlist_by_id(playlist_id) track = db.get_track_by_id(track_id) # Check track not already in playlist f = [*filter(lambda track: track.id == track_id, playlist.tracks)] if not f or len(f) == 0: playlist.tracks.append(track) db.session().commit() return redirect(request.referrer)
def newpost(): if request.method == 'POST': db_session = session() title = request.form['title'] catagory = request.form['catagory'] auther = request.form['auther'] content = request.form['content'] entry = Blog(title=title, catagory=catagory, auther=auther, content=content) db_session.add(entry) db_session.commit() return redirect(url_for('index'))
def post(self): file1 = self.request.files['file'][0] original_fname = file1['filename'] user=self.get_argument("user")#nombre de usuario user_id=self.get_argument("user_id")#id de usuario die=self.get_argument("datepicker")#fecha de expiracion output_file = open("uploads/"+user+"/" + original_fname, 'wb') output_file.write(file1['body']) #bbdd _file=File(name=original_fname,user_id=int(user_id),expiration=die) s=session() s.add(_file) s.commit() s.close() self.finish("file " + original_fname + " is uploaded")
def add_label(): # 1. Получить значения параметров label и id из GET-запроса # 2. Получить запись из БД с соответствующим id (такая запись только одна!) # 3. Изменить значение метки записи на значение label # 4. Сохранить результат в БД our_label = request.query.label our_id = request.query.id s = session() our_news = s.query(News).filter( News.id == our_id).one() # т. о. это объект класса News our_news.label = our_label # обновление записи (не факт, что работает) s.commit() redirect('/news')
def get(self, name): if not name: self.write('No params to read') else: path = name.split('/') if (len(path) == 2): user = name.split('/')[0] arch = name.split('/')[1] s = session() q1 = s.query(User).filter(User.name == user) if (q1.count() == 1): q2 = s.query(File).filter(File.user_id == q1[0].id, File.name == arch) if (q2.count() > 0): if (q2[0].expiration > datetime.date.today()): _file_dir = os.path.abspath( "") + "/uploads/" + user _file_path = "%s/%s" % (_file_dir, arch) if not arch or not os.path.exists(_file_path): raise httpclient.HTTPError(404) self.set_header('Content-Type', 'application/force-download') self.set_header('Content-Disposition', 'attachment; filename=%s' % arch) with open(_file_path, "rb") as f: try: while True: _buffer = f.read(4096) if _buffer: self.write(_buffer) else: f.close() self.finish() return except: raise httpclient.HTTPError(404) raise httpclient.HTTPError(500) else: self.write('expired link') else: self.write('invalid file') else: self.write('invalid user') else: self.write('invalids params')
def get(self,name): if not name: self.write('No params to read') else: path=name.split('/') if(len(path) == 2): user = name.split('/')[0] arch = name.split('/')[1] s=session() q1=s.query(User).filter(User.name==user) if(q1.count()==1): q2=s.query(File).filter(File.user_id==q1[0].id,File.name==arch) if(q2.count() > 0): if(q2[0].expiration > datetime.date.today()): _file_dir = os.path.abspath("")+"/uploads/"+user _file_path = "%s/%s" % (_file_dir, arch) if not arch or not os.path.exists(_file_path): raise httpclient.HTTPError(404) self.set_header('Content-Type', 'application/force-download') self.set_header('Content-Disposition', 'attachment; filename=%s' % arch) with open(_file_path, "rb") as f: try: while True: _buffer = f.read(4096) if _buffer: self.write(_buffer) else: f.close() self.finish() return except: raise httpclient.HTTPError(404) raise httpclient.HTTPError(500) else: self.write('expired link') else: self.write('invalid file') else: self.write('invalid user') else: self.write('invalids params')
def add_report(category, poster_id, offender_id, content, timestamp, offending_messages): s = db.session() report2add = db.Report(category=category, poster_id=poster_id, offender_id=offender_id, status=0, content=content, timestamp=timestamp) s.add(report2add) s.flush() report_id = report2add.id refrences = [] for msg in offending_messages: refrences.append( db.Reference(message_id=msg.id, report_id=report2add.id)) s.add_all(refrences) s.commit() s.close() return report_id
async def render_to_server(self): """ Checks if the report has its own channel, if not it creates one Will populate the channel with the initial report info will return channel ID on success 0 otherwise. Will also open a session with the reportMgr """ server = self.bot.get_guild(CONFIG.server) s = db.session() report = s.query(db.Report).filter(db.Report.id == self.report.id).first() if not report: return 0 channel = None report_has_channel = False if report.channel: for c in server.channels: if c.id == self.report.channel: channel = c report_has_channel = True if not report_has_channel: for c in server.channels: if c.id == CONFIG.reports_category: channel = await server.create_text_channel("report_" + str(self.report_id), category=c) report.channel = channel.id print("changing report(" + str(report.id) + ") channel to " + str(channel.id)) s.commit() print(report.channel) s.flush() break s.close() if not report_has_channel: await self.render(channel, 10, show_all=True) return channel.id
#este script solo corre por linea de comandos import os from getpass import getpass from database import User,File,session user_name = raw_input('ingrese el nombre de usuario ') user_pass = getpass('ingrese la clave de usuario ') confirm = raw_input('confirma creacion?(s/n) ') if confirm == 's' : #creacion del usuario try: s=session() result=s.query(User).filter(User.name==user_name) if result.count() >0: print 'este usuario ya fue creado :(' else : d=User(name=user_name,passw=user_pass) s.add(d) s.commit() print('usuario creado con exito') except Exception as e: print(e) #creacion de su carpeta de uploads try: directorio='uploads/'+user_name if os.path.exists(os.path.join(os.getcwd(),directorio)): print ' el directorio ya existe' else: os.system('mkdir uploads/'+user_name) print('directorio creado con exito') except Exception as e:
def find_locations(self): closures = database.session().query(Closure).all() for closure in closures: locations = self.find_location(closure.location) self.geolocate(locations)
async def report(self, ctx): """->Submits a report to the admins""" reporter = ctx.message.author if reporter in self.active_report_sessions: return self.active_report_sessions.append(reporter) server = self.bot.get_guild(CONFIG.server) guild = self.bot.get_guild(CONFIG.server) def check(m): if isinstance(m.channel, discord.DMChannel): return m.author == reporter if not isinstance(ctx.message.channel, discord.DMChannel): await ctx.message.delete() while True: offender = None selected_category = None report_text = "" member_name = "" dm = await ctx.message.author.send( "Please select one of the following categories.\n" "```Admin Abuse\n" "Dispute between users\n" "Spam\n" "Bot abuse\n" "Harassment\n" "Server Issue\n" "Server Suggestion\n" "User Issue\n" "Other```") msg = await self.bot.wait_for('message', timeout=120, check=check) while msg.content.lower() not in self.category_list: await ctx.message.author.send( "Invalid category please try again.") msg = await self.bot.wait_for('message', timeout=120, check=check) selected_category = self.category_list.index(msg.content.lower()) await ctx.message.author.send("Was there an offender?(y/n)") while True: msg = await self.bot.wait_for('message', timeout=120, check=check) if 'y' in msg.content.lower(): await ctx.message.author.send("Please copy their name.") count = 0 membernames = [] while True: msg = await self.bot.wait_for('message', timeout=120, check=check) for m in guild.members: nick = "" if m.nick: nick = m.nick if msg.content in m.name or msg.content in nick: offender = m count += 1 membernames.append([m.name, nick]) if offender == None: await ctx.message.author.send("No member found") elif count > 1: await ctx.message.author.send( "Multiple members found") for names in membernames: await ctx.message.author.send(names[0] + ", nickname: " + names[1]) await ctx.message.author.send( "Please copy one of the users above") count = 0 membernames = [] offender = None else: if offender.nick: await ctx.message.author.send("Using user:"******", nick:" + offender.nick) else: await ctx.message.author.send("Using user:"******"Please say yes or no") if offender != None: break await ctx.message.author.send( "Please describe the issue.\n" "You can use as many messages as you need\n" "You can post screenshots here, but try not to.\n" "You will be able to paste messages for evidence in the next step\n" "say \"done\" when you are done. You can say cancel to exit the report" ) report_content = "" while True: msg = await self.bot.wait_for('message', timeout=120, check=check) if (await is_cancel(msg)): self.active_report_sessions.remove(ctx.message.author) return if msg.content.lower() == "done": break else: report_content += msg.content + "\n" offending_msgs = [] if offender != None: await ctx.message.author.send( "Please copy any relevant messages from the offender.\n" "If there were no offending messages please say \"done\"" "If the messages were deleted, just paste any messages that occured on" "the same channel above or below the offending messages" "say \"done\" when you are done, you can say cancel to exit the report" ) while True: can_use_msg = False msg = await self.bot.wait_for('message', timeout=120, check=check) if (await is_cancel(msg)): self.active_report_sessions.remove(ctx.message.author) return if msg.content.lower() == "done": break else: s = db.session() results = s.query(db.Message).filter( db.Message.content.ilike("%" + msg.content + "%")) result_canidates = [] s.close() member = self.bot.get_member(msg.author.id) if results.count(): if results.count() > 1: num_groups = 0 result_groups = dbutil.group_message_results( results) if len(result_groups) == 1: for m in result_groups[0]: arr1 = [] for mm in m: if self.bot.check_channel_exists( mm.channel): can_use_msg = True channel = await self.bot.fetch_channel( mm.channel) if channel.permissions_for( member).read_messages: arr1.append(mm) if len(arr1): can_use_msg = True offending_msgs.append(arr1) else: await ctx.message.author.send( "I found multiple messages which match that content." ) for group in result_groups: author = await self.bot.fetch_user( group[0][0].author) if self.bot.check_channel_exists( group[0][0].channel): channel = await self.bot.fetch_channel( group[0][0].channel) if channel and channel.permissions_for( member).read_messages: output = author.name + " at #" + channel.name + "```" for m in group: num_groups += 1 result_canidates.append(m) output += "|" + str(num_groups) + "| " + str( len(m)) + " instance(s) of " + \ m[ 0].content[ :75] + " at " + str( m[0].timestamp) + "\n" output += "```" await ctx.message.author.send( output) await ctx.message.author.send( "Please select the number that corresponds to the instance" ) while True: print(len(result_canidates), num_groups) msg = await self.bot.wait_for( 'message', timeout=120, check=check) if msg.content.isdigit() and 0 < int( msg.content) <= len( result_canidates): offending_msgs.append( result_canidates[ int(msg.content) - 1]) can_use_msg = True break else: await ctx.message.author.send( "Invalid choice") elif results.count() == 0: ctx.message.author.send("No results found") else: can_use_msg = True for r in results: offending_msgs.append([r]) await ctx.message.author.send( "Type 'done' or if you wish to add more messages copy them here" ) if can_use_msg: await msg.add_reaction("✔") else: await ctx.message.author.send( "Could not find message in server") else: await ctx.message.author.send( "Could not find message in server") await ctx.message.author.send("Please confirm") report_msg = "" if offender != None: report_msg += "**Offender**: " + offender.name + "\n" report_msg += "**Category**:" + self.category_list[ selected_category] + "\n" if len(report_content): report_msg += "```" + report_content + "```" report_msg += "**Evidence**:" await ctx.message.author.send(report_msg) await msgutil.print_message_groups(offending_msgs, ctx.message.author, self.bot, padding=3) await ctx.message.author.send("Is this information correct? (y/n)") msg = await self.bot.wait_for('message', timeout=120, check=check) if 'y' in msg.content.lower(): break await ctx.message.author.send("sending report") report_id = 0 if offender == None: report_id = dbutil.add_report(selected_category, ctx.message.author.id, 0, report_content, msg.created_at, []) else: final_msg_id_list = [] final_offending_msg_list = [] for g in offending_msgs: for m in g: if m.id not in final_msg_id_list: final_offending_msg_list.append(m) final_msg_id_list.append(m.id) report_id = dbutil.add_report(selected_category, ctx.message.author.id, offender.id, report_content, msg.created_at, final_offending_msg_list) await ctx.message.author.send("Your report ``" + str(report_id) + "`` Has been submitted!") await ctx.message.author.send("You can use ``" + CONFIG.prefix + "view " + str(report_id) + "`` to view the status of the report") await ctx.message.author.send( "You can use ``" + CONFIG.prefix + "myreports`` to view all the reports you have submitted") self.active_report_sessions.remove(ctx.message.author) new_report = Report(self.bot, report_id) await new_report.render_to_server()
__tablename__ = "post" id = Column('id', Integer, primary_key=True) title = Column('title', String(100), nullable=False) date_posted = Column('date', DateTime, nullable=False, default=datetime.utcnow()) content = Column('content', Text, nullable=False) user_id = Column(Integer, ForeignKey('user.id'), nullable=False) def __repr__(self): return f"Post('{self.title}','{self.date_posted}')" Base.metadata.create_all(bind=engine) usersession = session() # user = User() # user.id = 2 # user.username = '******' # # usersession.add(user) # usersession.commit() # user = usersession.query(User).get(1) user.username = '******' post1 = Post() post1.id = 1 post1.content = 'Test content 1' post1.title = 'Test title 1'
def get_message_attachments(msg): s = db.session() results = s.execute("SELECT * FROM message_attachment WHERE message_id=" + str(msg.id)) s.close() return results
def post(post_id): db_session = session() entry = db_session.query(Blog).filter(Blog.id == post_id).one() return render_template('post.html', entry=entry)
def news_list(): s = session() rows = s.query(News).filter(News.label == None).all() return template('news_template', rows=rows)