コード例 #1
0
    def __init__(self,
                 admin,
                 board=None,
                 dest=None,
                 page=None,
                 perpage=50,
                 **kwargs):
        try:
            self.user = staff.check_password(admin)
        except staff.LoginError:
            Template.__init__(self, 'admin_login_template', login_task=dest)
            return
        if not dest:
            dest = HOME_PANEL

        self.admin = admin

        # TODO: Check if mod is banned.
        if not page:
            if dest in (HOME_PANEL, TRASH_PANEL):
                # Adjust for different pagination scheme. (Blame Wakaba.)
                page = 0
            else:
                page = 1
        if not str(perpage).isdigit():
            perpage = 50

        # The page attribute is not always a pure integer (thread pages).
        if str(page).isdigit():
            page = int(page)
        self.page = page
        self.perpage = int(perpage)
        self.board = local.environ['waka.board']

        if dest not in INTERFACE_MAPPING:
            dest = HOME_PANEL

        INTERFACE_MAPPING[dest](self, **kwargs)

        # Convert user reign list into a list of dictionaries, for
        # templating.
        reign = []
        if self.user.account == staff.MODERATOR:
            reign = [{'board_entry': entry} for entry in self.user.reign]
        else:
            if self.board:
                reign = interboard.get_all_boards\
                        (check_board_name=self.board.name)
            else:
                reign = interboard.get_all_boards()

        # Set global form variables.
        Template.update_parameters(self,
                                   username=self.user.username,
                                   type=self.user.account,
                                   admin=admin,
                                   boards_select=reign,
                                   boards=reign,
                                   page=self.page,
                                   perpage=self.perpage)
コード例 #2
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_staff_panel(self):
        session = model.Session()
        table = model.account
        sql = table.select().order_by(table.c.account.asc(), table.c.username.asc())

        query = session.execute(sql)
        users = [dict(row.items()) for row in query]

        rowtype = 1
        for row in users:
            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row["rowtype"] = rowtype

            # Get latest action from DB.
            action_table = model.activity
            action_grab_sql = (
                action_table.select()
                .where(action_table.c.username == row["username"])
                .order_by(action_table.c.date.desc())
            )
            last_action = session.execute(action_grab_sql).fetchone()

            # Copy to row.
            if last_action:
                row["action"] = last_action["action"]
                row["actiondate"] = last_action["date"]
            else:
                row["action"] = None
                row["actiondate"] = None

        Template.__init__(self, "staff_management", users=users)
コード例 #3
0
    def make_admin_staff_panel(self):
        session = model.Session()
        table = model.account
        sql = table.select().order_by(table.c.account.asc(),
                                      table.c.username.asc())

        query = session.execute(sql)
        users = [dict(row.items()) for row in query]

        rowtype = 1
        for row in users:
            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row['rowtype'] = rowtype

            # Get latest action from DB.
            action_table = model.activity
            action_grab_sql = action_table.select()\
                        .where(action_table.c.username == row['username'])\
                        .order_by(action_table.c.date.desc())
            last_action = session.execute(action_grab_sql).fetchone()

            # Copy to row.
            if last_action:
                row['action'] = last_action['action']
                row['actiondate'] = last_action['date']
            else:
                row['action'] = None
                row['actiondate'] = None

        Template.__init__(self, 'staff_management', users=users)
コード例 #4
0
 def __init__(self, lst, master, userr_coll, userr_name):
     self.master = master
     self.lst = lst
     self.userr_coll = userr_coll
     self.userr_name = userr_name
     Template.__init__(self, self.lst, self.master)
     self.master.title('about_us')
     print(type(self.userr_coll))
コード例 #5
0
    def make_admin_post_search_panel(self, search, text, caller='internal'):
        board = self.board
        session = model.Session()
        table = board.table

        board.check_access(self.user)

        popup = caller != 'board'

        if search.find('IP Address') != -1:
            try:
                sql = table.select()\
                           .where(table.c.ip == misc.dot_to_dec(text))
            except ValueError:
                raise WakaError('Please enter a valid IP.')
            search_type = 'IP'
        elif search.find('Text String') != -1:
            sql = table.select().where(table.c.comment.like('%'+text+'%'))
            search_type = 'text string'
        elif search.find('Author') != -1:
            sql = table.select().where(or_(table.c.name.like('%'+text+'%'),
                table.c.trip.like('%'+text+'%')))
            search_type = 'author'
        else:
            sql = table.select().where(table.c.num == text)
            search_type = 'ID'

        if search_type != 'ID':
            page = model.Page(sql, self.page, self.perpage)
            rowcount = page.total_entries
            total_pages = page.total_pages
            posts = page.rows
            if not posts:
                raise WakaError("No posts found for %s %s" % (search_type, text))
        else:
            rowcount = total_pages = 1
            row = session.execute(sql).fetchone()
            if not row:
                raise WakaError("Post not found. (It may have just been"
                                " deleted.)")
            posts = [row]


        inputs = [
            {'name': 'board', 'value': board.name},
            {'name' : 'task', 'value' : 'searchposts'},
            {'name' : 'text', 'value' : text},
            {'name': 'caller', 'value': caller},
            {'name' : 'search', 'value': search}
        ]

        rooturl = misc.make_script_url(task='searchposts', board=board.name,
            caller=caller, search=search, text=text, _amp=True)

        Template.__init__(self, 'post_search', num=id,
                          posts=posts, search=search, text=text,
                          inputs=inputs, number_of_pages=total_pages,
                          rooturl=rooturl, rowcount=rowcount, popup=popup)
コード例 #6
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_edit_staff_window(self, username):
        boards = interboard.get_all_boards()
        edited_user = staff.StaffMember.get(username)

        for board in boards:
            if board in edited_user.reign:
                board["underpower"] = True

        Template.__init__(self, "staff_edit_template", user_to_edit=username, boards=boards)
コード例 #7
0
    def make_admin_proxy_panel(self):
        session = model.Session()
        table = model.proxy
        query = table.select().order_by(table.c.timestamp.asc())
        rows = session.execute(query)

        Template.__init__(self,
                          'proxy_panel_template',
                          scanned=rows,
                          now=time.time())
コード例 #8
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def __init__(self, cookie, board=None, dest=None, page=None, perpage=50, **kwargs):
        try:
            self.user = staff.StaffMember.get_from_cookie(cookie)
        except staff.LoginError:
            Template.__init__(self, "admin_login_template", login_task=dest)
            return
        if not dest:
            dest = HOME_PANEL

        self.admin = cookie

        # TODO: Check if mod is banned.
        if not page:
            if dest in (HOME_PANEL, TRASH_PANEL):
                # Adjust for different pagination scheme. (Blame Wakaba.)
                page = 0
            else:
                page = 1
        if not str(perpage).isdigit():
            perpage = 50

        # The page attribute is not always a pure integer (thread pages).
        if str(page).isdigit():
            page = int(page)
        self.page = page
        self.perpage = int(perpage)
        self.board = local.environ["waka.board"]

        if dest not in INTERFACE_MAPPING:
            dest = HOME_PANEL

        INTERFACE_MAPPING[dest](self, **kwargs)

        # Convert user reign list into a list of dictionaries, for
        # templating.
        reign = []
        if self.user.account == staff.MODERATOR:
            reign = [{"board_entry": entry} for entry in self.user.reign]
        else:
            if self.board:
                reign = interboard.get_all_boards(check_board_name=self.board.name)
            else:
                reign = interboard.get_all_boards()

        # Set global form variables.
        Template.update_parameters(
            self,
            username=self.user.username,
            type=self.user.account,
            admin=cookie,
            boards_select=reign,
            boards=reign,
            page=self.page,
            perpage=self.perpage,
        )
コード例 #9
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_spam_panel(self):
        # TODO: Paginate this, too.
        spam_list = []
        for filename in config.SPAM_FILES:
            with open(filename, "r") as f:
                spam_list.extend([str_format.clean_string(l) for l in f])

        spamlines = len(spam_list)
        spam = "".join(spam_list)

        Template.__init__(self, "spam_panel_template", spam=spam, spamlines=spamlines)
コード例 #10
0
    def make_admin_report_panel(self, sortby='date', order='desc'):
        sortby_type = sortby
        sortby_dir = order

        session = model.Session()
        table = model.report
        sql = table.select()

        # Enforce limited moderation reign.
        if self.user.account == staff.MODERATOR:
            sql = sql.where(table.c.board.in_(self.user.reign))

        # Determine order.
        if sortby_type in ('board', 'postnum', 'date'):
            try:
                column = getattr(table.c, sortby_type)
            except AttributeError:
                raise WakaError('Sort-by column is absent from table.')
            sort = column.desc
            if sortby_dir == 'asc':
                sort = column.asc
            sql = sql.order_by(sort(), table.c.date.desc())
        else:
            sql = sql.order_by(table.c.date.desc())

        # Paginate.
        res = model.Page(sql, self.page, self.perpage)

        # Hidden input fields.
        inputs = [{
            'name': 'task',
            'value': 'reports'
        }, {
            'name': 'order',
            'value': sortby_dir
        }, {
            'name': 'sortby',
            'value': sortby_type
        }]

        rooturl = misc.make_script_url(task='reports',
                                       sortby=sortby_type,
                                       order=sortby_dir,
                                       _amp=True)

        Template.__init__(self,
                          'report_panel_template',
                          reports=res.rows,
                          sortby=sortby_type,
                          order=sortby_dir,
                          number_of_pages=res.total_pages,
                          rowcount=res.total_entries,
                          inputs=inputs,
                          rooturl=rooturl)
