def delpost(n):
    uid = getUID()

    if request.method == "POST":
        pid = int(request.form["pid"])
        post = c.posts.Collections.find_one({"id":pid})
        
        if post:
            if admin(uid) and getThread(post['tid'])['pid'] != post['id']:
                utils.delpost(pid)
                if "ajax" in request.form:
                    return "/thread-%d?type=4"%(post['tid'])
                else:
                    return redirect("/thread-%d?type=51"%(post['tid']))
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.postDoesNotExist(),uid)
    else:
        r = ""
    
        post = c.posts.Collections.find_one({"id":int(n)})
        if post:
            if admin(uid) and getThread(post['tid'])['pid'] != post['id']:
                r += html.delpost(post["id"])
                return page(r,uid)
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.postDoesNotExist(),uid)
def edittitle(n):
    uid = getUID()

    if request.method == "POST":
        tid = int(request.form["tid"])
        thread = c.threads.Collections.find_one({"id":tid})
        
        if thread:
            if admin(uid):
                utils.edittitle(tid, request.form["title"], request.form["desc"])
                return redirect("/thread-%d?type=1"%(tid))
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.threadDoesNotExist(),uid)
    else:
        r = ""
    
        thread = c.threads.Collections.find_one({"id":int(n)})
        if thread:
            if admin(uid):
                r += html.edittitle(thread["id"])
                return page(r,uid)
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.threadDoesNotExist(),uid)
def delthread(n):
    uid = getUID()

    if request.method == "POST":
        tid = int(request.form["tid"])
        thread = c.threads.Collections.find_one({"id":tid})
        
        if thread:
            if admin(uid):
                utils.delthread(tid)
                if "ajax" in request.form:
                    return "/forum-%d?type=1"%(thread['fid'])
                else:
                    return redirect("/forum-%d?type=1"%(thread['fid']))
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.threadDoesNotExist(),uid)
    else:
        r = ""
    
        thread = c.threads.Collections.find_one({"id":int(n)})
        if thread:
            if admin(uid):
                r += html.delthread(thread["id"])
                return page(r,uid)
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.threadDoesNotExist(),uid)
def reply(n):
    uid = getUID()

    if uid == -1:
        return page(html.permissionDenied(),-1)
    if request.method == "POST":
        tid = int(request.form["tid"])
        thread = c.threads.Collections.find_one({"id":tid})
        
        if thread:
            if (not thread['hid'] and not thread['lock']) or admin(uid):
                utils.createPost(uid, tid, request.form["content"])
                return redirect("/thread-%d"%(tid))
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.threadDoesNotExist(),uid)
    else:
        r = ""
    
        thread = c.threads.Collections.find_one({"id":int(n)})
        if thread:
            if (not thread['hid'] and not thread['lock']) or admin(uid):
                r += html.reply(thread["id"])
                return page(r,uid)
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.threadDoesNotExist(),uid)
def post(uid,n):
    user = getUser(n["uid"])
    thread = getThread(n['tid'])
    n["username"] = user["username"]
    n["date"] = n["date"].strftime(DATE_FORMAT)

    n['className'] = "active"
    show = True
    if not n['hid'] or admin(uid):
        n["content"] = "<br />".join(cgi.escape(n["content"]).split("\n"))
    else:
        show = False
        n["content"] = "This post has been hidden by an administrator."
    if n['hid']:
        n['className'] = "danger"

    # allow editing abilities
    n['pleft'] = ""
    if uid == n["uid"] or admin(uid):
        n['pleft'] = '<a href="/editpost-%d" class="btn btn-primary">Edit</a>'%(n['id'])

    # admin buttons
    if admin(uid):
        # if it isn't the first post

         #   n['pleft'] += ' &nbsp; <a href="/delpost-%d" class="btn btn-danger">Delete</a>'%(n['id'])
