Beispiel #1
0
def api_upload_attachment():
    i = ctx.request.input(name='', description='', link='')
    name = i.name.strip()
    description = i.description.strip()
    f = i.file
    ref_type = 'attachment'
    ref_id = db.next_str()
    fcontent = f.file.read()
    filename = f.filename
    fext = os.path.splitext(filename)[1]
    if not name:
        name = os.path.splitext(os.path.split(filename)[1])[0]

    preview = None
    w = h = 0
    res = store.upload_file(ref_type, ref_id, filename, fcontent)
    if res.mime.startswith('image/'):
        try:
            logging.info(
                'it seems an image was uploaded, so try to get size...')
            im = thumbnail.as_image(fcontent)
            w, h = im.size[0], im.size[1]
            logging.info('size got: %d x %d' % (w, h))
            if w > 160 or h > 120:
                logging.info(
                    'creating thumbnail for uploaded image (size %d x %d)...' %
                    (w, h))
                tn = thumbnail.create_thumbnail(im, 160, 120)
                pw, ph, pcontent = tn['width'], tn['height'], tn['data']
                logging.info(
                    'thumbnail was created successfully with size %d x %d.' %
                    (w, h))
                preview = store.upload_file(ref_type, ref_id, filename,
                                            fcontent)
            else:
                logging.info('No need to create thumbnail.')
                preview = res
        except:
            logging.exception('error when creating thumbnail.')

    current = time.time()
    attr = Dict( \
        id = ref_id, \
        website_id = ctx.website.id, \
        user_id = ctx.user.id, \
        resource_id = res.id, \
        preview_resource_id = preview and preview.id or '', \
        name = name, \
        description = description, \
        width = w, \
        height = h, \
        size = res.size, \
        mime = res.mime, \
        creation_time = current, \
        modified_time = current, \
        version = 0)
    db.insert('attachments', **attr)
    if i.link == u't':
        attr.filelink = '/api/resources/url?id=%s' % attr.resource_id
    return attr
Beispiel #2
0
def upload_file(ref_type, ref_id, filename, fcontent):
    fileext = os.path.splitext(filename)[1].lower()
    filesize = len(fcontent)
    dt = datetime.now()
    fpath = os.path.join(ctx.website.id, str(ref_type), str(dt.year),
                         str(dt.month), str(dt.day),
                         '%s%s' % (uuid.uuid4().hex, fileext))
    sname = get_enabled_store_name()
    url, the_ref = get_store_instance(sname).upload(fpath, fcontent)
    logging.info('uploaded file: %s' % url)
    ref = '%s:%s' % (sname, the_ref)
    r = Dict( \
        id = db.next_str(), \
        website_id = ctx.website.id, \
        ref_id = ref_id, \
        ref_type = ref_type, \
        deleted = False, \
        size = filesize, \
        filename = filename, \
        mime = mimetypes.types_map.get(fileext, 'application/octet-stream'), \
        ref = ref, \
        url = url, \
        creation_time = time.time(), \
        version = 0)
    db.insert('resources', **r)
    return r
Beispiel #3
0
 def _get_theme_info(name):
     m = load_module('themes.%s' % name)
     return Dict( \
         id = name, \
         name = getattr(m, 'name', name), \
         description = getattr(m, 'description', '(no description)'), \
         author = getattr(m, 'author', '(unknown)'), \
         version = getattr(m, 'version', '1.0'), \
         snapshot = '/themes/%s/static/snapshot.png' % name)
Beispiel #4
0
def get_menus():
    '''
    Get navigation menus as list, each element is a Dict object.
    '''
    menus = db.select('select * from menus order by display_order, name')
    if menus:
        return menus
    current = time.time()
    menu = Dict(id=db.next_str(), name=u'Home', description=u'', type='latest_articles', display_order=0, ref='', url='/latest', creation_time=current, modified_time=current, version=0)
    db.insert('menus', **menu)
    return [menu]
Beispiel #5
0
def _get_wikipages(wiki, returnDict=False):
    '''
    Get all wiki pages and return as tree. Each wiki page contains only id, wiki_id, parent_id, display_order, name and version.
    The return value is top-level list.
    '''
    pages = WikiPages.select('where wiki_id=?', wiki._id)
    pdict = dict(((p._id, p) for p in pages))
    if returnDict:
        return pdict
    proot = Dict(_id='')
    _tree_iter(pdict, proot)
    return proot.children
Beispiel #6
0
def _get_wikipages(wiki, returnDict=False):
    '''
    Get all wiki pages and return as tree. Each wiki page contains only id, website_id, wiki_id, parent_id, display_order, name and version.
    The return value is virtual root node.
    '''
    pages = db.select(
        'select id, website_id, wiki_id, parent_id, display_order, name, version from wiki_pages where wiki_id=?',
        wiki.id)
    pdict = dict(((p.id, p) for p in pages))
    if returnDict:
        return pdict
    proot = Dict(id='')
    _tree_iter(pdict, proot)
    return proot.children