コード例 #11
0
    def make_admin_home_panel(self):
        # Update perpage attribute: it is determined here by board options.
        board = self.board
        self.perpage = board.options['IMAGES_PER_PAGE']

        # Get reports.
        reports = board.get_local_reports()

        # Send to Template initializer.
        kwargs = {}
        threads = []

        if str(self.page).startswith('t'):
            self.page = self.page[1:]
            posts = board.get_thread_posts(self.page)
            threads.append({'posts': posts})
            kwargs = {
                'lockedthread': posts[0].locked,
                'parent': self.page,
                'thread': self.page
            }
        else:
            # Grab count of all threads.
            table = board.table
            session = model.Session()
            sql = select([func.count()], table.c.parent == 0)
            thread_count = session.execute(sql).fetchone()[0]
            total = (thread_count + self.perpage - 1) / self.perpage

            if total <= self.page and total > 0:
                # Set page number to last page if exceeding total.
                # Pages are 0-indexed.
                self.page = total - 1
            # Get partial board posts.
            pagethreads = board.get_some_threads(self.page)
            (pages, prevpage, nextpage)\
                = board.get_board_page_data(self.page, total,
                                            admin_page='mpanel')
            threads = board.parse_page_threads(pagethreads)
            kwargs = {
                'pages': pages,
                'prevpage': prevpage,
                'nextpage': nextpage
            }

        Template.__init__(self,
                          'post_panel_template',
                          postform=board.options['ALLOW_TEXTONLY']
                          or board.options['ALLOW_IMAGES'],
                          image_inp=board.options['ALLOW_IMAGES'],
                          threads=threads,
                          reportedposts=reports,
                          **kwargs)
コード例 #12
0
    def make_edit_staff_window(self, username):
        boards = interboard.get_all_boards()
        edited_user = staff.StaffMember.get(username)

        for board in boards:
            if board in edited_user.reign:
                board['underpower'] = True

        Template.__init__(self,
                          'staff_edit_template',
                          user_to_edit=username,
                          boards=boards)
コード例 #13
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_ban_panel(self, ip=""):
        session = model.Session()
        table = model.admin

        sql = select(
            [
                model.activity.c.username,
                table.c.num,
                table.c.type,
                table.c.comment,
                table.c.ival1,
                table.c.ival2,
                table.c.sval1,
                table.c.total,
                table.c.expiration,
            ],
            from_obj=[
                table.outerjoin(
                    model.activity,
                    and_(table.c.num == model.activity.c.admin_id, table.c.type == model.activity.c.action),
                )
            ],
        ).order_by(table.c.type.asc(), table.c.num.asc())

        # TODO: We should be paginating, but the page needs to be
        # adjusted first.
        # res = model.Page(sql, self.page, self.perpage)

        query = session.execute(sql)
        bans = [dict(row.items()) for row in query]

        rowtype = 1
        prevtype = ""
        for row in bans:
            prevtype = row
            if prevtype != row["type"]:
                row["divider"] = 1

            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row["rowtype"] = rowtype

            if row["expiration"]:
                row["expirehuman"] = misc.make_date(row["expiration"])
            else:
                row["expirehuman"] = "Never"

            if row["total"] == "yes":
                row["browsingban"] = "No"
            else:
                row["browsingban"] = "Yes"

        Template.__init__(self, "ban_panel_template", bans=bans, ip=ip)
コード例 #14
0
    def __init__(self):
	Template.__init__(self,
			  [{"class" : Getstatic, "match" : "getstatic CRunTime/memory [I"},
			   {"class" : Iload},
			   {"class" : Iconst},
			   {"class" : Iushr},
			   {"optional-class" : Iconst},
			   {"optional-class" : Iadd},
			   {"class" : Iaload},
			   {"class" : Istore},
			   ]
			  )
コード例 #15
0
    def make_admin_spam_panel(self):
        # TODO: Paginate this, too.
        spam_list = []
        for filename in config.SPAM_FILES:
            with open(filename, 'r') as f:
                spam_list.extend([str_format.clean_string(l) for l in f])

        spamlines = len(spam_list)
        spam = ''.join(spam_list)

        Template.__init__(self,
                          'spam_panel_template',
                          spam=spam,
                          spamlines=spamlines)
コード例 #16
0
    def make_admin_home_panel(self):
        # Update perpage attribute: it is determined here by board options.
        board = self.board
        self.perpage = board.options['IMAGES_PER_PAGE']

        # Get reports.
        reports = board.get_local_reports()

        # Send to Template initializer.
        kwargs = {}
        threads = []

        if str(self.page).startswith('t'):
            self.page = self.page[1:]
            posts = board.get_thread_posts(self.page)
            threads.append({'posts' : posts})
            kwargs = {'lockedthread' : posts[0].locked,
                      'parent' : self.page,
                      'thread' : self.page}
        else:
            # Grab count of all threads.
            table = board.table
            session = model.Session()
            sql = select([func.count()], table.c.parent == 0)
            thread_count = session.execute(sql).fetchone()[0]
            total = (thread_count + self.perpage - 1) / self.perpage

            if total <= self.page and total > 0:
                # Set page number to last page if exceeding total.
                # Pages are 0-indexed.
                self.page = total - 1
            # Get partial board posts.
            pagethreads = board.get_some_threads(self.page)
            (pages, prevpage, nextpage)\
                = board.get_board_page_data(self.page, total,
                                            admin_page='mpanel')
            threads = board.parse_page_threads(pagethreads)
            kwargs = {'pages' : pages,
                      'prevpage' : prevpage,
                      'nextpage' : nextpage}

        Template.__init__(self, 'post_panel_template', 
                          postform=board.options['ALLOW_TEXTONLY'] or
                                   board.options['ALLOW_IMAGES'],
                          image_inp=board.options['ALLOW_IMAGES'],
                          threads=threads,
                          reportedposts=reports,
                          **kwargs)
コード例 #17
0
    def make_admin_ban_panel(self, ip=''):
        session = model.Session()
        table = model.admin

        sql = select([model.activity.c.username,
                      table.c.num,
                      table.c.type,
                      table.c.comment,
                      table.c.ival1,
                      table.c.ival2,
                      table.c.sval1,
                      table.c.total,
                      table.c.expiration],
            from_obj=[table.outerjoin(model.activity,
            and_(table.c.num == model.activity.c.admin_id,
            table.c.type == model.activity.c.action))])\
            .order_by(table.c.type.asc(), table.c.num.asc())

        # TODO: We should be paginating, but the page needs to be
        # adjusted first.
        # res = model.Page(sql, self.page, self.perpage)

        query = session.execute(sql)
        bans = [dict(row.items()) for row in query]

        rowtype = 1
        prevtype = ''
        for row in bans:
            prevtype = row
            if prevtype != row['type']:
                row['divider'] = 1

            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row['rowtype'] = rowtype

            if row['expiration']:
                row['expirehuman'] = misc.make_date(row['expiration'])
            else:
                row['expirehuman'] = 'Never'

            if row['total'] == 'yes':
                row['browsingban'] = 'No'
            else:
                row['browsingban'] = 'Yes'

        Template.__init__(self, 'ban_panel_template', bans=bans, ip=ip)
コード例 #18
0
    def make_admin_ban_panel(self, ip=''):
        session = model.Session()
        table = model.admin

        sql = select([model.activity.c.username,
                      table.c.num,
                      table.c.type,
                      table.c.comment,
                      table.c.ival1,
                      table.c.ival2,
                      table.c.sval1,
                      table.c.total,
                      table.c.expiration],
            from_obj=[table.outerjoin(model.activity,
            and_(table.c.num == model.activity.c.admin_id,
            table.c.type == model.activity.c.action))])\
            .order_by(table.c.type.asc(), table.c.num.asc())

        # TODO: We should be paginating, but the page needs to be
        # adjusted first.
        # res = model.Page(sql, self.page, self.perpage)

        query = session.execute(sql)
        bans = [dict(row.items()) for row in query]

        rowtype = 1
        prevtype = ''
        for row in bans:
            prevtype = row
            if prevtype != row['type']:
                row['divider'] = 1

            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row['rowtype'] = rowtype

            if row['expiration']:
                row['expirehuman'] = misc.make_date(row['expiration'])
            else:
                row['expirehuman'] = 'Never'

            if row['total'] == 'yes':
                row['browsingban'] = 'No'
            else:
                row['browsingban'] = 'Yes'

        Template.__init__(self, 'ban_panel_template', bans=bans, ip=ip)