#            n['pleft'] += '<br /><br /><a href="#">Hide</a> &nbsp; &nbsp; <a href="#">Delete</a>'
        if n['hid']:
            n['pleft'] += ' <a href="unhidepost-%d" class="btn btn-warning">Unhide</a>'%(n['id'])
        else:
            n['pleft'] += ' <a href="hidepost-%d" class="btn btn-warning">Hide</a>'%(n['id'])
        if n['id'] != thread['pid']:
            n['pleft'] += ' <a href="/delpost-%d" class="btn btn-danger deletePost">Delete</a>'%(n['id'])


    # show last post edit time
    if "editdate" in n.keys():
        n['editdate'] = " - Lasted edited on %s"%(n["editdate"].strftime(DATE_FORMAT))
        if n["edituid"] != n["uid"]:
            n['editdate'] += " by <strong>%s</strong>"%(getUser(n['edituid'])['username'])
    else:
        n['editdate'] = ""

    r = """
<table class="table p_post" cellspacing="0">
<tr class="%(className)s">
<td class="p_left">"""%(n)
    if show:
        r += '<div class="user"><a href="user/%(uid)d">%(username)s</a></div><div class="p_buttons">%(pleft)s</div>'%(n)
    r += """</td>
<td class="p_right"><div class="p_date">%(date)s %(editdate)s</div><div class="p_content">%(content)s</div></td>
</tr>
</table>"""%(n)
    

    return r
def get_latest_monday(options):
    url = "http://docs.house.gov/floor/"
    html = utils.download(url, None, options)
    doc = BeautifulSoup(html)

    links = doc.select("a.downloadXML")
    if len(links) != 1:
        utils.admin("Error finding download link for this week!")
        return None

    link = links[0]
    week = os.path.split(link['href'])[-1].split(".")[0]

    return week
示例#7
0
def get_latest_monday(options):
    url = "http://docs.house.gov/floor/"
    html = utils.download(url, None, options)
    doc = BeautifulSoup(html)

    links = doc.select("a.downloadXML")
    if len(links) != 1:
        utils.admin("Error finding download link for this week!")
        return None

    link = links[0]
    week = os.path.split(link['href'])[-1].split(".")[0]

    return week
示例#8
0
def get_latest_monday(options):
    # docs.house.gov always links to the most recent week that isn't in the future.
    url = "http://docs.house.gov/floor/"
    html = utils.download(url, None, options)
    doc = BeautifulSoup(html)

    links = doc.select("a.downloadXML")
    if len(links) != 1:
        utils.admin("There is no docs.house.gov download link --- maybe there are no upcoming bills.")
        return None

    link = links[0]
    week = os.path.split(link['href'])[-1].split(".")[0]
    week = datetime.strptime(week, "%Y%m%d").date()

    return week
示例#9
0
def get_latest_monday(options):
    # docs.house.gov always links to the most recent week that isn't in the future.
    url = "https://docs.house.gov/floor/"
    html = utils.download(url, None, options)
    doc = BeautifulSoup(html, features="lxml")

    links = doc.select("a.downloadXML")
    if len(links) != 1:
        utils.admin("There is no docs.house.gov download link --- maybe there are no upcoming bills.")
        return None

    link = links[0]
    week = os.path.split(link['href'])[-1].split(".")[0]
    week = datetime.strptime(week, "%Y%m%d").date()

    return week
示例#10
0
def get_latest_monday(options):
    url = "http://docs.house.gov/floor/"
    html = utils.download(url, None, options)
    doc = BeautifulSoup(html)

    links = doc.select("a.downloadXML")
    if len(links) != 1:
        utils.admin(
            "There is no docs.house.gov download link --- maybe there are no upcoming bills."
        )
        return None

    link = links[0]
    week = os.path.split(link['href'])[-1].split(".")[0]

    return week
示例#11
0
def sudo():
    '''
    Administrator access.
    '''
    password = request.args.get('password')
    if password is not None and password == 'xyzzyspoon!':
        return jsonify(admin(database))

    else:
        return jsonify({}), 403
示例#12
0
def sudo():
    '''
    Administrator access.
    '''
    password = request.args.get('password')
    if password is not None and password == 'xyzzyspoon!':
        return jsonify(admin(database))

    else:
        return jsonify({}), 403
def unlockthread(n):
    uid = getUID()

    thread = c.threads.Collections.find_one({"id":int(n)})
    if thread:
        if admin(uid):
            utils.unlockthread(thread['id'])
            return redirect("thread-%d?type=5"%(thread['id']))
        else:
            return page(html.permissionDenied(),uid)
    else:
        return page(html.threadDoesNotExist(),uid)
