Ejemplo n.º 1
0
    async def on_message(self, message):
        if message.author == self.user:
            return

        command_match = self.command_matcher.match(message.content)

        if (command_match is not None):
            if (command_match.group(1) == 'strike'):
                target_user = message.guild.get_member(
                    int(command_match.group(2)))

                if self.get_next_strike_role(target_user.roles,
                                             message.guild.roles) is None:
                    await message.channel.send(
                        '**{} ({})** is at the max strike level.'.format(
                            target_user.display_name, target_user.name))
                    return

                session = Session()
                pending_strike = operations.user_has_pending_strike(
                    session, target_user.id)

                if pending_strike is not None:
                    await message.channel.send(
                        '**{} ({})** has pending strike.\n{}'.format(
                            target_user.display_name, target_user.name,
                            pending_strike.watched_message_jump_url))
                    return

                try:
                    voting_expiration_date = datetime.now() + timedelta(
                        hours=6)
                    bot_message = await message.channel.send(
                        content=
                        '```haskell\n{} ({}) is proposing a strike against {} ({}), react with strike to support\nReason: {}\nVoting ends at {}```'
                        .format(
                            message.author.display_name,
                            message.author.name,
                            target_user.display_name,
                            target_user.name,
                            command_match.group(3),
                            voting_expiration_date.replace(microsecond=0),
                        ))
                    operations.propose_strike(
                        session,
                        message.guild,
                        message.author,
                        target_user,
                        command_match.group(3),
                        bot_message.channel.id,
                        bot_message.id,
                        bot_message.jump_url,
                        voting_expiration_date,
                    )
                    session.commit()
                except Exception as e:
                    print(e)
                    session.rollback()
                finally:
                    session.close()
Ejemplo n.º 2
0
  def post(self, id_):
    """ Publish to BBS
    """
    errors = {}

    username = self.get_argument("username", "名無し")
    if username == "":
      username = "******"
    mail = self.get_argument("mail")

    text = self.get_argument("text")
    if text == "":
      errors["text"] = True

    if not errors:
      session = Session()
      res = Response(text, username)
      res.bbs_id = id_
      session.add(res)
      session.commit()
      session.close()

    responses = self.get_responses(id_)

    self.render("BBS/index.html",
        responses=responses,
        errors=errors
    )
Ejemplo n.º 3
0
def stopProcess(address, port, dbPassword):
    s = Session(address, port=port, service="Monitor")
    s.authorize("Cloud", dbPassword)
    s.doConnect()

    s.send("<Request Action=\"shutdown\"/>")

    s.close()
Ejemplo n.º 4
0
 async def on_guild_join(self, guild):
     session = Session()
     try:
         operations.create_server(session, guild.id)
         session.commit()
     except:
         session.rollback()
     finally:
         session.close()
Ejemplo n.º 5
0
def sample():
    title   = request.form['title'] # name を受け取る
    opinion = request.form['opinion']

    session = Session()
    sample = sample_model(id=title) # インスタンスを作成
    session.add(sample) # データ追加
    session.commit() # データをDBへ反映
    session.close() # セッションを閉じる
    return render_template('sample.html',title = title, opinion = opinion)
Ejemplo n.º 6
0
def doDatabaseAction(broker, user, password, db_name, action, child=None):
    s = Session(broker, service="ChorusManagement")
    s.authorize(user, password)

    if child is not None:
        child = [ child ]
    s.doConnect(attributes={"Database" : db_name, "Action" : action}, children=child)
    response = s.recv()
    checkForError(response)

    s.close()

    return response
Ejemplo n.º 7
0
def post_list_page():
    title   = request.form['title'] # name を受け取る
    opinion = request.form['opinion']
    
    session = Session()
    
    post_list   = post(title=title,opinion=opinion)
    session.add(post_list)
    #session.add(opinion_db)
    session.commit()

    post_list  = session.query( post ).all()
    session.close()
    return render_template('post_list.html',post_list=post_list,title=title,opinion=opinion)