コード例 #19
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_report_panel(self, sortby="date", order="desc"):
        sortby_type = sortby
        sortby_dir = order

        table = model.report
        sql = table.select()

        # Enforce limited moderation reign.
        if self.user.account == staff.MODERATOR:
            sql = sql.where(table.c.board.in_(self.user.reign))

        # Determine order.
        if sortby_type in ("board", "postnum", "date"):
            try:
                column = getattr(table.c, sortby_type)
            except AttributeError:
                raise WakaError("Sort-by column is absent from table.")
            sort = column.desc
            if sortby_dir == "asc":
                sort = column.asc
            sql = sql.order_by(sort(), table.c.date.desc())
        else:
            sql = sql.order_by(table.c.date.desc())

        # Paginate.
        res = model.Page(sql, self.page, self.perpage)

        # Hidden input fields.
        inputs = [
            {"name": "task", "value": "reports"},
            {"name": "order", "value": sortby_dir},
            {"name": "sortby", "value": sortby_type},
        ]

        rooturl = misc.make_script_url(task="reports", sortby=sortby_type, order=sortby_dir, _amp=True)

        Template.__init__(
            self,
            "report_panel_template",
            reports=res.rows,
            sortby=sortby_type,
            order=sortby_dir,
            number_of_pages=res.total_pages,
            rowcount=res.total_entries,
            inputs=inputs,
            rooturl=rooturl,
        )
コード例 #20
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_script_security_panel(self):
        session = model.Session()
        table = model.passprompt
        rows = session.execute(table.select())

        now = time.time()

        entries = []
        for row in rows:
            row = dict(row)
            if row["passfail"]:
                row["expiration"] = config.PASSFAIL_ROLLBACK - now + row["timestamp"]
            else:
                row["expiration"] = config.PASSPROMPT_EXPIRE_TO_FAILURE - now + row["timestamp"]
            entries.append(row)

        Template.__init__(self, "script_security_panel", entries=entries)
コード例 #21
0
    def make_sql_interface_panel(self, sql='', nuke=''):
        if self.user.account != staff.ADMIN:
            raise WakaError(strings.INSUFFICIENTPRIVILEGES)

        results = []

        if sql or nuke:
            if nuke != local.environ['waka.board'].options['NUKE_PASS']:
                raise WakaError(strings.WRONGPASS)

            session = model.Session()
            if sql:
                for sql in sql.split('\r\n'):
                    # Execute teh string.
                    try:
                        results.append('>>> ' + sql)
                        row = session.execute(sql)
                    except Exception as errstr:
                        results.append('ERROR: %s' % (errstr))
                    else:
                        try:
                            results.append(str(row.fetchall()))
                        except:
                            results.append('OK')
            else:
                # Remove board table contents and board list entry.
                try:
                    board = local.environ['waka.board']
                    board.table.drop(bind=model.engine, checkfirst=True)
                    del model._boards[board.name]
                    model.common.delete().where(model.common.c.board \
                                                == board.name)
                except Exception as errstr:
                    results.append('ERROR %s' % (errstr))
                else:
                    results.append('Comment table dropped. You should '
                                   'delete/move the board folder now.')
        else:
            results.append('Leave textarea blank to delete the board.\n\n'
                           '(It is recommended that you disable site access '
                           'while entering SQL or deleting boards.)')

        Template.__init__(self,
                          'sql_interface_template',
                          results='<br />'.join(results))
コード例 #22
0
    def make_ban_edit_popup(self, num):
        session = model.Session()
        table = model.admin
        sql = table.select().where(table.c.num == num)
        row = session.execute(sql).fetchone()

        if row.expiration:
            expiration = datetime.utcfromtimestamp(row.expiration)
        else:
            expiration = datetime.utcnow()

        Template.__init__(self, 'edit_window', hash=[row],
                          year=expiration.year,
                          month=expiration.month,
                          day=expiration.day,
                          hour=expiration.hour,
                          min=expiration.minute,
                          sec=expiration.second)
コード例 #23
0
    def make_sql_interface_panel(self, sql='', nuke=''):
        if self.user.account != staff.ADMIN:
            raise WakaError(strings.INUSUFFICENTPRIVLEDGES)

        results = []

        if sql or nuke:
            if nuke != local.environ['waka.board'].options['NUKE_PASS']:
                raise WakaError(strings.WRONGPASS)

            session = model.Session()
            if sql:
                for sql in sql.split('\r\n'):
                    # Execute teh string.
                    try:
                        results.append('>>> ' + sql)
                        row = session.execute(sql)
                    except Exception as errstr:
                        results.append('ERROR: %s' % (errstr))
                    else:
                        try:
                            results.append(str(row.fetchall()))
                        except:
                            results.append('OK')
            else:
                # Remove board table contents and board list entry.
                try:
                    board = local.environ['waka.board']
                    board.table.drop(bind=model.engine, checkfirst=True)
                    del model._boards[board.name]
                    model.common.delete().where(model.common.c.board \
                                                == board.name)
                except Exception as errstr:
                    results.append('ERROR %s' % (errstr))
                else:
                    results.append('Comment table dropped. You should '
                                   'delete/move the board folder now.')
        else:
            results.append('Leave textarea blank to delete the board.\n\n'
                           '(It is recommended that you disable site access '
                           'while entering SQL or deleting boards.)')

        Template.__init__(self, 'sql_interface_template',
                          results='<br />'.join(results))
コード例 #24
0
    def generateMsgDataType(msgData, currentMessage):
        msginfo = {}
        msgTypeInfo = {}
        msginfo['msgDataName'] = currentMessage + 'MsgData'
        msginfo['ieDetails'] = []
        msgTypeInfo['msgDataType'] = currentMessage + 'MsgType'
        msgTypeInfo['msgValue'] = msgData['msgDetails'][currentMessage][
            'msgValue']

        if msgTypeInfo not in msgDataTypeData['msgTypeList']:
            msgDataTypeData['msgTypeList'].append(msgTypeInfo)

        for ieDetail in msgData['ieDetails']:
            for key, value in ieDetail.items():
                for ie in msgData['ieList']:
                    ieInfo = {}

                    if value['ieVarName'] == ie:
                        ieInfo['ieName'] = value['ieVarName']
                        ieInfo['ieVarName'] = value['ieVarName']
                        ieInfo['ieType'] = value['ieTypeName']
                        ieInfo['iePresence'] = value['presence']
                        ieInfo['ieCardinality'] = value['cardinality']
                        ieInfo['grouped'] = value['grouped']
                        ieInfo['grpIeInstClassName'] = value['ieGroupTypeName']
                        if ieInfo['grouped'] == 'Yes':
                            ieInfo['grpIeInstClassName'] = value[
                                'ieGroupTypeName'][0].upper(
                                ) + value['ieGroupTypeName'][1:]
                        ieInfo['grpIeInstFileName'] = value['ieGroupTypeName']
                        if ieInfo not in msginfo['ieDetails']:
                            msginfo['ieDetails'].append(ieInfo)
        if msginfo not in msgDataTypeData['msgList']:
            msgDataTypeData['msgList'].append(msginfo)

        template = Template()
        ttFileNamefactoryH = 'tts/msgDataTypetemplate.h.tt'
        outputDir = '../../src/gtpV2Codec/msgClasses'

        if not os.path.exists(outputDir):
            os.makedirs(outputDir)
        outputFileName = 'gtpV2MsgDataTypes.h'
        template.__init__({'OUTPUT': outputFileName, 'OUTPUT_PATH': outputDir})
        template.process(ttFileNamefactoryH, {'tempdata': msgDataTypeData})
コード例 #25
0
    def make_admin_report_panel(self, sortby='date', order='desc'):
        sortby_type = sortby
        sortby_dir = order

        session = model.Session()
        table = model.report
        sql = table.select()

        # Enforce limited moderation reign.
        if self.user.account == staff.MODERATOR:
            sql = sql.where(table.c.board.in_(self.user.reign))

        # Determine order.
        if sortby_type in ('board', 'postnum', 'date'):
            try:
                column = getattr(table.c, sortby_type)
            except AttributeError:
                raise WakaError('Sort-by column is absent from table.')
            sort = column.desc
            if sortby_dir == 'asc':
                sort = column.asc
            sql = sql.order_by(sort(), table.c.date.desc())
        else:
            sql = sql.order_by(table.c.date.desc())

        # Paginate.
        res = model.Page(sql, self.page, self.perpage)

        # Hidden input fields.
        inputs = [{'name' : 'task', 'value' : 'reports'},
                  {'name' : 'order', 'value' : sortby_dir},
                  {'name' : 'sortby', 'value' : sortby_type}]

        rooturl = misc.make_script_url(task='reports', sortby=sortby_type,
            order=sortby_dir, _amp=True)

        Template.__init__(self, 'report_panel_template',
                          reports=res.rows,
                          sortby=sortby_type,
                          order=sortby_dir,
                          number_of_pages=res.total_pages,
                          rowcount=res.total_entries,
                          inputs=inputs,
                          rooturl=rooturl)
