Пример #1
0
def comment_create():
    data = request.get_json()
    article = g.article
    
    form = CommentForm(**data)
    if form.validate():
        form_data = form.data
        form_data['user'] = g.user
        form_data['ip'] = request.remote_addr

        try:
            comment = article.create_comment(**form_data)
            article.update_comment_count()
            article.update_user_comment_count(user_id=comment.user_id)

            db_session.commit()

            cache.update_article(article.id, article)
            cache.update_sorted_articles(article, 'comment_count')
            return jsonify({"data": comment.json_data()})
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
Пример #2
0
 def handleUpdateProjectDataRecord(self):
     '''
     更新研究项目中的一行数据
     :return:
     '''
     _data_dict = self.postParams("*")
     if "pid" in _data_dict and "row_id" in _data_dict:
         try:
             project_id = int(_data_dict.get("pid", 0))
             row_id = _data_dict.get("row_id", '')
         except Exception:
             project_id = 0
         if project_id > 0 and '' != row_id:
             try:
                 db_session.query(ProjectItem).filter(ProjectItem.proj_id==project_id).filter(ProjectItem.row_id==row_id).delete()
                 for _d in _data_dict:
                     if "pid" != _d and "row_id" != _d:
                         pproperty_item = db_session.query(ProjectProperty).filter(ProjectProperty.label==_d).first()
                         if pproperty_item is not None:
                             p_item = ProjectItem()
                             p_item.label = _d
                             p_item.value = _data_dict[_d]
                             p_item.row_id = row_id
                             p_item.proj_id = project_id
                             p_item.p_id = pproperty_item.id
                             db_session.add(p_item)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
     else:
         self.setFailureReason('缺少关键参数!')
Пример #3
0
def comment_create():
    data = request.get_json()
    topic = g.topic

    form = CommentForm(**data)
    if form.validate():
        form_data = form.data
        form_data['user'] = g.user
        form_data['ip'] = request.remote_addr

        try:
            comment = topic.create_comment(**form_data)
            topic.update_comment_count()
            topic.update_user_comment_count(user_id=comment.user_id)

            db_session.commit()

            cache.update_topic(topic.id, topic)
            cache.update_sorted_topics(topic, 'comment_count')
            return jsonify({"data": comment.json_data()})
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
Пример #4
0
 def handleAddProjectDataRecord(self):
     _data_dict = self.postParams("*")
     if "pid" in _data_dict:
         try:
             project_id = int(_data_dict.get('pid'))
         except Exception as e:
             project_id = 0
         if project_id > 0:
             row_num = str(uuid1())
             try:
                 for _d in _data_dict:
                     if "pid" != _d:
                         pproperty_item = db_session.query(ProjectProperty).\
                             filter(ProjectProperty.label==_d).\
                             filter(ProjectProperty.p_id==project_id).first()
                         if pproperty_item is not None:
                             p_item = ProjectItem()
                             p_item.label = _d
                             p_item.value = _data_dict[_d]
                             p_item.row_id = row_num
                             p_item.proj_id = project_id
                             p_item.p_id = pproperty_item.id
                             db_session.add(p_item)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
Пример #5
0
    async def add_filament(self, ctx: Context, *args: clean_content):
        # Check we have the bare minumum number of args
        if len(args) < 2:
            await ctx.send(
                "I need at least a filament name in quotes and the associated print profile."
            )
            return

        # Make sure there are the right number of args for each input type
        if len(args) < 3 and not ctx.message.attachments:
            await ctx.send(
                "Please provide an image of the filament by an image link or attachment"
            )

        # Do a quick check the folder(s) exist and make them if not
        self.print_images_dir.mkdir(parents=True, exist_ok=True)

        filament_name, filament_profile = args[:2]
        # Verify that the filament type is an expected type
        if not FilamentType.verify_type(str(filament_profile)):
            await ctx.send(
                f'Print profile "{filament_profile}" is not a valid profile. Currently accepted profiles are: `filamentum`, `prusament`.'
            )

        image_file = Path(self.print_images_dir,
                          get_valid_filename(filament_name))

        # Get the image and save it to the filesystem
        if ctx.message.attachments:
            # Take the first attachment and save it
            image_attachment = ctx.message.attachments[0]
            filename = str(image_file) + "." + image_attachment.filename.split(
                ".")[-1]
            await image_attachment.save(filename)
        else:
            image_url = args[2]
            filename = str(image_file) + "." + str(image_url).split(".")[-1]
            # Save the file to disk
            r = requests.get(image_url, stream=True)
            if r.status_code == 200:
                with open(filename, "wb") as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw, f)

        # Save the model to the database
        filament = FilamentType(
            name=str(filament_name),
            profile=str(filament_profile).casefold(),
            image_path=str(image_file),
        )
        db_session.add(filament)
        try:
            db_session.commit()
            await ctx.send(
                f'"{filament_name}" added to the available filament list!')
        except (ScalarListException, SQLAlchemyError) as e:
            db_session.rollback()
            logging.exception(e)
            await ctx.send(
                f'Could not add "{filament_name}" due to an internal error.')