Ejemplo n.º 8
0
    def upgrade(self):
        cnx = connector.connect(
            host=self.config.host,
            user=self.config.username,
            password=self.config.password)

        db_cursor = cnx.cursor()

        db_cursor.execute("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{0}'".format(self.config.database))
        db_exists = db_cursor.fetchone()

        if not db_exists:
            try:
                db_cursor.execute("CREATE DATABASE {0}".format(self.config.database))
            except Exception as ex:
                message = 'Could not create database: ' + ex.msg
                logging.error(message)
                raise Exception(message)

        cnx.database = self.config.database

        session = Session(cnx)

        # do it.
        session.execute("""
            CREATE TABLE IF NOT EXISTS upgrade_history (
              id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
              upgrade_date DATETIME,
              version INTEGER
            )""")

        session.execute("SELECT IFNULL(MAX(version),0) FROM upgrade_history")
        db_version = session.fetch_results()[0][0]  # first row first col

        script = self.__create_upgrade_script()

        max_version = 0
        for query in script:
            if query['version'] > db_version:
                if query['version'] > max_version:
                    max_version = query['version']
                session.execute(query['sql'])

        if max_version > db_version:
            session.execute("""INSERT INTO upgrade_history (upgrade_date, version)
                          VALUES('{date}', '{version}');""".format(date=datetime.now().isoformat(), version=max_version))
            logginghelper.log_debug('Upgraded database to version ' + str(max_version))

        session.commit()
        session.close()
Ejemplo n.º 9
0
  def get_responses(self, id_=1, less_than=None, more_than=None):
    session = Session()
    bbs = session.query(BBS).filter(BBS.id == id_).one()

    responses = session.query(Response).filter(Response.bbs_id == id_)
    if less_than:
      responses = responses.filter(Response.id < less_than)
    if more_than:
      responses = responses.filter(Response.id > more_than)
    responses = responses.order_by(Response.id.desc()).limit(30).all()

    responses = [res.toDict() for res in responses]

    session.close()
    return responses
Ejemplo n.º 10
0
def end_session(sid):
    """End a robot control session.  After session is ended, another party
    can then acquire a new session."""
    try:
        # TODO can we move this port stuff to hangouts.py?
        #  The issue was that Session.close deletes the session directory,
        #  which clears out the port storage file.  But we don't want to
        #  stop the hangout before we validate sid & close session.
        session = Session(sid)
        port = session.get('hangout_control_port')
        session.close()
        control.stop_controlserver()
        stop_hangout(port)
        heartbeats.send_session_ended()
        return {'message': "Session ended successfully."}
    except SessionConflict, e:
        abort(409, "Unable to end control session: %s" % str(e))
Ejemplo n.º 11
0
def getCloudEntry(broker, db_name, attrs=None):
    if not attrs:
        attrs = dict()
    attrs["Database"] = db_name

    s = Session(broker, service="SQL2")

    s.doConnect(attributes=attrs)
    connectDetail = s.recv()
    s.close()

    checkForError(connectDetail)

    root = ElementTree.fromstring(connectDetail)
    if root.tag != "Cloud":
        raise SessionException("Unexpecetd response type: " + root.tag)

    return (root.get("Address"), int(root.get("Port")))
Ejemplo n.º 12
0
def queryEngine(address, port, target, dbPassword, msgBody=None):
    s = Session(address, port=port, service="Query")
    s.authorize("Cloud", dbPassword)
    s.doConnect()

    msg = "<Query Target=\"%s\"/>" % target
    if msgBody is not None:
        xml = ElementTree.fromstring(msg)
        xml.append(msgBody)
        msg = ElementTree.tostring(xml)

    s.send(msg)
    response = s.recv()

    checkForError(response)

    s.close()

    return response
Ejemplo n.º 13
0
    def process(self):
        '''Process Request'''
        self.form = cgi.FieldStorage()
        error = ''
        try:
            # get user from session
            session = Session()
            session.close()
            if not session.logged_in:
                raise Exception('User not logged in')

            # get mid parameter
            if 'mid' not in self.form:
                raise Exception('mid parameter not in request')

            user_id = self.response['user_id'] = session.user.id
            message_id = self.response['message_id'] = self.form['mid'].value
            MessageLikes(Message(message_id)).add(user_id)

        except Exception, e:
            error = 'Could not write user/message/like: %s' % e