コード例 #26
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_sql_interface_panel(self, sql="", nuke=""):
        if self.user.account != staff.ADMIN:
            raise WakaError(strings.INSUFFICIENTPRIVILEGES)

        results = []

        if sql or nuke:
            if nuke != local.environ["waka.board"].options["NUKE_PASS"]:
                raise WakaError(strings.WRONGPASS)

            session = model.Session()
            if sql:
                for sql in sql.split("\r\n"):
                    # Execute teh string.
                    try:
                        results.append(">>> " + sql)
                        row = session.execute(sql)
                    except Exception as errstr:
                        results.append("ERROR: %s" % (errstr))
                    else:
                        try:
                            results.append(str(row.fetchall()))
                        except:
                            results.append("OK")
            else:
                # Remove board table contents and board list entry.
                try:
                    board = local.environ["waka.board"]
                    board.table.drop(bind=model.engine, checkfirst=True)
                    del model._boards[board.name]
                    model.common.delete().where(model.common.c.board == board.name)
                except Exception as errstr:
                    results.append("ERROR %s" % (errstr))
                else:
                    results.append("Comment table dropped. You should " "delete/move the board folder now.")
        else:
            results.append(
                "Leave textarea blank to delete the board.\n\n"
                "(It is recommended that you disable site access "
                "while entering SQL or deleting boards.)"
            )

        Template.__init__(self, "sql_interface_template", results="<br />".join(results))
コード例 #27
0
 def generateGroupedIeDataType(grpIeDetails, grpIe):
     grpIeInfo={}
     
     grpIeInfo['iePresenceList']=[]
     grpIeTypeInfo={}
     grpIeTypeInfo['grpIeTypeName']=grpIe + 'IeType'
     grpIeTypeInfo['grpIeTypeValue']=grpIeDetails['ieTypeValue']
     if grpIeTypeInfo not in grpIeDataTypeData['grpTypeList']:
         grpIeDataTypeData['grpTypeList'].append(grpIeTypeInfo)
     
     for inst in grpIeDetails['instList']:
         
         instDetails  = grpIeDetails[inst]
         grpIeInfo={}
         grpIeInfo['iePresenceList']=[]
         grpIeInfo['grpIeName']= inst+'Data'
         grpIeInfo['ieList']=[]
         for ieDict in instDetails['ieDetails']:
             for ieDetails in ieDict:
                 if ieDict[ieDetails]['presence']!='M':
                     grpIeInfo['iePresenceList'].append(ieDict[ieDetails]['ieVarName']+'IePresent')
                 ieInfo={}
                 ieInfo['ieTypeName']=ieDict[ieDetails]['ieTypeName']+'IeData'
                 ieInfo['ieVarName']=ieDict[ieDetails]['ieVarName']
                 ieInfo['ieCardinality'] = ieDict[ieDetails]['cardinality']
                 ieInfo['grouped'] = ieDict[ieDetails]['grouped']
                 if ieInfo['grouped']=='Yes':
                     ieInfo['grpIeInstClassName'] =ieDict[ieDetails]['ieGroupTypeName'][0].upper()+ieDict[ieDetails]['ieGroupTypeName'][1:]
                    
                 grpIeInfo['ieList'].append(ieInfo)
     
     if grpIeInfo not in grpIeDataTypeData['grpList']:
         grpIeDataTypeData['grpList'].append(grpIeInfo)
     template = Template()
     ttFileNamefactoryH = 'tts/grpIeDataTypetemplate.h.tt'
     outputDir = '../../src/gtpV2Codec/ieClasses/'
     
     if not os.path.exists(outputDir):
         os.makedirs(outputDir)
     outputFileName = 'gtpV2GrpIeDataTypes.h'
     template.__init__({'OUTPUT' : outputFileName, 'OUTPUT_PATH' : outputDir})
     template.process(ttFileNamefactoryH, {'tempdata' : grpIeDataTypeData})
コード例 #28
0
    def make_ban_edit_popup(self, num):
        session = model.Session()
        table = model.admin
        sql = table.select().where(table.c.num == num)
        row = session.execute(sql).fetchone()

        if row.expiration:
            expiration = datetime.utcfromtimestamp(row.expiration)
        else:
            expiration = datetime.utcnow()

        Template.__init__(self,
                          'edit_window',
                          hash=[row],
                          year=expiration.year,
                          month=expiration.month,
                          day=expiration.day,
                          hour=expiration.hour,
                          min=expiration.minute,
                          sec=expiration.second)
コード例 #29
0
    def make_admin_script_security_panel(self):
        session = model.Session()
        table = model.passprompt
        rows = session.execute(table.select())

        now = time.time()

        entries = []
        for row in rows:
            row = dict(row)
            if row['passfail']:
                row['expiration']\
                    = config.PASSFAIL_ROLLBACK - now + row['timestamp']
            else:
                row['expiration']\
                    = config.PASSPROMPT_EXPIRE_TO_FAILURE - now \
                      + row['timestamp']
            entries.append(row)

        Template.__init__(self, 'script_security_panel', entries=entries)
コード例 #30
0
ファイル: iECodeGen.py プロジェクト: zhuzhiyu0220/openmme
    def generateIeDataType(self, currentType, typeVal, varList):
        ieinfo = {}
        ieTypeInfo = {}
        ieinfo['ieName'] = currentType + 'IeData'
        ieinfo['varList'] = varList
        ieTypeInfo['ieName'] = currentType + 'IeType'
        ieTypeInfo['value'] = typeVal
        if ieinfo not in ieDataTypeData['ieList']:
            ieDataTypeData['ieList'].append(ieinfo)
        if ieTypeInfo not in ieDataTypeData['ieTypeList']:
            ieDataTypeData['ieTypeList'].append(ieTypeInfo)
        #print(ieDataTypeData)
        template = Template()
        ttFileNamefactoryH = 'tts/ieDataTypetemplate.h.tt'
        outputDir = '../../src/gtpV2Codec/ieClasses'

        if not os.path.exists(outputDir):
            os.makedirs(outputDir)
        outputFileName = 'gtpV2IeDataTypes.h'
        template.__init__({'OUTPUT': outputFileName, 'OUTPUT_PATH': outputDir})
        template.process(ttFileNamefactoryH, {'tempdata': ieDataTypeData})
コード例 #31
0
    def __init__(self,lst,master,userr_coll,userr_name):
        self.userr_coll = userr_coll
        self.userr_name = userr_name
        self.master = master
        self.lst = []
        Template.__init__(self, self.lst, self.master)


        self.master.title('movies')
        self.key = -1
        try:
            self.client = pymongo.MongoClient("localhost",27017)
            self.db = self.client
        except Exception as e:
            messagebox.showinfo("Info", e)

        self.d = self.db.sample_mflix.movies.aggregate([{'$project': {'title': 1}}])

        for dic in self.d:
            self.lst.append(dic['title'])
        self.movie_list = []
        self.names_list = list(self.userr_coll.find({}))[0]['recommanded']
        for i in range(10):
            self.dict = self.db.sample_mflix.movies.aggregate([{'$match': {'title': f'{self.names_list[i]}'}}, {'$limit': 10}])
            try:
                url = list(self.dict)[0]['poster']
            except:
                url = 'https://m.media-amazon.com/images/M/MV5BYzk0YWQzMGYtYTM5MC00NjM2LWE5YzYtMjgyNDVhZDg1N2YzXkEyXkFqcGdeQXVyMzE0MjY5ODA@._V1_SY1000_SX677_AL_.jpg'
            page = requests.get(url)
            load = Image.open(io.BytesIO(page.content))
            load = load.resize((200, 70), Image.ANTIALIAS)
            self.movie_list.append(load)
        self.update_list()
        self.dict = self.userr_coll.aggregate([{'$match': {'_id': self.userr_name}}])
        x = list(self.dict)[0]

        docs = x['movie']
        if len(docs)==0:
            c = userinfo(self.master,self.lst,self.userr_coll,self.userr_name)