Пример #6
0
    def insert_data(self, data):
        """
        Will handle inserting data into the database
        """
        try:
            # Check if book is in database, if so update else create
            try:
                book = db_session.query(Book).filter(Book.book_id == data.get('book_id')).one()
            except NoResultFound:
                book = Book()

            book.title = data.get('title')
            book.subtitle = data.get('subtitle')
            book.author = data.get('author')
            book.year = data.get('year')
            book.pages = data.get('pages')
            book.language = data.get('language')
            book.publisher = data.get('publisher')
            book.isbn = data.get('isbn')
            book.format = data.get('format')
            book.description = data.get('description')
            book.file_source = data.get('file_source')
            book.file_cover_source = data.get('file_cover_source')
            book.file_location = data.get('file_location')
            book.file_cover_location = data.get('file_cover_location')
            book.book_id = data.get('book_id')
            book.time_collected = data.get('time_collected')

            db_session.add(book)
            db_session.commit()
            # self.track_stat('rows_added_to_db', rows_affected)

        except Exception:
            db_session.rollback()
            logger.exception("Error adding to db {data}".format(data=data))
Пример #7
0
    def send(self):
        """
        发送邮件
        :return:
        """
        ret_oper = False
        recvers = ";".join(self.mailto_list)
        try:
            smtp_server = smtplib.SMTP()
            smtp_server.connect(self.smtp_host, self.smtp_port)
            smtp_server.login(self.smtp_user, self.smtp_pwd)
            msg = MIMEText(self.content, "html", "utf-8")
            msg['Subject'] = self.subject
            msg['From'] = MAIL_SENDER
            msg['To'] = recvers
            smtp_server.sendmail(self.sender, recvers, msg.as_string())
            ret_oper = True
        except Exception as e:
            pass
        finally:
            try:
                mail_log = EmailLog()
                mail_log.recver = ";".join(self.mailto_list)
                mail_log.subject = self.subject
                mail_log.content = self.content
                mail_log.status = EmailLog.STATUS_SEND_SUCCESS if ret_oper else EmailLog.STATUS_SEND_FAILURE
                db_session.add(mail_log)
                db_session.commit()
            except Exception as e:
                db_session.rollback()
            smtp_server.quit()

        return ret_oper
Пример #8
0
 def handleRegister(self):
     """
     处理用户注册
     :return:
     """
     name, email, pwd = self.postParams('name', 'email', 'pwd')
     if self.checkParamsAvailable(email, pwd):
         exists_query = db_session.query(User).filter(User.email==email).exists()
         if not db_session.query(exists_query).scalar():
             try:
                 set_user = User()
                 set_user.name = name
                 set_user.email = email
                 set_user.salt = User.genSalt()
                 set_user.pwd = User.genPassword(pwd, set_user.salt)
                 set_user.reg_ip = str(request.remote_addr)
                 db_session.add(set_user)
                 db_session.commit()
                 self.changeResponse2Success()
                 mailer = getMailSender()
                 mailer.setMailtoList([email])
                 mailer.setSubject("感谢注册 [史前-在线定量研究工具]")
                 _mail_content = render_template("noticer/email/_register.html", nickname=name)
                 mailer.setContent(_mail_content)
                 mailer.send()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("该邮箱已经被注册,请更换邮箱申请或尝试找回密码!")
Пример #9
0
    async def add(self, ctx: Context, item: str):
        author_id = (
            db_session.query(User)
            .filter(User.user_uid == ctx.message.author.id)
            .first()
            .id
        )

        if (
            not db_session.query(BlockedKarma)
            .filter(BlockedKarma.topic == item.casefold())
            .all()
        ):
            blacklist = BlockedKarma(topic=item.casefold(), user_id=author_id)
            db_session.add(blacklist)
            try:
                db_session.commit()
                await ctx.send(f"Added {item} to the karma blacklist. :pencil:")
            except (ScalarListException, SQLAlchemyError):
                db_session.rollback()
                await ctx.send(
                    f"Something went wrong adding {item} to the karma blacklist. No change has occurred"
                )
        else:
            await ctx.send(
                f"{item} is already in the karma blacklist. :page_with_curl:"
            )
Пример #10
0
def getById(type, id):
    try:
        o = db_session.query(type).filter_by(id=object.id)
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Пример #11
0
    def insert_data(self, data):
        """
        Will handle inserting data into the database
        """
        try:
            db_session = DBSession()
            # Check if comic is in database, if so update else create
            try:
                comic = db_session.query(Comic).filter(
                    Comic.comic_id == data.get('comic_id')).one()
            except NoResultFound:
                comic = Comic()

            comic.title = data.get('title')
            comic.alt = data.get('alt')
            comic.comic_id = data.get('comic_id')
            comic.source_file_location = data.get('source_file_location')
            comic.saved_file_location = data.get('saved_file_location')
            comic.posted_at = data.get('posted_at')
            comic.raw_json = data.get('raw_json')
            comic.time_collected = data.get('time_collected')
            comic.transcript = data.get('transcript')

            db_session.add(comic)
            db_session.commit()
            # self.track_stat('rows_added_to_db', rows_affected)

        except Exception:
            db_session.rollback()
            logger.exception("Error adding to db {data}".format(data=data))
Пример #12
0
    def insert_data(self, data):
        """
        Will handle inserting data into the database
        """
        try:
            db_session = DBSession()
            # Check if whatif is in database, if so update else create
            try:
                whatif = db_session.query(Whatif).filter(Whatif.whatif_id == data.get('whatif_id')).one()
            except NoResultFound:
                whatif = Whatif()

            whatif.title = data.get('title')
            whatif.question = data.get('question')
            whatif.whatif_id = data.get('whatif_id')
            whatif.saved_file_location = data.get('saved_file_location')
            whatif.posted_at = data.get('posted_at')
            whatif.time_collected = data.get('time_collected')

            db_session.add(whatif)
            db_session.commit()

        except Exception:
            db_session.rollback()
            logger.exception("Error adding to db {data}".format(data=data))