Beispiel #7
0
def _load_plugins(ptype):
    D = dict()
    for pname, mod in loader.scan_submodules('plugin.%s' % ptype).iteritems():
        try:
            keys = frozenset([i['key'] for i in mod.Plugin.get_inputs()])
            s = Dict(id=pname,
                     name=pname,
                     description=mod.Plugin.get_description(),
                     keys=keys,
                     Plugin=mod.Plugin)
            D[pname] = s
            logging.info('Load plugin: %s.%s' % (ptype, pname))
        except:
            logging.exception('Failed to load plugin: %s.%s' % (ptype, pname))
    return D
Beispiel #8
0
def _get_categories():
    cats = db.select(
        'select * from categories where website_id=? order by display_order, name',
        ctx.website.id)
    if not cats:
        logging.info('create default uncategorized...')
        current = time.time()
        uncategorized = Dict(id=db.next_str(), \
            website_id=ctx.website.id, \
            name='Uncategorized', description='', \
            locked=True, display_order=0, \
            creation_time=current, modified_time=current, \
            version=0)
        db.insert('categories', **uncategorized)
        cats = [uncategorized]
    return cats
Beispiel #9
0
def api_create_wiki():
    ' create a new wiki. '
    i = ctx.request.input(name='', description='', content='')
    name = i.name.strip()
    if not name:
        raise APIValueError('name', 'name cannot be empty')
    content = i.content.strip()
    if not content:
        raise APIValueError('content', 'content cannot be empty')
    current = time.time()
    wiki = Dict( \
        id=db.next_str(), \
        website_id=ctx.website.id, \
        name=name, \
        description=i.description.strip(), \
        content=content, \
        creation_time=current, \
        modified_time=current, \
        version=0)
    db.insert('wikis', **wiki)
    return wiki
Beispiel #10
0
def api_create_category():
    i = ctx.request.input(name='', description='')
    name = i.name.strip()
    description = i.description.strip()
    if not name:
        raise APIValueError('name', 'name cannot be empty')
    num = len(_get_categories())
    if num >= 100:
        raise APIError(
            'operation:failed', 'category',
            'cannot create new category for the maximum number of categories was reached.'
        )
    logging.info('create new category...')
    current = time.time()
    cat = Dict(id=db.next_str(), \
            website_id=ctx.user.website_id, \
            name=name, description=description, \
            locked=False, display_order=num, \
            creation_time=current, modified_time=current, \
            version=0)
    db.insert('categories', **cat)
    return cat
Beispiel #11
0
def api_create_article():
    i = ctx.request.input(category_id='',
                          name='',
                          tags='',
                          content='',
                          draft='')
    name = i.name.strip()
    content = i.content.strip()
    category_id = i.category_id
    if not name:
        raise APIValueError('name', 'name cannot be empty.')
    if not content:
        raise APIValueError('content', 'content cannot be empty.')
    if not category_id:
        raise APIValueError('category_id', 'category_id cannot be empty.')
    cat = _get_category(category_id)
    draft = True
    if ctx.user.role_id < ROLE_CONTRIBUTORS:
        draft = True if i.draft else False
    current = time.time()
    html_content, summary = html.parse_md(content, 800)
    article = Dict( \
        id=db.next_str(), \
        website_id=ctx.website.id, \
        user_id=ctx.user.id, \
        user_name=ctx.user.name, \
        category_id=category_id, \
        draft=draft, \
        name=name, \
        tags=_format_tags(i.tags), \
        read_count=0, \
        summary=summary, \
        content=content, \
        creation_time=current, \
        modified_time=current, \
        version=0)
    db.insert('articles', **article)
    return article
Beispiel #12
0
def api_create_page():
    i = ctx.request.input(name='', tags='', content='', draft='false')
    name = i.name.strip()
    content = i.content.strip()
    if not name:
        raise APIValueError('name', 'name cannot be empty.')
    if not content:
        raise APIValueError('content', 'content cannot be empty.')
    draft = boolean(i.draft)
    current = time.time()
    page = Dict( \
        id=db.next_str(), \
        website_id=ctx.website.id, \
        draft=draft, \
        name=name, \
        tags=_format_tags(i.tags), \
        read_count=0, \
        content=content, \
        creation_time=current, \
        modified_time=current, \
        version=0)
    db.insert('pages', **page)
    return page
Beispiel #13
0
      ...
    APIValueError: Invalid email address.
    >>> check_email('[email protected]')
    Traceback (most recent call last):
      ...
    APIValueError: Invalid email address.
    >>> check_email('*****@*****.**')
    Traceback (most recent call last):
      ...
    APIValueError: Invalid email address.
    >>> check_email('*****@*****.**')
    Traceback (most recent call last):
      ...
    APIValueError: Invalid email address.
    >>> check_email('*****@*****.**')
    Traceback (most recent call last):
      ...
    APIValueError: Invalid email address.
    '''
    e = str(email).strip().lower()
    if _REG_EMAIL.match(e) is None:
        raise APIValueError('email', 'Invalid email address.')
    return e


if __name__ == '__main__':
    cache.client = cache.RedisClient('localhost')
    ctx.website = Dict(id='123000')
    import doctest
    doctest.testmod()