コード例 #32
0
ファイル: xlUtils.py プロジェクト: sauravpkr/Nucleus
    def templateProcess(templateData, ttFileNameCpp, ttFileNameH, outputDirCpp,
                        outputDirH):

        template = Template()

        if not os.path.exists(outputDirCpp):
            os.makedirs(outputDirCpp)
        outputFileNameCpp = templateData['fileName'] + '.cpp'

        template.__init__({
            'OUTPUT': outputFileNameCpp,
            'OUTPUT_PATH': outputDirCpp
        })
        template.process(ttFileNameCpp, {'tempdata': templateData})

        if not os.path.exists(outputDirH):
            os.makedirs(outputDirH)
        outputFileNameH = templateData['fileName'] + '.h'
        template.__init__({
            'OUTPUT': outputFileNameH,
            'OUTPUT_PATH': outputDirH
        })
        template.process(ttFileNameH, {'tempdata': templateData})
コード例 #33
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_activity_panel(
        self,
        view="",
        user_to_view=None,
        action_to_view=None,
        ip_to_view=None,
        post_to_view=None,
        sortby_name="date",
        sortby_dir="desc",
    ):

        board = self.board

        template_view = "staff_activity_unfiltered"
        action_name = action_content = ""

        table = model.activity
        account_table = model.account

        dual_table_select = [
            account_table.c.username,
            account_table.c.account,
            account_table.c.disabled,
            table.c.action,
            table.c.info,
            table.c.date,
            table.c.ip,
        ]
        sql = select(
            dual_table_select, from_obj=[table.join(account_table, table.c.username == model.account.c.username)]
        )

        rooturl_args = dict(
            task="stafflog", board=board.name, view=view, sortby=sortby_name, order=sortby_dir, _amp=True
        )

        if view == "user":
            if not user_to_view:
                raise WakaError("Please select a user to view.")
            template_view = "staff_activity_by_user"
            sql = sql.where(table.c.username == user_to_view)
            rooturl_args["usertoview"] = user_to_view

        elif view == "action":
            if not action_to_view:
                raise WakaError("Please select an action to view.")
            template_view = "staff_activity_by_actions"
            (action_name, action_content) = staff_tasks.get_action_name(action_to_view, 1)
            sql = sql.where(table.c.action == action_to_view)
            rooturl_args["actiontoview"] = action_to_view

        elif view == "ip":
            if not ip_to_view:
                raise WakaError("Please specify an IP address to view.")
            template_view = "staff_activity_by_ip_address"
            sql = sql.where(table.c.info.like("%" + ip_to_view + "%"))
            rooturl_args["iptoview"] = ip_to_view

        elif view == "post":
            if not post_to_view:
                raise WakaError("Post key missing.")
            template_view = "staff_activity_by_post"
            sql = sql.where(table.c.info.like("%" + post_to_view + "%"))
            rooturl_args["posttoview"] = post_to_view

        rooturl = misc.make_script_url(**rooturl_args)

        # Acquire staff info.
        session = model.Session()
        staff_get = model.account.select()
        staff = session.execute(staff_get).fetchall()

        # Establish list of hidden inputs.
        inputs = [
            {"name": "actiontoview", "value": action_to_view},
            {"name": "task", "value": "stafflog"},
            {"name": "posttoview", "value": post_to_view},
            {"name": "usertoview", "value": user_to_view},
            {"name": "iptoview", "value": ip_to_view},
            {"name": "order", "value": sortby_dir},
            {"name": "sortby", "value": sortby_name},
            {"name": "view", "value": view},
        ]

        if self.board:
            inputs.append({"name": "board", "value": self.board.name})

        # Apply sorting.
        if sortby_name and hasattr(table.c, sortby_name):
            order_col = getattr(table.c, sortby_name)
            if sortby_dir.lower() == "asc":
                sort_spec = order_col.asc()
            else:
                sort_spec = order_col.desc()
            sql = sql.order_by(sort_spec)

        res = model.Page(sql, self.page, self.perpage)

        Template.__init__(
            self,
            template_view,
            user_to_view=user_to_view,
            entries=res.rows,
            staff=staff,
            rowcount=res.total_entries,
            numberofpages=res.total_pages,
            view=view,
            order=sortby_dir,
            action_name=action_name,
            content_name=action_content,
            sortby=sortby_name,
            number_of_pages=res.total_pages,
            rooturl=rooturl,
            inputs=inputs,
        )
コード例 #34
0
    def make_admin_post_search_panel(self, search, text, caller='internal'):
        board = self.board
        session = model.Session()
        table = board.table

        board.check_access(self.user)

        popup = caller != 'board'

        if search.find('IP Address') != -1:
            try:
                sql = table.select()\
                           .where(table.c.ip == misc.dot_to_dec(text))
            except ValueError:
                raise WakaError('Please enter a valid IP.')
            search_type = 'IP'
        elif search.find('Text String') != -1:
            sql = table.select().where(table.c.comment.like('%' + text + '%'))
            search_type = 'text string'
        elif search.find('Author') != -1:
            sql = table.select().where(
                or_(table.c.name.like('%' + text + '%'),
                    table.c.trip.like('%' + text + '%')))
            search_type = 'author'
        else:
            sql = table.select().where(table.c.num == text)
            search_type = 'ID'

        if search_type != 'ID':
            page = model.Page(sql, self.page, self.perpage)
            rowcount = page.total_entries
            total_pages = page.total_pages
            posts = page.rows
            if not posts:
                raise WakaError("No posts found for %s %s" %
                                (search_type, text))
        else:
            rowcount = total_pages = 1
            row = session.execute(sql).fetchone()
            if not row:
                raise WakaError("Post not found. (It may have just been"
                                " deleted.)")
            posts = [row]

        inputs = [{
            'name': 'board',
            'value': board.name
        }, {
            'name': 'task',
            'value': 'searchposts'
        }, {
            'name': 'text',
            'value': text
        }, {
            'name': 'caller',
            'value': caller
        }, {
            'name': 'search',
            'value': search
        }]

        rooturl = misc.make_script_url(task='searchposts',
                                       board=board.name,
                                       caller=caller,
                                       search=search,
                                       text=text,
                                       _amp=True)

        Template.__init__(self,
                          'post_search',
                          num=id,
                          posts=posts,
                          search=search,
                          text=text,
                          inputs=inputs,
                          number_of_pages=total_pages,
                          rooturl=rooturl,
                          rowcount=rowcount,
                          popup=popup)
コード例 #35
0
ファイル: pymol.py プロジェクト: berquist/fragit-main
 def __init__(self, infile, outfile):
     Template.__init__(self, infile, outfile)
     self._setTemplateType("pymol")
     self._setLoadStructureString("cmd.do(\"load %s\")")
コード例 #36
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_post_search_panel(self, search, text, caller="internal"):
        board = self.board
        session = model.Session()
        table = board.table

        self.user.check_access(board.name)

        popup = caller != "board"

        if search.find("IP Address") != -1:
            try:
                sql = table.select().where(table.c.ip == misc.dot_to_dec(text))
            except ValueError:
                raise WakaError("Please enter a valid IP.")
            search_type = "IP"
        elif search.find("Text String") != -1:
            sql = table.select().where(table.c.comment.like("%" + text + "%"))
            search_type = "text string"
        elif search.find("Author") != -1:
            sql = table.select().where(or_(table.c.name.like("%" + text + "%"), table.c.trip.like("%" + text + "%")))
            search_type = "author"
        else:
            sql = table.select().where(table.c.num == text)
            search_type = "ID"

        if search_type != "ID":
            page = model.Page(sql, self.page, self.perpage)
            rowcount = page.total_entries
            total_pages = page.total_pages
            posts = page.rows
            if not posts:
                raise WakaError("No posts found for %s %s" % (search_type, text))
        else:
            rowcount = total_pages = 1
            row = session.execute(sql).fetchone()
            if not row:
                raise WakaError("Post not found. (It may have just been" " deleted.)")
            posts = [row]

        inputs = [
            {"name": "board", "value": board.name},
            {"name": "task", "value": "searchposts"},
            {"name": "text", "value": text},
            {"name": "caller", "value": caller},
            {"name": "search", "value": search},
        ]

        rooturl = misc.make_script_url(
            task="searchposts", board=board.name, caller=caller, search=search, text=text, _amp=True
        )

        Template.__init__(
            self,
            "post_search",
            num=id,
            posts=posts,
            search=search,
            text=text,
            inputs=inputs,
            number_of_pages=total_pages,
            rooturl=rooturl,
            rowcount=rowcount,
            popup=popup,
        )
コード例 #37
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
 def make_del_staff_window(self, username):
     Template.__init__(self, "staff_delete_template", user_to_delete=username)
コード例 #38
0
 def make_ban_popup(self, ip, delete=''):
     Template.__init__(self, 'ban_window', ip=ip, delete=delete)
コード例 #39
0
 def __init__(self):
     Template.__init__(self, Template.TEMPLATE_PREFIX, "<PREFIX>")
コード例 #40
0
 def make_enable_staff_window(self, username):
     Template.__init__(self,
                       'staff_enable_template',
                       user_to_enable=username)
コード例 #41
0
 def make_del_staff_window(self, username):
     Template.__init__(self,
                       'staff_delete_template',
                       user_to_delete=username)