Ejemplo n.º 14
0
    async def on_raw_reaction_add(self, payload):
        #TODO add this as a customizable user setting
        PROPONENTS_REQUIRED = 2

        if payload.emoji.name == 'strike':
            session = Session()
            try:
                strike = operations.add_strike_proponent(
                    session, payload.message_id, payload.user_id)

                if strike is not None:
                    if len(strike.proponents) >= PROPONENTS_REQUIRED:
                        guild = self.get_guild(payload.guild_id)
                        target_user = guild.get_member(
                            strike.targeted_user.discord_user_id)
                        strike_level_modified = await self.strike(
                            target_user, guild.roles, strike.reason)
                        strike = operations.mark_strike_operation_successful(
                            session, payload.message_id, strike_level_modified)
                        channel = guild.get_channel(payload.channel_id)
                        discord_proposing_user = guild.get_member(
                            strike.proposing_user.discord_user_id)
                        discord_target_user = guild.get_member(
                            strike.targeted_user.discord_user_id)
                        await channel.send('Strike proposed by **{} ({})** against **{} ({})** was successful. Strike {} applied.'.\
                            format(
                                discord_proposing_user.display_name,
                                discord_proposing_user.name,
                                discord_target_user.display_name,
                                discord_target_user.name,
                                strike.strike_level_modified
                            )
                        )
                    session.commit()
            except Exception as e:
                print(e)
                session.rollback()
                raise
            finally:
                session.close()
Ejemplo n.º 15
0
    async def clear_strikes(self):
        #TODO add this as a customizable user setting
        TIME_BEFORE_DECAY = 1
        session = Session()
        try:
            decayed_strikes = operations.get_decayed_strikes(
                session, TIME_BEFORE_DECAY)
            for strike in decayed_strikes:
                guild = self.get_guild(strike.server.discord_server_id)
                user = guild.get_member(strike.targeted_user.discord_user_id)
                await self.clear_strike(user, strike.strike_level_modified)
                strike.decay()
                await guild.get_channel(
                    strike.watched_message_channel_id
                ).send('Strike **{}** on {} ({}) has expired.'.format(
                    strike.strike_level_modified, user.display_name,
                    user.name))

            session.commit()
        except Exception as e:
            print(e)
        finally:
            session.close()
Ejemplo n.º 16
0
  def post(self, id_):
    """ Publish to BBS
    """
    errors = {}

    username = self.get_argument("username", "名無し")
    if username == "":
      username = "******"

    text = self.get_argument("text")
    if text == "":
      errors["text"] = True

    if not errors:
      session = Session()
      res = Response(text, username)
      res.bbs_id = id_
      session.add(res)
      session.commit()
      res = res.toDict()
      session.close()

    self.set_header("Content-Type", "text/json")
    self.write(json_encode([res]));
Ejemplo n.º 17
0
def index():
    session = Session()
    result  = session.query( sample_model ).all() # 全件取得 session.query(★★ class_name ★★).all()
    session.close()
    # app.logger.debug() # デバッグ用
    return render_template('index.html',result=result)