Пример #13
0
def vote():
    topic = g.topic
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = topic.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = topic.update_points(up=up, points=2)
                topic.user.update_points(up=up, points=6)
            else:
                points = topic.points
        else:
            # this is a new vote
            points = topic.update_points(up)
            user_points = 1
            if up:
                user_points = 5
            topic.user.update_points(up=up, points=user_points)
        
        db_session.commit()
        data = {
            "points": points
        }

        cache.update_topic(topic.id, topic)
        cache.update_sorted_topics(topic, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
Пример #14
0
def vote():
    article = g.article
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = article.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = article.update_points(up=up, points=2)
                article.user.update_points(up=up, points=11)
            else:
                points = article.points
        else:
            # this is a new vote
            points = article.update_points(up)
            user_points = 1
            if up:
                user_points = 10
            article.user.update_points(up=up, points=user_points)
        
        db_session.commit()
        data = {
            "points": points
        }

        cache.update_article(article.id, article)
        cache.update_sorted_articles(article, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
Пример #15
0
def vote():
    topic = g.topic
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = topic.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = topic.update_points(up=up, points=2)
                topic.user.update_points(up=up, points=6)
            else:
                points = topic.points
        else:
            # this is a new vote
            points = topic.update_points(up)
            user_points = 1
            if up:
                user_points = 5
            topic.user.update_points(up=up, points=user_points)

        db_session.commit()
        data = {"points": points}

        cache.update_topic(topic.id, topic)
        cache.update_sorted_topics(topic, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
Пример #16
0
    def insert_data(self, data):
        """
        Will handle inserting data into the database
        """
        try:
            db_session = DBSession()
            # Check if comic is in database, if so update else create
            try:
                comic = db_session.query(Comic).filter(
                    Comic.comic_id == data.get('comic_id')).one()
            except NoResultFound:
                comic = Comic()

            comic.title = data.get('title')
            comic.comic_id = data.get('id')
            comic.alt = data.get('alt')
            comic.file_path = data.get('file_path')
            comic.posted_at = data.get('posted_at')
            comic.time_collected = data.get('time_collected')

            db_session.add(comic)
            db_session.commit()

        except Exception:
            db_session.rollback()
            logger.exception("Error adding to db {data}".format(data=data))
Пример #17
0
def create():
    data = request.get_json()
    
    form = TopicForm(**data)
    if form.validate():
        form_data = form.data
        form_data['ip'] = request.remote_addr

        try:
            topic = g.user.create_topic(**form_data)
            alert = dict(
                type='success',
                messages=_("Your topic has been created successfully. You will be redirected to it shortly")
            )

            redirect = topic.get_url('view')
            cache.update_sorted_topics(topic, 'date_created')
            return jsonify({"data": topic.json_data(), "alert": alert, "redirect": redirect})
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
Пример #18
0
async def on_message(message: Message):
    # If the message is by a bot thats not irc then ignore it
    if message.author.bot and message.author.id != CONFIG[
            "UWCS_DISCORD_BRIDGE_BOT_ID"]:
        return

    user = db_session.query(User).filter(
        User.user_uid == message.author.id).first()
    if not user:
        user = User(user_uid=message.author.id, username=str(message.author))
        db_session.add(user)
    else:
        user.last_seen = message.created_at
    # Commit the session so the user is available now
    try:
        db_session.commit()
    except (ScalarListException, SQLAlchemyError):
        db_session.rollback()
        # Something very wrong, but not way to reliably recover so abort
        return

    # Only log messages that were in a public channel
    if isinstance(message.channel, GuildChannel):
        # Log the message to the database
        logged_message = LoggedMessage(
            message_uid=message.id,
            message_content=message.clean_content,
            author=user.id,
            created_at=message.created_at,
            channel_name=message.channel.name,
        )
        db_session.add(logged_message)
        try:
            db_session.commit()
        except (ScalarListException, SQLAlchemyError):
            db_session.rollback()
            return

        # Get all specified command prefixes for the bot
        command_prefixes = bot.command_prefix(bot, message)
        # Only process karma if the message was not a command (ie did not start with a command prefix)
        if True not in [
                message.content.startswith(prefix)
                for prefix in command_prefixes
        ]:
            reply = process_karma(message, logged_message.id, db_session,
                                  CONFIG["KARMA_TIMEOUT"])
            if reply:
                await message.channel.send(reply)

    # allow irc users to use commands by altering content to remove the nick before sending for command processing
    # note that clean_content is *not* altered and everything relies on this fact for it to work without having to go back and lookup the message in the db
    # if message.content.startswith("**<"): <-- FOR TESTING
    if message.author.id == CONFIG["UWCS_DISCORD_BRIDGE_BOT_ID"]:
        # Search for first "> " and strip the message from there (Since irc nicks cant have <, > in them
        idx = message.content.find(">** ")
        idx += 4
        message.content = message.content[idx:]

    await bot.process_commands(message)
Пример #19
0
def create():
    data = request.get_json()

    form = TopicForm(**data)
    if form.validate():
        form_data = form.data
        form_data['ip'] = request.remote_addr

        try:
            topic = g.user.create_topic(**form_data)
            alert = dict(
                type='success',
                messages=
                _("Your topic has been created successfully. You will be redirected to it shortly"
                  ))

            redirect = topic.get_url('view')
            cache.update_sorted_topics(topic, 'date_created')
            return jsonify({
                "data": topic.json_data(),
                "alert": alert,
                "redirect": redirect
            })
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
Пример #20
0
def vote():
    article = g.article
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = article.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = article.update_points(up=up, points=2)
                article.user.update_points(up=up, points=11)
            else:
                points = article.points
        else:
            # this is a new vote
            points = article.update_points(up)
            user_points = 1
            if up:
                user_points = 10
            article.user.update_points(up=up, points=user_points)

        db_session.commit()
        data = {"points": points}

        cache.update_article(article.id, article)
        cache.update_sorted_articles(article, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
Пример #21
0
 def handleAddGeoUnit(self):
     """
     处理往地理坐标集合上添加坐标点的工作
     :return:
     """
     gid, geo_name, longitude, latitude, desc, area, high, map_type = \
         self.postParams("gid", "geo_name", "longitude", "latitude", "desc", "area", "high", "map_type")
     if self.checkParamsAvailable(gid, geo_name, longitude, latitude, desc, area, high, map_type):
         try:
             current_user = UserIdentify.getCurrentUser()
             geo_unit = GeoPointUnit()
             geo_unit.group_id = gid
             geo_unit.name = geo_name
             geo_unit.longitude = longitude
             geo_unit.latitude = latitude
             geo_unit.desc = desc
             geo_unit.map_type = map_type
             if str(high).isdigit():
                 geo_unit.high = high
             else:
                 geo_unit.high = 0
             if str(area).isdigit():
                 geo_unit.area = area
             else:
                 geo_unit.area = 0
             geo_unit.u_id = current_user.get('uid', 0)
             db_session.add(geo_unit)
             db_session.commit()
             self.changeResponse2Success()
         except Exception as e:
             db_session.rollback()
             self.setFailureReason(str(e))
Пример #22
0
def deleteById(object, item_id):
    try:
        db_session.query(type(object)).filter_by(id=item_id).delete()
        db_session.commit()
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Пример #23
0
def add(object):
    try:
        db_session.add(object)
        db_session.commit()
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Пример #24
0
def update(object):
    try:
        objToUpdate = db_session.query(type(object)).filter_by(id=object.id)
        objToUpdate.update(object.toMappedValues())
        db_session.commit()
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Пример #25
0
    async def channel_ignore(self,
                             ctx: Context,
                             channel: TextChannel,
                             mode: ChannelIgnoreMode.get = None):
        ignored_channel = (db_session.query(IgnoredChannel).filter(
            IgnoredChannel.channel == channel.id).first())

        if mode == ChannelIgnoreMode.Ignore:
            if ignored_channel is None:
                # Create a new entry
                user = (db_session.query(User).filter(
                    User.user_uid == ctx.author.id).first())
                new_ignored_channel = IgnoredChannel(
                    channel=channel.id,
                    user_id=user.id,
                )
                db_session.add(new_ignored_channel)
                try:
                    db_session.commit()
                    await ctx.send(
                        f"Added {channel.mention} to the ignored list.")
                except SQLAlchemyError as e:
                    db_session.rollback()
                    logging.error(e)
                    await ctx.send(
                        "Something went wrong. No change has occurred.")
            else:
                # Entry already present
                await ctx.send(f"{channel.mention} is already ignored!")
        elif mode == ChannelIgnoreMode.Watch:
            if ignored_channel is not None:
                # Remove the entry
                db_session.query(IgnoredChannel).filter(
                    IgnoredChannel.channel == channel.id).delete()
                try:
                    db_session.commit()
                    await ctx.send(
                        f"{channel.mention} is no longer being ignored.")
                except SQLAlchemyError as e:
                    db_session.rollback()
                    logging.error(e)
                    await ctx.send(
                        "Something went wrong. No change has occurred.")
            else:
                # The entry is not present
                await ctx.send(
                    f"{channel.mention} is not currently being ignored.")

        else:
            # Report status
            if ignored_channel is not None:
                await ctx.send(f"{channel.mention} is currently being ignored."
                               )
            else:
                await ctx.send(
                    f"{channel.mention} is not currently being ignored")
Пример #26
0
def db_add(location_id, location_name, lttd, lngt, owner_id, post_id, caption,
           picture, comments_count, likes_count):
    'Функция для добавления данных в БД'
    post = InstLocations(location_id, location_name, lttd, lngt, owner_id,
                         post_id, caption, picture, comments_count,
                         likes_count)
    try:
        db_session.add(post)
        db_session.commit()
    except (OperationalError, IntegrityError):
        db_session.rollback()
Пример #27
0
def before_request():
    if ACCESS_LOG_ON:
        user_identify = UserIdentify()
        try:
            access_log = AccessLog()
            access_log.ip = str(request.remote_addr)
            access_log.path = str(request.path)
            access_log.email = 'anonymous' if user_identify.is_Guest() else user_identify.email
            db_session.add(access_log)
            db_session.commit()
        except Exception as e:
            db_session.rollback()
Пример #28
0
    async def add(self, ctx: Context, *args: clean_content):
        if not args:
            await ctx.send("You're missing a time and a message!")
        else:
            trigger_time = parse_time(args[0])
            now = datetime.now()
            if not trigger_time:
                await ctx.send("Incorrect time format, please see help text.")
            elif trigger_time < now:
                await ctx.send("That time is in the past.")
            else:
                # HURRAY the time is valid and not in the past, add the reminder
                display_name = get_name_string(ctx.message)

                # set the id to a random value if the author was the bridge bot, since we wont be using it anyways
                # if ctx.message.clean_content.startswith("**<"): <---- FOR TESTING
                if user_is_irc_bot(ctx):
                    author_id = 1
                    irc_n = display_name
                else:
                    author_id = (
                        db_session.query(User)
                        .filter(User.user_uid == ctx.author.id)
                        .first()
                        .id
                    )
                    irc_n = None

                if len(args) > 1:
                    rem_content = " ".join(args[1:])
                    trig_at = trigger_time
                    trig = False
                    playback_ch_id = ctx.message.channel.id
                    new_reminder = Reminder(
                        user_id=author_id,
                        reminder_content=rem_content,
                        trigger_at=trig_at,
                        triggered=trig,
                        playback_channel_id=playback_ch_id,
                        irc_name=irc_n,
                    )
                    db_session.add(new_reminder)
                    try:
                        db_session.commit()
                        await ctx.send(
                            f"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {CONFIG.REMINDER_SEARCH_INTERVAL} seconds)."
                        )
                    except (ScalarListException, SQLAlchemyError) as e:
                        db_session.rollback()
                        logging.error(e)
                        await ctx.send(f"Something went wrong")
                else:
                    await ctx.send("Please include some reminder text!")
Пример #29
0
async def on_member_join(member: Member):
    # Add the user to our database if they've never joined before
    user = db_session.query(User).filter(User.user_uid == member.id).first()
    if not user:
        user = User(user_uid=member.id, username=str(member))
        db_session.add(user)
    else:
        user.last_seen = datetime.utcnow()
    try:
        db_session.commit()
    except (ScalarListException, SQLAlchemyError):
        db_session.rollback()
Пример #30
0
    async def on_message(self, message: Message):
        # If the message is by a bot that's not irc then ignore it
        if message.author.bot and not user_is_irc_bot(message):
            return

        user = (db_session.query(User).filter(
            User.user_uid == message.author.id).one_or_none())
        if not user:
            user = User(user_uid=message.author.id,
                        username=str(message.author))
            db_session.add(user)
        else:
            user.last_seen = message.created_at
        # Commit the session so the user is available now
        try:
            db_session.commit()
        except (ScalarListException, SQLAlchemyError) as e:
            db_session.rollback()
            logging.error(e)
            # Something very wrong, but not way to reliably recover so abort
            return

        # Only log messages that were in a public channel
        if isinstance(message.channel, GuildChannel):
            # Log the message to the database
            logged_message = LoggedMessage(
                message_uid=message.id,
                message_content=message.clean_content,
                author=user.id,
                created_at=message.created_at,
                channel_name=message.channel.name,
            )
            db_session.add(logged_message)
            try:
                db_session.commit()
            except (ScalarListException, SQLAlchemyError) as e:
                db_session.rollback()
                logging.error(e)
                return

            # KARMA

            # Get all specified command prefixes for the bot
            command_prefixes = self.bot.command_prefix(self.bot, message)
            # Only process karma if the message was not a command (ie did not start with a command prefix)
            if not any(
                    message.content.startswith(prefix)
                    for prefix in command_prefixes):
                reply = process_karma(message, logged_message.id, db_session,
                                      CONFIG.KARMA_TIMEOUT)
                if reply:
                    await message.channel.send(reply)
Пример #31
0
    async def on_message_delete(self, message: Message):
        # Get the message from the database
        db_message = (db_session.query(LoggedMessage).filter(
            LoggedMessage.message_uid == message.id).one_or_none())

        # Can't really do anything if the message isn't in the logs so only handle when it is
        if db_message:
            # Update the message deleted_at and commit the changes made
            db_message.deleted_at = datetime.utcnow()
            try:
                db_session.commit()
            except (ScalarListException, SQLAlchemyError):
                db_session.rollback()
Пример #32
0
 async def on_member_join(self, member: Member):
     """Add the user to our database if they've never joined before"""
     user = get_database_user(member)
     if not user:
         user = User(user_uid=member.id, username=str(member))
         db_session.add(user)
     else:
         user.last_seen = datetime.utcnow()
     try:
         db_session.commit()
     except (ScalarListException, SQLAlchemyError) as e:
         logging.exception(e)
         db_session.rollback()
Пример #33
0
 def handleDeleteProjectDataRecord(self):
     '''
     删除研究项目中的一行数据
     :return:
     '''
     pid, row_id = self.postParams("pid", "row_id")
     if self.checkParamsAvailable(pid, row_id):
         try:
             db_session.query(ProjectItem).filter(ProjectItem.proj_id==pid).filter(ProjectItem.row_id==row_id).delete()
             db_session.commit()
             self.changeResponse2Success()
         except Exception as e:
             db_session.rollback()
Пример #34
0
    async def channel_karma(self,
                            ctx: Context,
                            channel: TextChannel,
                            mode: MiniKarmaMode.get = None):
        # TODO: avoid writing duplicate code with above if possible?
        karma_channel = (db_session.query(MiniKarmaChannel).filter(
            MiniKarmaChannel.channel == channel.id).first())

        if mode == MiniKarmaMode.Mini:
            if karma_channel is None:
                user = (db_session.query(User).filter(
                    User.user_uid == ctx.author.id).first())
                new_karma_channel = MiniKarmaChannel(
                    channel=channel.id,
                    user_id=user.id,
                )
                db_session.add(new_karma_channel)
                try:
                    db_session.commit()
                    await ctx.send(
                        f"Added {channel.mention} to the mini-karma channels")
                except SQLAlchemyError as e:
                    db_session.rollback()
                    logging.error(e)
                    await ctx.send(
                        "Something went wrong. No change has occurred.")
            else:
                await ctx.send(
                    f"{channel.mention} is already on mini-karma mode!")
        elif mode == MiniKarmaMode.Normal:
            if karma_channel is not None:
                db_session.query(MiniKarmaChannel).filter(
                    MiniKarmaChannel.channel == channel.id).delete()
                try:
                    db_session.commit()
                    await ctx.send(
                        f"{channel.mention} is now on normal karma mode")
                except SQLAlchemyError as e:
                    db_session.rollback()
                    logging.error(e)
                    await ctx.send(
                        "Something went wrong. No change has occurred")
            else:
                await ctx.send(
                    f"{channel.mention} is already on normal karma mode!")
        else:
            if karma_channel is None:
                await ctx.send(f"{channel.mention} is on normal karma mode.")
            else:
                await ctx.send(f"{channel.mention} is on mini-karma mode.")
Пример #35
0
def admin_login():
    if request.method == 'POST':
        id = request.form['username']
        pw = request.form['password']
    
        db_session.rollback()
        check_user = db_session.query(User).filter(User.id == id).first()
        
        if check_password(check_user.password, pw):
            session['username'] = id
            return redirect(url_for('admin'))
            
    else:
        return "Admin Login Page"
        """return render_template('admin_login.html')"""
Пример #36
0
def admin_login():
    if request.method == 'POST':
        id = request.form['username']
        pw = request.form['password']

        db_session.rollback()
        check_user = db_session.query(User).filter(User.id == id).first()

        if check_password(check_user.password, pw):
            session['username'] = id
            return redirect(url_for('admin'))

    else:
        return "Admin Login Page"
        """return render_template('admin_login.html')"""
Пример #37
0
def user_db_add_user(chat_id, first_name=None, last_name=None, username=None):
    user = db_session.query(User).filter(User.user_id == chat_id).first()
    if user:  # если chat_id уже есть в БД - обновляет инфу
        user.username = username
        user.first_name = first_name
        user.last_name = last_name
    else:
        new_user = User(chat_id, first_name, last_name,
                        username)  # если chat_id нет в БД - добавляет
        db_session.add(new_user)
    try:
        db_session.commit()  # обновляет данные в БД
        return 'add_user: User created' if not user else 'add_user: User is exist, data have updated'
    except sqlalchemy.exc.IntegrityError:
        db_session.rollback()
        return 'add_user: Error'
Пример #38
0
 def mutate(self,info,id):
     local_id = from_global_id(id)[1]
     cart=db_session.query(CartModel).filter_by(id=local_id).scalar()
     in_cart = Counter([item.product for item in cart.items])
     insufficient_stock = []
     for prod in in_cart:
         new_inventory= prod.inventory_count - in_cart[prod]
         if new_inventory < 0:
             insufficient_stock.append(to_global_id("Product",prod.id))
         else:   
             db_session.query(ProductModel).filter_by(id=prod.id).update(dict(inventory_count=new_inventory))
     if insufficient_stock:
         db_session.rollback()
         return CartComplete(success=False,insufficient_stock=insufficient_stock)
     db_session.commit()
     return CartComplete(success=True)
Пример #39
0
 def handleDeletePropertyForProject(self):
     """
     删除指定的研究项目属性
     :return:
     """
     _id, = self.postParams("id")
     if self.checkParamsAvailable(_id):
         try:
             _del_property = db_session.query(ProjectProperty).filter(ProjectProperty.id==_id).first()
             if _del_property is not None:
                 db_session.query(ProjectItem.proj_id==_del_property.p_id).filter(ProjectItem.label==_del_property.label).delete()
                 db_session.delete(_del_property)
                 db_session.commit()
                 self.changeResponse2Success()
         except Exception as e:
             db_session.rollback()
             self.setFailureReason(str(e))
Пример #40
0
 def post(self):              
     form = AForm(self.request.arguments)        
     id = self.get_argument('id', None)
     
     try:
         f = self.request.files['image'][0]
         image = f['filename']
         extn = os.path.splitext(image)[1]
         if extn in ('.jpg','.png','.bmp','.jpeg'):
             name =str(int(random.random()*10000000000000))
             fh = open(__UPLOADS__ + name + extn, 'wb')
             fh.write(f['body'])
             image = name+extn
             
 
         else:
             self.finish('this is is not image file')
     except:
         image = self.get_argument('image', None)
     if form.validate():
         form.image.data = image 
         print(form.image.data )  
         if id:
             ar = Article.query.filter_by(id=id).one()
             if not ar: raise tornado.web.HTTPError(404)
             form.populate_obj(ar)                
             db_session.add(ar)
             db_session.commit()            
             self.redirect('/manage/articles')
         else:
             while True:
                 e = Article.query.filter_by(slug=form.data['slug']).first()
                 if not e: break
                 form.data['slug'] += "-2"
             ar = Article(1,2,34,12,12)
             form.populate_obj(ar)
             db_session.add(ar)
             try:
                 db_session.commit()
             except:
                 db_session.rollback()
         
             self.redirect('/manage/articles')                
     else:
         self.write('%s' %form.errors)
Пример #41
0
def delete_blog():
	title = request.form['title']
	print title
	delete_blog_post = db_session.query(Blog_Post).first()
	show = db_session.relationship('Show',
                           backref=db.backref('episodes', cascade="all, delete-orphan"),
                           lazy='joined')
	print delete_blog_post
	db_session.delete(delete_comments)
	db_session.delete(delete_blog_post)
	try:
		print "succsess"
		db_session.commit()
	except Exception as e:
		print "error"
		db_session.rollback()
		db_session.flush()
	return redirect(url_for('routes.add_blog'))
Пример #42
0
 def add_user(self, json):
   """
   たまひよ会員新規登録。
   名前の末尾のアンダースコアは取り除く。
   IRCの事情をケアする仕様。
   """
   args = loads(json)
   print args
   user = self._whoami(args["caller"], alias_contain=False)
   if (user is None) or (not user.admin):
     return dumps((False,))
   db_session.add(User(self._rstrip_underscore(args["newcomer"]), args["rate"]))
   try:
     db_session.commit()
   except IntegrityError:
     db_session.rollback()
     return dumps((False,))
   return dumps((True,))
Пример #43
0
 def iam(self, json): # Web版のみにしないとまずい気が
   """別名登録"""
   args = loads(json)
   print args
   user = self._whoami(args["alias"], alias_contain=False)
   if user is not None:
     return dumps((False,))
   user = self._whoami(args["original_name"], alias_contain=False)
   if user is None:
     return dumps((False,))
   db_session.add(UserAlias(args["alias"], user.id))
   try:
     db_session.flush()
   except IntegrityError:
     db_session.rollback()
     return dumps((False,))
   db_session.commit()
   return dumps((True,))
Пример #44
0
    async def on_member_join(self, member: Member):
        # Add the user to our database if they've never joined before
        user = db_session.query(User).filter(User.user_uid == member.id).first()
        if not user:
            user = User(user_uid=member.id, username=str(member))
            db_session.add(user)
        else:
            user.last_seen = datetime.utcnow()
        try:
            db_session.commit()
        except (ScalarListException, SQLAlchemyError):
            db_session.rollback()

        #  await member.send(WELCOME_MESSAGE.format(user_id=member.id))

        # Join message
        channel = self.bot.get_channel(CONFIG.UWCS_WELCOME_CHANNEL_ID)
        await channel.send(self.generate_welcome_message(member.display_name))
Пример #45
0
 async def remove(self, ctx: Context, item: str):
     if (not db_session.query(BlockedKarma).filter(
             BlockedKarma.topic == item.casefold()).all()):
         await ctx.send(
             f"{item} is not in the karma blacklist. :page_with_curl:")
     else:
         db_session.query(BlockedKarma).filter(
             BlockedKarma.topic == item.casefold()).delete()
         try:
             db_session.commit()
             await ctx.send(
                 f"{item} has been removed from the karma blacklist. :wastebasket:"
             )
         except (ScalarListException, SQLAlchemyError):
             db_session.rollback()
             await ctx.send(
                 f"Something went wrong removing {item} to the karma blacklist. No change has occurred"
             )
Пример #46
0
 async def on_message_edit(self, before: Message, after: Message):
     # Only care about messages that are in public channels
     if isinstance(before.channel, GuildChannel):
         # Message wasn't pinned
         if before.pinned == after.pinned:
             # Log any edits to messages
             original_message = (db_session.query(LoggedMessage).filter(
                 LoggedMessage.message_uid == before.id).first())
             if original_message:
                 message_diff = MessageDiff(
                     original_message=original_message.id,
                     new_content=after.clean_content,
                     created_at=(after.edited_at or datetime.utcnow()),
                 )
                 db_session.add(message_diff)
                 try:
                     db_session.commit()
                 except (ScalarListException, SQLAlchemyError):
                     db_session.rollback()
Пример #47
0
 def handleDeleteGeoPointUnit(self):
     """
     从坐标节点集中删除一个坐标节点
     :return:
     """
     gid, geopt = self.getParams("gid", "geopt")
     if self.checkParamsAvailable(gid, geopt):
         geo_unit = db_session.query(GeoPointUnit).filter(GeoPointUnit.group_id==gid).\
             filter(GeoPointUnit.id==geopt).first()
         if geo_unit is not None:
             try:
                 db_session.delete(geo_unit)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("地理兴趣点坐标未找到")
Пример #48
0
def answer_create():
    user = g.user
    question = g.question
    ip = request.remote_addr
    content = request.get_json().get('content')

    form = AnswerForm(content=content)
    if form.validate():
        form_data = form.data
        form_data['ip'] = ip
        form_data['user'] = user
        try:
            answer = question.create_answer(**form_data)
            question.update_answer_count()
            db_session.commit()
            return jsonify({"data": answer.json_data()})
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
Пример #49
0
def comment_delete():
    data = request.get_json()

    id = data.get('id')

    comment = Comment.find_by_pk(id)

    if comment:
        try:
            comment.article.update_comment_count(offset=-1)
            comment.article.update_user_comment_count(offset=-1, user_id=comment.user_id)
            comment.delete()
            db_session.commit()

            cache.update_article(comment.article.id, comment.article)
            cache.update_sorted_articles(comment.article, 'comment_count')
            return json_data(data)
        except Exception:
            db_session.rollback()
            return json_error_database()
    else:
        return json_error_invalid_request()
Пример #50
0
def create_db():
    #
    try:
        # load file into dictionary
        # data = open('example.log')

        line_re = re.compile(r'^([^\s]+)\s([^\s]+)\s([^\s]+)\s\[([^\]]+)\]\s\"(GET|POST)\s([^\s]+)\s([^\"]+)\"\s([^\s]+)\s([^\s]+)\s([^\s]+)\s\"([^\"]+)\"\s\"([^\"]+)\"\s\"([^\"]+)\"\s')
        target = os.path.join("/Users/seb/dev/jala/logs", "access_log.2015-11-25")
        # target = os.path.join("C:\\", "dev", "access_log.2015-11-27")
        with open(target) as f:
            for line in f:
                tokens = line_re.match(line)
                if tokens:
                    e = LogEntry(
                        sourceip=tokens.group(1),
                        request_id=tokens.group(2),
                        request_user=tokens.group(3),
                        timestamp=tokens.group(4),
                        request_type=tokens.group(5),
                        destination=tokens.group(6),
                        protocol=tokens.group(7),
                        return_code=tokens.group(8),
                        size=tokens.group(9),
                        duration=tokens.group(10),
                        referrer=tokens.group(11),
                        agent=tokens.group(12),
                        session=tokens.group(13)
                    )
                    db_session.add(e)
            #db_session.commit()

            db_session.commit()
    except Exception as ex:
        print(ex)
        db_session.rollback() #Rollback the changes on error
    finally:
        db_session.close() #Close the connection
Пример #51
0
 def addPorpertyForProject(self):
     """
     添加字段属性
     :return:
     """
     pid, name, label, _type, desc = self.postParams("pid", "name", "label", "type", "desc")
     if self.checkParamsAvailable(pid, name, label, _type, desc):
         project_exists = db_session.query(Project).filter(Project.id==pid).exists()
         if db_session.query(project_exists).scalar():
             try:
                 project_property = ProjectProperty()
                 project_property.name = name
                 project_property.label = label
                 project_property.type = _type
                 project_property.desc = desc
                 project_property.p_id = pid
                 db_session.add(project_property)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("父级实验项目不存在!")
Пример #52
0
 def handleCreateLaborary(self):
     """
     处理创建实验室功能
     :return:
     """
     name, unit, desc = self.postParams("name", "unit", "desc")
     if self.checkParamsAvailable(name):
         current_user = UserIdentify()
         same_name_item = db_session.query(Laborary).filter(Laborary.name==name).exists()
         if not db_session.query(same_name_item).scalar():
             try:
                 new_laborary = Laborary()
                 new_laborary.name = name
                 new_laborary.desc = desc
                 new_laborary.unit = unit
                 new_laborary.u_id = current_user.uid
                 db_session.add(new_laborary)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("已经存在同名的定量实验室!")
Пример #53
0
 def handleAddPropertyOption(self):
     """
     添加属性选项字段
     :return:
     """
     name, label, weight, opid = self.postParams("oname", "oid", "oweight", "opid")
     if self.checkParamsAvailable(name, label, opid):
         conflict_exists = db_session.query(PropertyOptions).filter(PropertyOptions.p_id==opid).\
             filter(or_(PropertyOptions.name==name, PropertyOptions.label==label)).exists()
         if not db_session.query(conflict_exists).scalar():
             try:
                 po = PropertyOptions()
                 po.name = name
                 po.label = label
                 po.weight = weight if weight is not None else 0
                 po.p_id = opid
                 db_session.add(po)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("选项名称或选项编号冲突!")
Пример #54
0
 def handleCreateProject(self):
     """
     创建指定实验室下的定量实验项目
     :return:
     """
     lid, pname, pdesc = self.postParams("lid", "pname", "pdesc")
     self.setData({'lid': lid})
     if self.checkParamsAvailable(lid, pname):
         project_exists_query = db_session.query(Project).filter(Project.name==pname).\
             filter(Project.l_id==lid).exists()
         if not db_session.query(project_exists_query).scalar():
             try:
                 new_project = Project()
                 new_project.l_id = lid
                 new_project.name = pname
                 new_project.desc = pdesc
                 db_session.add(new_project)
                 db_session.commit()
                 self.changeResponse2Success()
             except Exception as e:
                 db_session.rollback()
                 self.setFailureReason(str(e))
         else:
             self.setFailureReason("该实验室下存在同名的定量研究项目,请重新命名!")
def error_response(error, message=""):
    db_session.rollback()
    return make_response(jsonify(error=error, message=message),
        error_codes[error])
Пример #56
0
def teardown_request(exception=None):
    try:
        db_session.commit()
    except:
        db_session.rollback()
        raise
Пример #57
0
def admin_test():
    db_session.rollback()
    create_user = User(id='admin', password=hash_password('password')) 
    db_session.add(create_user)
    db_session.commit()