コード例 #42
0
    def make_admin_activity_panel(self, view='', user_to_view=None,
                                  action_to_view=None, ip_to_view=None,
                                  post_to_view=None, sortby_name='date',
                                  sortby_dir='desc'):

        board = self.board

        template_view = 'staff_activity_unfiltered'
        action_name = action_content = ''

        table = model.activity
        account_table = model.account
        
        dual_table_select = [account_table.c.username,
                             account_table.c.account,
                             account_table.c.disabled,
                             table.c.action,
                             table.c.info,
                             table.c.date,
                             table.c.ip]
        sql = select(dual_table_select,
                     from_obj=[table.join(account_table,
                     table.c.username == model.account.c.username)])

        rooturl_args = dict(task='stafflog', board=board.name,
            view=view, sortby=sortby_name, order=sortby_dir, _amp=True)

        if view == 'user':
            if not user_to_view:
                raise WakaError('Please select a user to view.')
            template_view = 'staff_activity_by_user'
            sql = sql.where(table.c.username == user_to_view)
            rooturl_args['usertoview'] = user_to_view

        elif view == 'action':
            if not action_to_view:
                raise WakaError('Please select an action to view.')
            template_view = 'staff_activity_by_actions'
            (action_name, action_content) \
                = staff_tasks.get_action_name(action_to_view, 1)
            sql = sql.where(table.c.action == action_to_view)
            rooturl_args['actiontoview'] = action_to_view

        elif view == 'ip':
            if not ip_to_view:
                raise WakaError('Please specify an IP address to view.')
            template_view = 'staff_activity_by_ip_address'
            sql = sql.where(table.c.info.like('%' + ip_to_view + '%'))
            rooturl_args['iptoview'] = ip_to_view

        elif view == 'post':
            if not post_to_view:
                raise WakaError('Post key missing.')
            template_view = 'staff_activity_by_post'
            sql = sql.where(table.c.info.like('%' + post_to_view + '%'))
            rooturl_args['posttoview'] = post_to_view

        rooturl = misc.make_script_url(**rooturl_args)

        # Acquire staff info.
        session = model.Session()
        staff_get = model.account.select()
        staff = session.execute(staff_get).fetchall()

        # Establish list of hidden inputs.
        inputs = [
            {'name' : 'actiontoview', 'value' : action_to_view},
            {'name' : 'task', 'value' : 'stafflog'},
            {'name' : 'posttoview', 'value' : post_to_view},
            {'name' : 'usertoview', 'value' : user_to_view},
            {'name' : 'iptoview', 'value' : ip_to_view},
            {'name' : 'order', 'value' : sortby_dir},
            {'name' : 'sortby', 'value' : sortby_name},
            {'name' : 'view', 'value': view}
        ]

        if self.board:
            inputs.append({'name' : 'board', 'value' : self.board.name})

        # Apply sorting.
        if sortby_name and hasattr(table.c, sortby_name):
            order_col = getattr(table.c, sortby_name)
            if sortby_dir.lower() == 'asc':
                sort_spec = order_col.asc()
            else:
                sort_spec = order_col.desc()
            sql = sql.order_by(sort_spec)

        res = model.Page(sql, self.page, self.perpage)

        Template.__init__(self, template_view,
                          user_to_view=user_to_view,
                          entries=res.rows,
                          staff=staff,
                          rowcount=res.total_entries,
                          numberofpages=res.total_pages,
                          view=view,
                          order=sortby_dir,
                          action_name=action_name,
                          content_name=action_content,
                          sortby=sortby_name,
                          number_of_pages=res.total_pages,
                          rooturl=rooturl,
                          inputs=inputs)
コード例 #43
0
    def make_admin_trash_panel(self):
        board = self.board
        table = model.backup
        session = model.Session()
        template_kwargs = {}

        # List of current threads *and* orphaned posts.
        threads = []

        if str(self.page).startswith('t'):
            self.page = self.page[1:]
            sql = table.select().where(and_(or_(table.c.postnum == self.page,
                                                table.c.parent == self.page),
                                            table.c.board_name == board.name))\
                                .order_by(table.c.timestampofarchival.desc(),
                                          table.c.postnum.asc())
            thread = [dict(x.items()) for x in session.execute(sql).fetchall()]

            if not thread:
                raise WakaError('Thread not found.')

            threads = [{'posts': thread}]

            template_kwargs = {
                'postform':
                board.options['ALLOW_TEXTONLY']
                or board.options['ALLOW_IMAGES'],
                'image_inp':
                board.options['ALLOW_IMAGES'],
                'textonly_inp':
                0,
                'threads':
                threads,
                'thread':
                self.page,
                'parent':
                self.page
            }

        elif config.POST_BACKUP:
            max_res = board.options['IMAGES_PER_PAGE']

            sqlcond = and_(
                or_(
                    table.c.parent == 0,
                    and_(
                        table.c.parent > 0,
                        not_(
                            exists([table.c.num],
                                   table.c.parent == table.c.postnum)))),
                table.c.board_name == board.name)

            # Acquire the number of full threads *and* orphaned posts.
            sql = select([func.count()], sqlcond, table)\
                  .order_by(table.c.timestampofarchival.desc(),
                              table.c.postnum.asc())

            thread_ct = session.execute(sql).fetchone()[0]

            total = int(thread_ct + max_res - 1) / max_res
            offset = self.page * max_res

            (pages, prevpage, nextpage) \
                = board.get_board_page_data(self.page, total,
                                            admin_page='postbackups')

            last_page = len(pages) - 1
            if self.page > last_page and last_page > 0:
                self.page = last_page

            sql = table.select().where(sqlcond)\
                  .order_by(table.c.timestampofarchival.desc(),
                              table.c.num.asc())\
                  .limit(board.options['IMAGES_PER_PAGE'])\
                  .offset(offset)
            threads = [{'posts' : [dict(x.items())]} \
                for x in session.execute(sql)]

            # Loop through 'posts' key in each dictionary in the threads
            # list.
            for item in threads:
                thread = item['posts']
                threadnum = thread[0]['postnum']
                postcount = imgcount = shownimages = 0

                # Orphaned?
                item['standalone'] = 0

                if not thread[0]['parent']:
                    sql = select(
                        [func.count(), func.count(table.c.image)],
                        table.c.parent == threadnum, table)

                    (postcount, imgcount) = session.execute(sql).fetchone()

                    max_res = board.options['REPLIES_PER_THREAD']
                    offset = postcount - imgcount if postcount > max_res \
                                                  else 0

                    sql = table.select().where(table.c.parent == threadnum)\
                            .order_by(table.c.timestampofarchival.desc(),
                                      table.c.postnum.asc())\
                            .limit(max_res)\
                            .offset(offset)
                    thread.extend([dict(x.items()) \
                                       for x in session.execute(sql)])

                else:
                    item['standalone'] = 1

                for post in thread:
                    image_dir \
                        = os.path.join(board.path, board.options['IMG_DIR'])

                    thumb_dir \
                        = os.path.join(board.path, board.options['THUMB_DIR'])

                    base_thumb = os.path.basename(post['thumbnail'] or '')
                    base_image = os.path.basename(post['image'] or '')

                    base_filename = (post['image'] or '')\
                        .replace(image_dir, '').lstrip('/')

                    backup_dir = os.path.join(board.url,
                                              board.options['ARCHIVE_DIR'],
                                              board.options['BACKUP_DIR'])

                    if post['image']:
                        post['image'] = os.path.join(backup_dir, base_image)
                        shownimages += 1

                    if re.match(board.options['THUMB_DIR'], post['thumbnail']
                                or ''):
                        post['thumbnail'] \
                            = os.path.join(backup_dir, base_thumb)

                item['omit'] = postcount - max_res if postcount > max_res\
                                                   else 0

                item['omitimages'] = imgcount - shownimages \
                                     if imgcount > shownimages else 0

                template_kwargs = {'postform' \
                                      : board.options['ALLOW_TEXTONLY'] or
                                        board.options['ALLOW_IMAGES'],
                                  'image_inp' : board.options['ALLOW_IMAGES'],
                                   'textonly_inp' \
                                      : board.options['ALLOW_IMAGES'] and
                                        board.options['ALLOW_TEXTONLY'],
                                   'nextpage' : nextpage,
                                   'prevpage' : prevpage,
                                   'threads' : threads,
                                   'pages' : pages}

        Template.__init__(self, 'backup_panel_template', **template_kwargs)
コード例 #44
0
ファイル: pymol.py プロジェクト: berquist/fragit-main
	def __init__(self,infile,outfile):
		Template.__init__(self,infile,outfile)
		self._setTemplateType("pymol")
		self._setLoadStructureString("cmd.do(\"load %s\")")
コード例 #45
0
ファイル: prefixtemplate.py プロジェクト: aspiers/Fail2Ban
	def __init__(self):
		Template.__init__(self, Template.TEMPLATE_PREFIX, "<PREFIX>")