Ejemplo n.º 18
0
class MainFrame(wx.Frame):
    """Main Frame  of the app."""
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.session = Session()

        self.SetBackgroundColour(BGD_COLOR)

        # List of timers so we can stop them when we quit.
        # Avoids PyDeadObjectError.
        self.timers = set()
        Publisher().subscribe(self.new_timer, "new_timer")

        # Build the menu bar
        menu_bar = wx.MenuBar()

        file_menu = wx.Menu()
        exit_item = file_menu.Append(wx.ID_EXIT, text="E&xit")
        self.Bind(wx.EVT_MENU, self.on_quit, exit_item)

        help_menu = wx.Menu()
        about_item = help_menu.Append(wx.ID_ABOUT, text="&About",
                                      help="Information about this program")
        self.Bind(wx.EVT_MENU, self.on_about, about_item)

        menu_bar.Append(file_menu, "&File")
        menu_bar.Append(help_menu, "&Help")
        self.SetMenuBar(menu_bar)

        self.CreateStatusBar(style=0)
        Publisher().subscribe(self.change_statusbar, "change_statusbar")

        # Add panels
        connections_panel = ConnectionsPanel(self, self.session, BGD_COLOR)
        clipboard_panel = ClipboardPanel(self, self.session, BGD_COLOR)
        status_panel = StatusPanel(self, BGD_COLOR)

        new_btn = wx.Button(self, label="New Connection")
        new_btn.Bind(wx.EVT_BUTTON, self.on_new)

        auto_sync_cb = wx.CheckBox(self, id=wx.ID_ANY,
                                       label="Automatically Sync")
        self.Bind(wx.EVT_CHECKBOX, self.on_toggle_auto, auto_sync_cb)
        auto_sync_cb.Bind(wx.EVT_ENTER_WINDOW, self.on_enter_auto)
        auto_sync_cb.Bind(wx.EVT_LEAVE_WINDOW, self.on_leave_auto)

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        top_row_sizer = wx.BoxSizer(wx.HORIZONTAL)
        board_sizer = wx.BoxSizer(wx.VERTICAL)

        btn_flags = wx.SizerFlags().Proportion(0).Border(wx.ALL, 5).Bottom()
        status_flags = wx.SizerFlags().Proportion(1).Expand().Border(wx.ALL, 5).Top()
        flags = wx.SizerFlags().Proportion(0).Expand().Border(wx.ALL, 5)
        board_flags = wx.SizerFlags().Proportion(0).Border(wx.ALL, 5).Right()
        top_flags = wx.SizerFlags().Proportion(0).Expand().Border(wx.ALL, 5)
        conn_flags = wx.SizerFlags().Proportion(1).Expand().Border(wx.ALL, 5)
        
        board_sizer.AddF(auto_sync_cb, flags)
        board_sizer.AddF(clipboard_panel, flags)

        top_row_sizer.AddF(new_btn, btn_flags)
        top_row_sizer.AddF(status_panel, status_flags)
        top_row_sizer.AddF(board_sizer, board_flags)

        main_sizer.AddF(top_row_sizer, top_flags)
        main_sizer.AddF(connections_panel, conn_flags)

        self.SetSizer(main_sizer)

    def new_timer(self, msg):
        self.timers.add(msg.data)

    def change_statusbar(self, msg):
        self.SetStatusText(msg.data)

    def on_new(self, event):
        Publisher().sendMessage(("new_connection"))

    def on_toggle_auto(self, event):
        Publisher().sendMessage(("auto_toggle"), event.IsChecked())

    def on_enter_auto(self, event):
        Publisher().sendMessage(("change_statusbar"),
            "Automatically copy/paste new items to/from your clipboard")
        event.Skip()

    def on_leave_auto(self, event):
        Publisher().sendMessage(("change_statusbar"), "")
        event.Skip()

    def on_about(self, event):
        aboutbox = AboutDialog(self)
        aboutbox.ShowModal()
        aboutbox.Destroy()

    def on_quit(self, event):
        for timer in self.timers():
            timer.Stop()
        self.session.close()
        self.Close()
Ejemplo n.º 19
0
class CategoriesController:
    def __init__(self):
        """Initializes model with database connection"""
        self.db_session = Session()

    def create(self, form_data):
        """Creates a new category and returns a json object"""
        try:
            """form includes user_token, which is used to get user email"""
            user = UserModel(form_data['user_token'])
            form_data['created_by'] = user.email
            category = CategoryModel(form_data).create(self.db_session)
        except exc.IntegrityError as e:
            self.db_session.rollback()
            category = CategoryModel({'errors': 'failed to update database'})
        finally:
            self.db_session.close()

        return jsonify(category.attributes())

    def delete(self, name, form_data):
        """Deletes a category and returns a json object"""
        try:
            """form includes user_token, which is used to get user email"""
            user = UserModel(form_data['user_token'])
            category = CategoryModel(
                {'name': name, 'created_by': user.email}
            ).delete(self.db_session)
        except exc.IntegrityError as e:
            self.db_session.rollback()
            category = CategoryModel({'errors': 'Error Deleting Category'})
        finally:
            self.db_session.close()

        return jsonify(category.attributes())

    def index(self):
        """Queries categories and items, then renders index view"""
        categories = CategoryModel.all(self.db_session)
        items = ItemModel.latest(self.db_session)
        self.db_session.close()

        return render_template(
            'categories/index.html', categories=categories, items=items
        )

    def show(self, name, headers):
        """Queries single category. Returns html or json view"""
        category = CategoryModel.find(self.db_session, name)
        self.db_session.close()

        if headers == 'application/json':
            return jsonify(category.attributes())
        else:
            return render_template('categories/show.html', category=category)

    def update(self, form_data):
        """Updates a category and returns a json object"""
        try:
            user = UserModel(form_data['user_token'])
            form_data['created_by'] = user.email
            category = CategoryModel(form_data).update(self.db_session)
        except exc.IntegrityError as e:
            self.db_session.rollback()
            category = CategoryModel({'errors': 'Error Updating Category'})
        finally:
            self.db_session.close()
        return jsonify(category.attributes())
