Ejemplo n.º 1
0
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle

from anubis.util import options

options.define('ttf_font_name', 'fzyh.ttf', 'Name of TTF Font')
options.define('pdf_font_size', 84, 'Font Size of generated PDF.')

A4_TRANSVERSE = A4[::-1]
_reged = False


def gen_team_pdf(team_tuples: list):
    global _reged
    if not _reged:
        pdfmetrics.registerFont(
            TTFont('my_font', options.options.ttf_font_name))
        _reged = True
    buf = io.BytesIO()
    canv = canvas.Canvas(buf, pagesize=A4_TRANSVERSE)
    style = ParagraphStyle(name='default',
                           fontName='my_font',
                           fontSize=options.options.pdf_font_size,
                           alignment=1,
                           leading=options.options.pdf_font_size * 1.2)
    for index, team in team_tuples:
Ejemplo n.º 2
0
import collections
import copy

from anubis.service import bus
from anubis.util import options

PREFIX_DISCUSSION_NODES = 'discussion-nodes-'

options.define('smallcache_max_entries', default=64,
               help='Maximum number of entries of smallcache.')

_cache = collections.OrderedDict()


async def _on_unset(e):
    if e['value'] in _cache:
        del _cache[e['value']]


def init():
    bus.subscribe(_on_unset, ['smallcache-unset'])


def get_direct(key, default=None):
    if key not in _cache:
        return default
    _cache.move_to_end(key)
    return _cache[key]


def get(key, default=None):
Ejemplo n.º 3
0
import asyncio

import aioamqp

from anubis.util import options

options.define('mq_host',
               default='localhost',
               help='Message queue hostname or IP address.')
options.define('mq_vhost',
               default='/anubis',
               help='Message queue virtual host.')
options.define('mq_user', default='guest', help='Message queue username.')
options.define('mq_password', default='guest', help='Message queue password')

_protocol_future = None
_channel_futures = {}


async def _connect():
    global _protocol_future
    if _protocol_future:
        return await _protocol_future
    _protocol_future = future = asyncio.Future()
    try:
        _, protocol = await aioamqp.connect(
            host=options.options.mq_host,
            virtualhost=options.options.mq_vhost,
            login=options.options.mq_user,
            password=options.options.mq_password)
        future.set_result(protocol)
Ejemplo n.º 4
0
from motor import motor_asyncio

from anubis.util import options

options.define('db_host',
               default='localhost',
               help='Database hostname or IP address.')
options.define('db_name', default='anubis', help='Database name.')


class Database(object):
    _instance = None

    def __new__(cls):
        if not cls._instance:
            client = motor_asyncio.AsyncIOMotorClient(options.options.db_host)
            cls._instance = motor_asyncio.AsyncIOMotorDatabase(
                client, options.options.db_name)
        return cls._instance


class Collection(object):
    _instances = {}

    def __new__(cls, name):
        if name not in cls._instances:
            cls._instances[name] = motor_asyncio.AsyncIOMotorCollection(
                Database(), name)
        return cls._instances[name]

Ejemplo n.º 5
0
import aioredis

from anubis.util import options

options.define('redis_host',
               default='localhost',
               help='Redis hostname or IP address.')
options.define('redis_port', default=6379, help='Redis port.')
options.define('redis_index', default=1, help='Redis database index.')

_connection = None


async def _create_connect():
    global _connection
    if not _connection:
        _connection = await aioredis.create_redis(
            (options.options.redis_host, options.options.redis_port),
            db=options.options.redis_index)
    return _connection


async def database():
    return await _create_connect()
Ejemplo n.º 6
0
import collections

from anubis.util import options

options.define('pretty', default=False, help='Pretty print the result.')

_methods = collections.OrderedDict()


def wrap(method):
    if method.__module__ == '__main__':
        _methods[method.__name__] = method
    return method