コード例 #46
0
 def make_ban_popup(self, ip, delete=''):
     Template.__init__(self, 'ban_window', ip=ip, delete=delete)
コード例 #47
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
 def make_ban_popup(self, ip, delete=""):
     Template.__init__(self, "ban_window", ip=ip, delete=delete)
コード例 #48
0
 def make_disable_staff_window(self, username):
     Template.__init__(self, 'staff_disable_template',
                             user_to_disable=username)
コード例 #49
0
 def __init__(self):
     Template.__init__(self, Template.TEMPLATE_TIME, "<TIME>")
コード例 #50
0
    def make_admin_trash_panel(self):
        board = self.board
        table = model.backup
        session = model.Session()
        template_kwargs = {}

        # List of current threads *and* orphaned posts.
        threads = []

        if str(self.page).startswith('t'):
            self.page = self.page[1:]
            sql = table.select().where(and_(or_(table.c.postnum == self.page,
                                                table.c.parent == self.page),
                                            table.c.board_name == board.name))\
                                .order_by(table.c.timestampofarchival.desc(),
                                          table.c.postnum.asc())
            thread = [dict(x.items()) for x in session.execute(sql).fetchall()]

            if not thread:
                raise WakaError('Thread not found.')

            threads = [{'posts' : thread}]

            template_kwargs = {
                'postform' : board.options['ALLOW_TEXTONLY'] or
                             board.options['ALLOW_IMAGES'],
                'image_inp' : board.options['ALLOW_IMAGES'],
                'textonly_inp' : 0,
                'threads' : threads,
                'thread' : self.page,
                'parent' : self.page
            }

        elif config.POST_BACKUP:
            max_res = board.options['IMAGES_PER_PAGE']

            sqlcond = and_(or_(table.c.parent == 0,
                and_(table.c.parent > 0, not_(exists([table.c.num],
                    table.c.parent == table.c.postnum)))),
                table.c.board_name == board.name)

            # Acquire the number of full threads *and* orphaned posts.
            sql = select([func.count()], sqlcond, table)\
                  .order_by(table.c.timestampofarchival.desc(),
                              table.c.postnum.asc())

            thread_ct = session.execute(sql).fetchone()[0]

            total = int(thread_ct + max_res - 1) / max_res
            offset = self.page * max_res

            (pages, prevpage, nextpage) \
                = board.get_board_page_data(self.page, total,
                                            admin_page='postbackups')

            last_page = len(pages) - 1
            if self.page > last_page and last_page > 0:
                self.page = last_page

            sql = table.select().where(sqlcond)\
                  .order_by(table.c.timestampofarchival.desc(),
                              table.c.num.asc())\
                  .limit(board.options['IMAGES_PER_PAGE'])\
                  .offset(offset)
            threads = [{'posts' : [dict(x.items())]} \
                for x in session.execute(sql)]

            # Loop through 'posts' key in each dictionary in the threads
            # list.
            for item in threads:
                thread = item['posts']
                threadnum = thread[0]['postnum']
                postcount = imgcount = shownimages = 0

                # Orphaned?
                item['standalone'] = 0

                if not thread[0]['parent']:
                    sql = select([func.count(), func.count(table.c.image)],
                                  table.c.parent == threadnum,
                                  table)

                    (postcount, imgcount) = session.execute(sql).fetchone()

                    max_res = board.options['REPLIES_PER_THREAD']
                    offset = postcount - imgcount if postcount > max_res \
                                                  else 0

                    sql = table.select().where(table.c.parent == threadnum)\
                            .order_by(table.c.timestampofarchival.desc(),
                                      table.c.postnum.asc())\
                            .limit(max_res)\
                            .offset(offset)
                    thread.extend([dict(x.items()) \
                                       for x in session.execute(sql)])

                else:
                    item['standalone'] = 1

                for post in thread:
                    image_dir \
                        = os.path.join(board.path, board.options['IMG_DIR'])

                    thumb_dir \
                        = os.path.join(board.path, board.options['THUMB_DIR'])

                    base_thumb = os.path.basename(post['thumbnail'] or '')
                    base_image = os.path.basename(post['image'] or '')

                    base_filename = (post['image'] or '')\
                        .replace(image_dir, '').lstrip('/')

                    backup_dir = os.path.join(board.url,
                                              board.options['ARCHIVE_DIR'],
                                              board.options['BACKUP_DIR'])

                    if post['image']:
                        post['image'] = os.path.join(backup_dir, base_image)
                        shownimages += 1

                    if re.match(board.options['THUMB_DIR'],
                                post['thumbnail'] or ''):
                        post['thumbnail'] \
                            = os.path.join(backup_dir, base_thumb)
                
                item['omit'] = postcount - max_res if postcount > max_res\
                                                   else 0

                item['omitimages'] = imgcount - shownimages \
                                     if imgcount > shownimages else 0

                template_kwargs = {'postform' \
                                      : board.options['ALLOW_TEXTONLY'] or
                                        board.options['ALLOW_IMAGES'],
                                  'image_inp' : board.options['ALLOW_IMAGES'],
                                   'textonly_inp' \
                                      : board.options['ALLOW_IMAGES'] and
                                        board.options['ALLOW_TEXTONLY'],
                                   'nextpage' : nextpage,
                                   'prevpage' : prevpage,
                                   'threads' : threads,
                                   'pages' : pages}

        Template.__init__(self, 'backup_panel_template', **template_kwargs)
コード例 #51
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
 def make_enable_staff_window(self, username):
     Template.__init__(self, "staff_enable_template", user_to_enable=username)
コード例 #52
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
 def make_admin_proxy_panel(self):
     Template.__init__(self, "proxy_panel_template")
コード例 #53
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
    def make_admin_trash_panel(self):
        board = self.board
        table = model.backup
        session = model.Session()
        template_kwargs = {}

        # List of current threads *and* orphaned posts.
        threads = []

        if str(self.page).startswith("t"):
            self.page = self.page[1:]
            sql = (
                table.select()
                .where(
                    and_(
                        or_(table.c.postnum == self.page, table.c.parent == self.page), table.c.board_name == board.name
                    )
                )
                .order_by(table.c.timestampofarchival.desc(), table.c.postnum.asc())
            )
            thread = [dict(x.items()) for x in session.execute(sql).fetchall()]

            if not thread:
                raise WakaError("Thread not found.")

            threads = [{"posts": thread}]

            template_kwargs = {
                "postform": board.options["ALLOW_TEXTONLY"] or board.options["ALLOW_IMAGES"],
                "image_inp": board.options["ALLOW_IMAGES"],
                "textonly_inp": 0,
                "threads": threads,
                "thread": self.page,
                "parent": self.page,
            }

        elif config.POST_BACKUP:
            max_res = board.options["IMAGES_PER_PAGE"]

            sqlcond = and_(
                or_(
                    table.c.parent == 0,
                    and_(table.c.parent > 0, not_(exists([table.c.num], table.c.parent == table.c.postnum))),
                ),
                table.c.board_name == board.name,
            )

            # Acquire the number of full threads *and* orphaned posts.
            sql = select([func.count()], sqlcond, table).order_by(
                table.c.timestampofarchival.desc(), table.c.postnum.asc()
            )

            thread_ct = session.execute(sql).fetchone()[0]

            total = int(thread_ct + max_res - 1) / max_res
            offset = self.page * max_res

            (pages, prevpage, nextpage) = board.get_board_page_data(self.page, total, admin_page="postbackups")

            last_page = len(pages) - 1
            if self.page > last_page and last_page > 0:
                self.page = last_page

            sql = (
                table.select()
                .where(sqlcond)
                .order_by(table.c.timestampofarchival.desc(), table.c.num.asc())
                .limit(board.options["IMAGES_PER_PAGE"])
                .offset(offset)
            )
            threads = [{"posts": [dict(x.items())]} for x in session.execute(sql)]

            # Loop through 'posts' key in each dictionary in the threads
            # list.
            for item in threads:
                thread = item["posts"]
                threadnum = thread[0]["postnum"]
                postcount = imgcount = shownimages = 0

                # Orphaned?
                item["standalone"] = 0

                if not thread[0]["parent"]:
                    sql = select([func.count(), func.count(table.c.image)], table.c.parent == threadnum, table)

                    (postcount, imgcount) = session.execute(sql).fetchone()

                    max_res = board.options["REPLIES_PER_THREAD"]
                    offset = postcount - imgcount if postcount > max_res else 0

                    sql = (
                        table.select()
                        .where(table.c.parent == threadnum)
                        .order_by(table.c.timestampofarchival.desc(), table.c.postnum.asc())
                        .limit(max_res)
                        .offset(offset)
                    )
                    thread.extend([dict(x.items()) for x in session.execute(sql)])

                else:
                    item["standalone"] = 1

                for post in thread:
                    # image_dir \
                    #    = os.path.join(board.path, board.options['IMG_DIR'])

                    # thumb_dir \
                    #    = os.path.join(board.path, board.options['THUMB_DIR'])

                    base_thumb = os.path.basename(post["thumbnail"] or "")
                    base_image = os.path.basename(post["image"] or "")

                    # base_filename = (post['image'] or '')\
                    #    .replace(image_dir, '').lstrip('/')

                    backup_dir = os.path.join(board.url, board.options["ARCHIVE_DIR"], board.options["BACKUP_DIR"])

                    if post["image"]:
                        post["image"] = os.path.join(backup_dir, base_image)
                        shownimages += 1

                    if re.match(board.options["THUMB_DIR"], post["thumbnail"] or ""):
                        post["thumbnail"] = os.path.join(backup_dir, base_thumb)

                item["omit"] = postcount - max_res if postcount > max_res else 0

                item["omitimages"] = imgcount - shownimages if imgcount > shownimages else 0

                template_kwargs = {
                    "postform": board.options["ALLOW_TEXTONLY"] or board.options["ALLOW_IMAGES"],
                    "image_inp": board.options["ALLOW_IMAGES"],
                    "textonly_inp": board.options["ALLOW_IMAGES"] and board.options["ALLOW_TEXTONLY"],
                    "nextpage": nextpage,
                    "prevpage": prevpage,
                    "threads": threads,
                    "pages": pages,
                }

        Template.__init__(self, "backup_panel_template", **template_kwargs)