Ejemplo n.º 20
0
      <node lat="46.5059522910652" lon="6.674499182942514" changeset="%(changeset)s" />
</osm>"""%{'changeset': changeset_id})
    n4 = api.put("/api/0.6/node/create", """<?xml version="1.0" encoding="UTF-8"?>
<osm>
      <node lat="46.50601259859745" lon="6.674312944430097" changeset="%(changeset)s" />
</osm>"""%{'changeset': changeset_id})

    print api.put("/api/0.6/way/create", """<?xml version="1.0" encoding="UTF-8"?>
<osm>
      <way changeset="%(changeset)s">
        <nd ref="%(n1)s" />
        <nd ref="%(n2)s" />
        <nd ref="%(n3)s" />
        <nd ref="%(n4)s" />
        <nd ref="%(n1)s" />
        <tag k="test" v="test" />
      </way>
</osm>"""%{'changeset': changeset_id, 'n1': n1, 'n2': n2, 'n3': n3, 'n4': n4})

    # close changeset
    api.put("/api/0.6/changeset/%s/close"%changeset_id)

    print
    print "Writing changes to " + OSMOAuth.API_URL + "/browse/changeset/" + changeset_id

else:
    print
    print "No valid query."

session.close()
Ejemplo n.º 21
0
class ItemsController:
    def __init__(self):
        """Initializes model with database connection"""
        self.db_session = Session()

    def create(self, form):
        """Creates a new item and returns a json object with item values"""
        try:
            """form includes user_token, which is used to get user email"""
            user = UserModel(form['user_token'])
            form['created_by'] = user.email
            item = ItemModel(form).create(self.db_session)
        except exc.IntegrityError as e:
            self.db_session.rollback()
            item = ItemModel({'errors': 'Error Creating Item'})
        finally:
            self.db_session.close()

        return jsonify(item.attributes())

    def delete(self, title, form_data):
        """Deletes an item and returns a json object with the item values"""
        try:
            """form includes user_token, which is used to get user email"""
            user = UserModel(form_data['user_token'])
            item = ItemModel({
                'title': title,
                'created_by': user.email
            }).delete(self.db_session)
        except exc.IntegrityError as e:
            self.db_session.rollback()
            item = ItemModel({'errors': 'Error Deleting Item'})
        finally:
            self.db_session.close()

        return jsonify(item.attributes())

    def index(self, category_name, headers):
        """Queries category and related items, then renders index view"""
        category = CategoryModel.find(self.db_session, category_name)
        items = ItemModel.category_group(self.db_session, category.id)
        self.db_session.close()

        if headers == 'application/json':
            json_items = []
            for item in items:
                json_items.append(item.attributes())
            return jsonify({
                'category': category.attributes(),
                'items': json_items
            })
        else:
            return render_template('items/index.html',
                                   category=category,
                                   items=items)

    def show(self, title, headers):
        """Queries single item. Returns html or json view"""
        item = ItemModel.find(self.db_session, title)
        self.db_session.close()

        if headers == 'application/json':
            return jsonify(item.attributes())
        else:
            categories = CategoryModel.all(self.db_session)
            return render_template('items/show.html',
                                   item=item,
                                   categories=categories)

    def update(self, form_data):
        """Updates an item and returns a json object with the item values"""
        try:
            """form includes user_token, which is used to get user email"""
            user = UserModel(form_data['user_token'])
            form_data['created_by'] = user.email
            item = ItemModel(form_data).update(self.db_session)
        except exc.IntegrityError as e:
            self.db_session.rollback()
            item = ItemModel({'errors': 'Error Updating Item'})
        finally:
            self.db_session.close()
        return jsonify(item.attributes())