def invoke_by_args():
    import argparse
    import asyncio
    import inspect
    import pprint
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='')
    for name, method in _methods.items():
        subparser = subparsers.add_parser(name)
        argcount = method.__code__.co_argcount
        num_defaults = len(method.__defaults__) if method.__defaults__ else 0
        argoffset = argcount - num_defaults
        for index, argname in enumerate(
                method.__code__.co_varnames[:argcount]):
            if index < argoffset:
                subparser.add_argument(argname,
Ejemplo n.º 7
0
import logging
import asyncio
from os import path

from aiohttp import web
import sockjs

from anubis import error
from anubis.util import options
from anubis.util import locale
from anubis.util import json
from anubis.util import tools
from anubis.service import bus

options.define('debug', default=False, help='Enable debug mode.')
options.define('static', default=True, help='Serve static files.')
options.define('ip_header',
               default='X-Forwarded-For',
               help='Header name for remote IP.')
options.define('unsaved_session_expire_seconds',
               default=43200,
               help='Expire time for unsaved session, in seconds.')
options.define('saved_session_expire_seconds',
               default=2592000,
               help='Expire time for saved session, in seconds.')
options.define('cookie_domain', default=None, help='Cookie domain.')
options.define('cookie_secure',
               default=False,
               help='Enable secure cookie flag.')
options.define('registration_token_expire_seconds',
               default=86400,
Ejemplo n.º 8
0
from email.mime import text

import smtplib as asmtp

from anubis.util import argmethod
from anubis.util import options

options.define('smtp_host', default='smtp.qq.com', help='SMTP server')
options.define('smtp_port', default=465, help='SMTP server port')
options.define('smtp_user',
               default='*****@*****.**',
               help='SMTP username')
options.define('smtp_password',
               default='emymknobimmlbbnb',
               help='SMTP password')
options.define('mail_from', default='*****@*****.**', help='Mail from')


@argmethod.wrap
async def send_mail(to: str, subject: str, content: str):
    _server = asmtp.SMTP_SSL(host=options.options.smtp_host,
                             port=options.options.smtp_port)
    msg = text.MIMEText(content, _subtype='html', _charset='UTF-8')
    msg['Subject'] = subject
    msg['From'] = options.options.mail_from
    msg['To'] = to

    _server.ehlo()
    _server.login(options.options.smtp_user, options.options.smtp_password)
    _server.sendmail(options.options.mail_from, to, msg.as_string())
Ejemplo n.º 9
0
import collections
import os
import functools
import yaml

from anubis.util import options

options.define('default_locale', default='zh_CN', help='Default locale.')

_locales = {}
VIEW_LANGS = {}


def load_translations(translation_path):
    langs = []
    for filename in os.listdir(translation_path):
        if not filename.endswith('.yaml'):
            continue
        with open(os.path.join(translation_path, filename),
                  encoding='utf-8') as yaml_file:
            code = filename[:-5]
            name = yaml_file.readline()[1:].strip()
            _locales[code] = yaml.load(yaml_file)
            langs.append((code, name))
    global VIEW_LANGS
    VIEW_LANGS = collections.OrderedDict(langs)


@functools.lru_cache()
def get_translate(locale_code):
    if locale_code not in _locales:
Ejemplo n.º 10
0
import asyncio
from aiohttp import ClientSession
from urllib import parse
from bs4 import BeautifulSoup

from anubis import error
from anubis.util import argmethod
from anubis.util import options
from anubis.util import ocr


options.define('school_url', 'http://jwc.sut.edu.cn', 'URL of school server.')
options.define('school_login_method', 'ACTIONLOGON.APPPROCESS', 'Method of school login.')
options.define('school_captcha_method', 'ACTIONVALIDATERANDOMPICTURE.APPPROCESS', 'Method of captcha.')
options.define('school_student_method', 'ACTIONQUERYSTUDENTBYSTUDENTNO.APPPROCESS?mode=2',
               'Method of fetch student info.')
options.define('school_teacher_username', 'teacher', 'Username of school teacher account.')
options.define('school_teacher_pass', 'password', 'Password of school teacher account.')

_session = ClientSession(loop=asyncio.get_event_loop())


async def _get_captcha_image():
    global _session
    captcha_url = parse.urljoin(options.options.school_url, options.options.school_captcha_method)
    async with _session.get(captcha_url) as response:
        return await response.read()


async def _login():
    global _session