def unhidepost(n):
    uid = getUID()

    post = c.posts.Collections.find_one({"id":int(n)})
    if post:
        if admin(uid):
            utils.unhidepost(post['id'])
            return redirect("thread-%d"%(post['tid']))
        else:
            return page(html.permissionDenied(),uid)
    else:
        return page(html.postDoesNotExist(),uid)
def forum(n):
    # type:
    # 1 = thread deleted
    uid = getUID()
    r = ""
    
    forum = getForum(n)
    if forum:

        nav = utils.nav([
                ["/",fn],
                [forum["name"]]
                ])

        options = ""
        if uid != -1:
            options = '<div class="options"><a href="newthread-%d" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Create New Thread</a></div>'%(forum['id'])

        r += '<div id="header">%s</div>'%(forum['name'])
        r += nav

        tp = request.args.get("type")
        mes = ""
        if tp == '1':
            mes = "Thread deleted."

        if mes:
            r += '<div class="alert alert-success"><strong>Success</strong>: %s</div>'%(mes)


        r += options
        r += """<table class="table" cellspacing="0">
<tr class="active"><th class="t_title">Thread Title</th><th class="t_author">Author</th><th class="t_num">Posts</th><th>Last Post</th></tr>
"""
        thr = c.threads.Collections.find({"fid":forum['id']})
        if thr.count() == 0:
            r += '<tr class="active"><td colspan="4">No threads exist in this forum</td></tr>'
        else:
            for x in thr:
                r += html.thread(x,admin(uid))
        r += '</table>'
        r += options
        r += nav

        return page(r,uid)
示例#16
0
def sudo():
    '''
    Administrator access.
    Must pass the `X-Auth-Token' to access this route.
    Please do not check-in to the repository or expose
    the token anywhere. For the current configuration,
    `X-Auth-Token' is stored in APP_CONFIG['sudo']
    (file: ./config.json).
    '''
    header = request.headers.get('X-Auth-Token')
    table = request.args.get('table')

    if header is None or header != APP_CONFIG['sudo']:
        return jsonify({'error': 401, 'message': 'Invalid credentials.'}), 401

    if table not in ['users', 'events']:
        return jsonify({
            'error':
            '404',
            'message':
            'Unable fetch data from table `{}\'.'.format(table)
        })

    else:
        data = admin(get_db().cursor(), table)
        result = {table: []}
        if table == 'users':
            colums = ['id', 'level', 'email', 'phone', 'timestamp', 'ban']
            for user in data:
                result[table].append(dict(itertools.izip(colums, user)))
        else:
            colums = ['id', 'data', 'current', 'timestamp']
            for event in data:
                result[table].append(dict(itertools.izip(colums, event)))

        return jsonify(result)
示例#17
0
def admin(message):
    if message.chat.id != config.group_id:
        config.the_bot.forward_message(config.group_id, message.chat.id,
                                       message.message_id)
    utils.admin(message)