コード例 #54
0
ファイル: staff_interface.py プロジェクト: dequis/wakarimasen
 def make_delete_all_window(self, **kwargs):
     Template.__init__(self, "delete_crap_confirm", **kwargs)
コード例 #55
0
    def make_admin_activity_panel(self,
                                  view='',
                                  user_to_view=None,
                                  action_to_view=None,
                                  ip_to_view=None,
                                  post_to_view=None,
                                  sortby_name='date',
                                  sortby_dir='desc'):

        board = self.board

        template_view = 'staff_activity_unfiltered'
        action_name = action_content = ''

        table = model.activity
        account_table = model.account

        dual_table_select = [
            account_table.c.username, account_table.c.account,
            account_table.c.disabled, table.c.action, table.c.info,
            table.c.date, table.c.ip
        ]
        sql = select(dual_table_select,
                     from_obj=[
                         table.join(
                             account_table,
                             table.c.username == model.account.c.username)
                     ])

        rooturl_args = dict(task='stafflog',
                            board=board.name,
                            view=view,
                            sortby=sortby_name,
                            order=sortby_dir,
                            _amp=True)

        if view == 'user':
            if not user_to_view:
                raise WakaError('Please select a user to view.')
            template_view = 'staff_activity_by_user'
            sql = sql.where(table.c.username == user_to_view)
            rooturl_args['usertoview'] = user_to_view

        elif view == 'action':
            if not action_to_view:
                raise WakaError('Please select an action to view.')
            template_view = 'staff_activity_by_actions'
            (action_name, action_content) \
                = staff_tasks.get_action_name(action_to_view, 1)
            sql = sql.where(table.c.action == action_to_view)
            rooturl_args['actiontoview'] = action_to_view

        elif view == 'ip':
            if not ip_to_view:
                raise WakaError('Please specify an IP address to view.')
            template_view = 'staff_activity_by_ip_address'
            sql = sql.where(table.c.info.like('%' + ip_to_view + '%'))
            rooturl_args['iptoview'] = ip_to_view

        elif view == 'post':
            if not post_to_view:
                raise WakaError('Post key missing.')
            template_view = 'staff_activity_by_post'
            sql = sql.where(table.c.info.like('%' + post_to_view + '%'))
            rooturl_args['posttoview'] = post_to_view

        rooturl = misc.make_script_url(**rooturl_args)

        # Acquire staff info.
        session = model.Session()
        staff_get = model.account.select()
        staff = session.execute(staff_get).fetchall()

        # Establish list of hidden inputs.
        inputs = [{
            'name': 'actiontoview',
            'value': action_to_view
        }, {
            'name': 'task',
            'value': 'stafflog'
        }, {
            'name': 'posttoview',
            'value': post_to_view
        }, {
            'name': 'usertoview',
            'value': user_to_view
        }, {
            'name': 'iptoview',
            'value': ip_to_view
        }, {
            'name': 'order',
            'value': sortby_dir
        }, {
            'name': 'sortby',
            'value': sortby_name
        }, {
            'name': 'view',
            'value': view
        }]

        if self.board:
            inputs.append({'name': 'board', 'value': self.board.name})

        # Apply sorting.
        if sortby_name and hasattr(table.c, sortby_name):
            order_col = getattr(table.c, sortby_name)
            if sortby_dir.lower() == 'asc':
                sort_spec = order_col.asc()
            else:
                sort_spec = order_col.desc()
            sql = sql.order_by(sort_spec)

        res = model.Page(sql, self.page, self.perpage)

        Template.__init__(self,
                          template_view,
                          user_to_view=user_to_view,
                          entries=res.rows,
                          staff=staff,
                          rowcount=res.total_entries,
                          numberofpages=res.total_pages,
                          view=view,
                          order=sortby_dir,
                          action_name=action_name,
                          content_name=action_content,
                          sortby=sortby_name,
                          number_of_pages=res.total_pages,
                          rooturl=rooturl,
                          inputs=inputs)
コード例 #56
0
 def make_delete_all_window(self, **kwargs):
     Template.__init__(self, 'delete_crap_confirm', **kwargs)
コード例 #57
0
    def __init__(self, master, lst, userr_coll,userr_name):

        self.lst = master
        self.master = lst
        Template.__init__(self, self.master,self.lst)

        self.userr_name = userr_name
        self.userr_coll = userr_coll
        self.l = [{}]
        try:
            self.client = pymongo.MongoClient("localhost",27017)
            self.db = self.client
        except Exception as e:
            messagebox.showinfo("Info", e)

        self.d = self.db.sample_mflix.movies.aggregate([{'$project': {'title': 1}}])

        for dic in self.d:
            self.lst.append(dic['title'])



        self.title('user_info')
        self.geometry('700x500+300+100')
        self.top = Frame(self, height = 50,width = 700, bg='#5e615e')
        self.top.pack()
        myfont = Font(family='Ink Free', size=35, weight='bold')
        self.label = Label(self.top, text='For User Info', bg='#5e615e', fg='#f1ff26', font=myfont)
        self.label.place(x=200, y=0)
        self.strip = Frame(self,height = 5,width = 700,bg = 'red')
        self.strip.pack()


        self.bottom = Frame(self,height = 390,width = 700,bg = '#2b2929')
        self.bottom.pack()

        self.strip = Frame(self, height=5, width=700, bg='red')
        self.strip.pack()
        self.footer = Frame(self, height=50, width=700, bg='#5e615e')
        self.footer.pack()
        self.entrt = Frame(self.bottom, height=100, bg='grey')
        self.entrt.place(x=1200, y=500)
        self.entry = AutocompleteEntry(self.entrt)
        self.entry.set_completion_list(self.lst)
        self.entry.place(x=500, y=500)
        self.entry.focus_set()
        self.combo = AutocompleteCombobox(self.bottom, width=20, height=15, font="Verdana 25")
        self.combo.set_completion_list(self.lst)
        bigfont = Font(family="Helvetica", size=20)
        self.combo.option_add("*TCombobox*Listbox*Font", bigfont)
        self.combo.place(x=80, y=30)
        self.combo.focus_set()
        self.count = 0
        myfontm = Font(family='Ink Free', size=12, weight='bold')
        self.var = DoubleVar()
        self.scale = Scale(self.bottom, variable=self.var, activebackground='black', cursor='arrow', from_=10, to=0,
                      resolution=0.1, sliderlength=15, troughcolor='grey', bg='#2b2929', fg='white', length=150, bd=0,
                      relief=RAISED)
        self.scale.place(x=580, y=30)
        

        p = 0
        for i in 'Rate Here':
            l= Label(self.bottom,text = i,font = myfontm,bg = '#2b2929',fg = '#f1ff26')
            l.place(x = 635,y = 23+p*18)
            p+=1

        self.button1 = Button(self.bottom, text='Search', font="Verdana 13", command=self.Search)

        self.button1.place(x=240, y=85)
        self.button2 = Button(self.footer, text='Submit',activebackground='#08fc6e', command=self.Submit)
        self.button2.place(x=600, y=15)
コード例 #58
0
 def __init__(self):
     Template.__init__(self, Template.TEMPLATE_TIME, "<TIME>")
コード例 #59
0
 def __init__(self, *args, **kwargs):
     Template.__init__(self, *args, **kwargs)
コード例 #60
0
 def make_admin_proxy_panel(self):
     Template.__init__(self, 'proxy_panel_template')