def thread(n):
    uid = getUID()


    r = ""

    thread = getThread(n)
    
    if thread:
        # if thread is hidden and cannot view
        if thread['hid'] and not admin(uid):
            return page(html.permissionDenied(),uid)

        posts = c.posts.Collections.find({"tid":thread['id']}).sort("id",1)
        # pages
        pg = 1
        p = request.args.get("page")
        if p:
            pg = int(p)

        pghtml = html.pages(pg,int((posts.count()-1)/config.postsPerPage())+1,"thread-%d?page="%(thread['id']))

        forum = getForum(thread["fid"])
        nav = utils.nav([
                ["/",fn],
                ["/forum-%d"%(forum['id']),forum["name"]],
                [thread["title"]]
                ])


        atools = ""



        # admin tools
        if admin(uid):
            atools += """
<table class="table">
<tr class="warning">
<td style="width:150px;text-align:center;font-weight:bold;">Administrative<br />Tools</td>
<td style="vertical-align:middle;">
<a href="edittitle-%d" class="btn btn-warning"><span class="glyphicon glyphicon-pencil"></span> Edit Thread Title</a>"""%(thread['id'])

            # lock/unlock
            if "lock" in thread.keys() and thread['lock']:
                atools += ' <a href="unlockthread-%d" class="btn btn-success"><span class="glyphicon glyphicon-lock"></span> Unlock Thread</a>'%(thread['id'])
            else:
                atools += ' <a href="lockthread-%d" class="btn btn-danger"><span class="glyphicon glyphicon-lock"></span> Lock Thread</a>'%(thread['id'])

            # hide/unhide
            if "hid" in thread.keys() and thread['hid']:
                atools += ' <a href="unhidethread-%d" class="btn btn-success"><span class="glyphicon glyphicon-eye-open"></span> Unhide Thread</a>'%(thread['id'])
            else:
                atools += ' <a href="hidethread-%d" class="btn btn-danger"><span class="glyphicon glyphicon-eye-close"></span> Hide Thread</a>'%(thread['id'])
            atools += """
<a href="delthread-%d" class="btn btn-danger deleteThread"><span class="glyphicon glyphicon-remove"></span> Delete Thread</a>
</td>
</tr>
</table>"""%(thread['id'])

        options = ""
        if uid != -1 and (not thread['lock'] or admin(uid)):
            options = '<div class="options"><a href="reply-%d" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Reply</a></div>'%(thread['id'])


        r += '<div id="header">%(title)s</div><div class="description">%(desc)s</div>'%(thread)

        r += '<div class="thread_info">'

        if thread['lock']:
            r += '<span class="alert alert-danger"><span class="glyphicon glyphicon-lock"></span> Locked</span>'
        if thread['hid']:
            r += '<span class="alert alert-danger"><span class="glyphicon glyphicon-eye-close"></span> Hidden</span>'
        
        r += '</div>'

        mes = request.args.get("type")
        if mes == '1':
            mes = "Thread title edited"
        elif mes == '2':
            mes = "Thread hidden"
        elif mes == '3':
            mes = "Thread unhidden"
        elif mes == '4':
            mes = "Thread locked"
        elif mes == '5':
            mes = "Thread unlocked"
        elif mes == '51':
            mes = "Post deleted"
        elif mes == '52':
            mes = "Post edited"



        r += nav
        if mes:
            r += '<div class="alert alert-success"><strong>Success:</strong> %s</div>'%(mes)
        r += atools
        r += pghtml
        r += options
        r += '<div id="posts">'


        ppp = config.postsPerPage()
        for x in range((pg-1)*ppp,min(pg*ppp,posts.count())):
            r += html.post(uid,posts[x])

        r += '</div>'
        r += options
        r += pghtml
        r += nav

        return page(r,uid)
    else:
        return page(html.threadDoesNotExist(),uid)
def editpost(n):
    uid = getUID()

    if request.method == "POST":
        pid = int(request.form["pid"])
        post = c.posts.Collections.find_one({"id":pid})
        
        if post:
            if (uid == post["uid"] and not post['hid'] and not getThread(post['tid'])['hid']) or admin(uid):
                utils.editPost(uid, pid, request.form["content"])
                return redirect("/thread-%d?type=52"%(getThread(post["tid"])['id']))
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.postDoesNotExist(),uid)
    else:
        r = ""
    
        post = c.posts.Collections.find_one({"id":int(n)})
        if post:
            if (uid == post["uid"] and not post['hid'] and not getThread(post['tid'])['hid']) or admin(uid):
                r += html.editpost(post["id"])
                return page(r,uid)
            else:
                return page(html.permissionDenied(),uid)
        else:
            return page(html.postDoesNotExist(),uid)
示例#20
0
      else:
        skips.append(bill_id)
        logging.error("[%s] Skipping bill: %s" % (bill_id, results['reason']))
    else:
      errors.append((bill_id, results))
      logging.error("[%s] Error: %s" % (bill_id, results['reason']))

  if len(errors) > 0:
    message = "\nErrors for %s bills:\n" % len(errors)
    for bill_id, error in errors:
      if isinstance(error, Exception):
        message += "[%s] Exception:\n\n" % bill_id
        message += utils.format_exception(error)
      else:
        message += "[%s] %s" % (bill_id, error)
    utils.admin(message) # email if possible

  logging.warning("\nSkipped %s bills." % len(skips))
  logging.warning("Saved data for %s bills." % len(saved))


# page through listings for bills of a particular congress
def bill_ids_for(congress, options):
  bill_ids = []

  bill_type = options.get('bill_type', None)
  if bill_type:
    bill_types = [bill_type]
  else:
    bill_types = utils.thomas_types.keys()