Пример #1
0
 def POST(self):
     dirname = xutils.get_argument("dirname")
     destname = xutils.get_argument("destname")
     xutils.zip_dir(dirname, os.path.join(dirname, destname))
     return xtemplate.render_text(html, dirname=dirname, destname=destname)
Пример #2
0
 def GET(self):
     id = xutils.get_argument("id")
     db = xtables.get_file_table()
     db.update(is_marked=0, where=dict(id=id))
     raise web.seeother("/note/view?id=%s" % id)
Пример #3
0
 def POST(self):
     id = xutils.get_argument("id")
     status = xutils.get_argument("status", type=int)
     return update_message(id, status)
Пример #4
0
 def get_page(self):
     """返回当前页码"""
     return xutils.get_argument("page", 1, type=int)
Пример #5
0
 def GET(self):
     id = xutils.get_argument("id", type=int)
     sched = xtables.get_schedule_table().select_first(where=dict(id=id))
     return xtemplate.render("system/crontab_edit.html",
                             item=sched,
                             links=get_cron_links())
Пример #6
0
 def GET(self):
     id = xutils.get_argument("id")
     note = check_get_note(id)
     NOTE_DAO.update(id, archived=False)
     raise web.found("/note/%s" % id)
Пример #7
0
 def get_input(self):
     return xutils.get_argument("input", "")
Пример #8
0
    def GET(self, op):
        id = xutils.get_argument("id", "")
        name = xutils.get_argument("name", "")
        page = xutils.get_argument("page", 1, type=int)
        pagesize = xutils.get_argument("pagesize", xconfig.PAGE_SIZE, type=int)
        show_menu = xutils.get_argument("show_menu", "true") != "false"
        orderby = xutils.get_argument("orderby", "mtiem_desc")
        user_name = xauth.get_current_name()
        show_add_file = False
        title = None
        show_pagination = True
        show_search_div = False

        # 回收站的笔记也能看到
        if id == "" and name == "":
            raise HTTPError(504)
        if id != "":
            file = xutils.call("note.get_by_id", id)
        elif name is not None:
            file = xutils.call("note.get_by_name", name, db=db)
        if file is None:
            raise web.notfound()

        if file.type != "group" and not file.is_public and user_name != "admin" and user_name != file.creator:
            raise web.seeother("/unauthorized")
        pathlist = xutils.call("note.list_path", file)
        can_edit = (file.creator == user_name) or (user_name == "admin")
        role = xauth.get_current_role()

        # 定义一些变量
        show_groups = False
        show_mdate = False
        files = []
        recent_created = []
        groups = []
        amount = 0
        show_recommend = False
        template_name = "note/view.html"
        next_note = None
        prev_note = None
        filelist = None
        xconfig.note_history.put(
            dict(user=user_name, link="/note/view?id=%s" % id, name=file.name))
        recommended_notes = []

        title = file.name
        if file.type == "group":
            files = xutils.call("note.list_by_parent", user_name, file.id,
                                (page - 1) * pagesize, pagesize, orderby)
            amount = xutils.call("note.count", user_name, file.id)
            content = file.content
            show_search_div = True
            show_add_file = True
            show_mdate = True
        elif file.type == "md" or file.type == "text":
            content = file.content
            show_recommend = True
            show_pagination = False
            if op == "edit":
                show_recommend = False
                template_name = "note/editor/markdown_edit.html"
        else:
            content = file.content
            content = content.replace(u'\xad', '\n')
            content = content.replace(u'\n', '<br/>')
            file.data = file.data.replace(u"\xad", "\n")
            file.data = file.data.replace(u'\n', '<br/>')
            if file.data == None or file.data == "":
                file.data = content
            show_recommend = True
            show_pagination = False

        fpath = os.path.join(xconfig.UPLOAD_DIR, file.creator,
                             str(file.parent_id), str(id))

        # 处理相册
        if file.type == "gallery":
            if os.path.exists(fpath):
                filelist = fsutil.list_files(fpath, webpath=True)
            else:
                filelist = []
            file.path = fpath

        if show_recommend and user_name is not None:
            show_groups = False
            # 推荐系统
            ctx = Storage(id=file.id,
                          name=file.name,
                          creator=file.creator,
                          content=file.content,
                          parent_id=file.parent_id,
                          result=[])
            xmanager.fire("note.recommend", ctx)
            recommended_notes = ctx.result

            next_note = xutils.call("note.find_next_note", file)
            prev_note = xutils.call("note.find_prev_note", file)

        xmanager.fire("note.view", file)
        show_aside = True
        if op == "edit":
            show_aside = False

        return xtemplate.render(template_name,
                                show_aside=show_aside,
                                html_title=title,
                                file=file,
                                path=fpath,
                                filelist=filelist,
                                note_id=id,
                                op=op,
                                show_mdate=show_mdate,
                                show_add_file=show_add_file,
                                show_menu=show_menu,
                                show_pagination=show_pagination,
                                can_edit=can_edit,
                                pathlist=pathlist,
                                page_max=math.ceil(amount / pagesize),
                                page=page,
                                page_url="/note/view?id=%s&orderby=%s&page=" %
                                (id, orderby),
                                files=files,
                                recent_created=recent_created,
                                show_groups=show_groups,
                                groups=groups,
                                prev_note=prev_note,
                                next_note=next_note,
                                recommended_notes=recommended_notes)
Пример #9
0
 def POST(self):
     name = xutils.get_argument("name")
     dirname = xconfig.SCRIPTS_DIR
     path = os.path.join(dirname, name)
     os.remove(path)
     raise web.seeother("/system/script_admin")
Пример #10
0
 def POST(self):
     key = xutils.get_argument("key", "")
     value = xutils.get_argument("value", "")
     cacheutil.set(key, value)
     return dict(code = "success")
Пример #11
0
 def GET(self):
     key = xutils.get_argument("key", "")
     return dict(code = "success", data = cacheutil.get(key))
Пример #12
0
    def GET(self, op):
        id = xutils.get_argument("id", "")
        name = xutils.get_argument("name", "")
        page = xutils.get_argument("page", 1, type=int)
        pagesize = xutils.get_argument("pagesize", xconfig.PAGE_SIZE, type=int)
        db = xtables.get_file_table()
        user_name = xauth.get_current_name()
        show_add_file = False
        title = None

        if id == "" and name == "":
            raise HTTPError(504)
        if id != "":
            id = int(id)
            file = dao.get_by_id(id, db=db)
        elif name is not None:
            file = dao.get_by_name(name, db=db)
        if file is None:
            raise web.notfound()
        if file.is_deleted == 1:
            raise web.seeother("/")

        if file.type != "group" and not file.is_public and user_name != "admin" and user_name != file.creator:
            raise web.seeother("/unauthorized")
        show_search_div = False
        pathlist = dao.get_pathlist(db, file)
        can_edit = (file.creator == user_name) or (user_name == "admin")
        role = xauth.get_current_role()

        # 定义一些变量
        files = []
        recent_created = []
        amount = 0
        template_name = "note/view.html"
        xconfig.note_history.put(
            dict(user=user_name, link="/note/view?id=%s" % id, name=file.name))

        title = file.name
        groups = xutils.call("note.list_group")
        if file.type == "group":
            where_sql = "parent_id=$parent_id AND is_deleted=0 AND (creator=$creator OR is_public=1)"
            if xauth.is_admin():
                where_sql = "parent_id=$parent_id AND is_deleted=0"
            amount = db.count(where=where_sql,
                              vars=dict(parent_id=file.id, creator=user_name))
            files = db.select(where=where_sql,
                              vars=dict(parent_id=file.id,
                                        is_deleted=0,
                                        creator=user_name),
                              order="mtime DESC",
                              limit=pagesize,
                              offset=(page - 1) * pagesize)
            content = file.content
            show_search_div = True
            show_add_file = True
            # recent_created  = xutils.call("note.list_recent_created", file.id, 10)
        elif file.type == "md" or file.type == "text":
            content = file.content
            if op == "edit":
                template_name = "note/markdown_edit.html"
        else:
            content = file.content
            content = content.replace(u'\xad', '\n')
            content = content.replace(u'\n', '<br/>')
            file.data = file.data.replace(u"\xad", "\n")
            file.data = file.data.replace(u'\n', '<br/>')
            if file.data == None or file.data == "":
                file.data = content

        xmanager.fire("note.view", file)
        show_aside = True
        if op == "edit":
            show_aside = False
        return xtemplate.render(template_name,
                                show_aside=show_aside,
                                html_title=title,
                                file=file,
                                op=op,
                                show_add_file=show_add_file,
                                can_edit=can_edit,
                                pathlist=pathlist,
                                page_max=math.ceil(amount / pagesize),
                                page=page,
                                page_url="/file/view?id=%s&page=" % id,
                                files=files,
                                recent_created=recent_created,
                                show_groups=True,
                                groups=groups)
Пример #13
0
 def GET(self):
     id = xutils.get_argument("id", type=int)
     db = xtables.get_file_table()
     return db.select_one(where={"id": id})
Пример #14
0
 def get_format(self):
     return xutils.get_argument("_format", "")
Пример #15
0
 def GET(self):
     id = xutils.get_argument("id")
     note = check_get_note(id)
     NOTE_DAO.update(id, priority=0)
     raise web.found("/note/%s" % id)
Пример #16
0
 def POST(self):
     content = xutils.get_argument("content")
     result = xutils.exec_python_code("<shell>", content)
     return dict(code="success", message="", data=result)
Пример #17
0
 def GET(self):
     id = xutils.get_argument("id")
     note = check_get_note(id)
     NOTE_DAO.update(id, archived=False, priority=0)
     raise web.found(note.url)
Пример #18
0
    def POST(self):
        user_name = xauth.current_name()
        part_file = True
        chunksize = 5 * 1024 * 1024
        chunk = xutils.get_argument("chunk", 0, type=int)
        chunks = xutils.get_argument("chunks", 1, type=int)
        file = xutils.get_argument("file", {})
        prefix = xutils.get_argument("prefix", "")
        dirname = xutils.get_argument("dirname", xconfig.DATA_DIR)
        dirname = dirname.replace("$DATA", xconfig.DATA_DIR)
        note_id = xutils.get_argument("note_id")

        # 不能访问上级目录
        if ".." in dirname:
            return dict(code="fail", message="can not access parent directory")

        filename = None
        webpath = ""
        origin_name = ""

        if hasattr(file, "filename"):
            origin_name = file.filename
            xutils.trace("UploadFile", file.filename)
            filename = os.path.basename(file.filename)
            filename = xutils.get_real_path(filename)
            if dirname == "auto":
                filename = generate_filename(filename, prefix)
                filepath, webpath = xutils.get_upload_file_path(
                    user_name, filename, replace_exists=True)
                dirname = os.path.dirname(filepath)
                filename = os.path.basename(filepath)
            else:
                # TODO check permission.
                filepath = os.path.join(dirname, filename)

            if chunk == 0:
                lock = try_lock_file(filepath)

            if part_file:
                tmp_name = "%s_%d.part" % (filename, chunk)
                seek = 0
            else:
                tmp_name = filename
                seek = chunk * chunksize

            xutils.makedirs(dirname)
            tmp_path = os.path.join(dirname, tmp_name)

            with open(tmp_path, "wb") as fp:
                fp.seek(seek)
                if seek != 0:
                    xutils.log("seek to {}", seek)
                for file_chunk in file.file:
                    fp.write(file_chunk)
        else:
            return dict(code="fail", message=u"请选择文件")
        if part_file and chunk + 1 == chunks:
            self.merge_files(dirname, filename, chunks)

        try_touch_note(note_id)
        if note_id != None and note_id != "":
            xutils.call("note.touch", note_id)
        return dict(code="success",
                    webpath=webpath,
                    link=get_link(origin_name, webpath))
Пример #19
0
 def POST(self):
     name = xutils.get_argument("name")
     xauth.remove_user(name)
     return dict(code="success")
Пример #20
0
 def GET(self):
     return xtemplate.render("message/message.html",
                             search_action="/message",
                             search_placeholder="搜索备忘信息",
                             count_message=count_message,
                             key=xutils.get_argument("key", ""))
Пример #21
0
 def get_format(self):
     """返回当前请求的数据格式"""
     return xutils.get_argument("_format", "")
Пример #22
0
def get_user_from_token():
    token = xutils.get_argument("token")
    if token != None and token != "":
        return select_first(lambda x: x.token == token)
Пример #23
0
 def POST(self):
     id = xutils.get_argument("id", type=int)
     xtables.get_schedule_table().delete(where=dict(id=id))
     xmanager.load_tasks()
     raise web.seeother("/system/crontab")
Пример #24
0
 def POST(self):
     files = xutils.get_argument("files[]", list())
     for i, fpath in enumerate(files):
         files[i] = os.path.abspath(fpath)
     xconfig.FS_CLIP = files
     return dict(code="success")
Пример #25
0
    def GET(self, op, id=None):
        if id is None:
            id = xutils.get_argument("id", "")
        name = xutils.get_argument("name", "")
        page = xutils.get_argument("page", 1, type=int)
        pagesize = xutils.get_argument("pagesize", xconfig.PAGE_SIZE, type=int)
        show_menu = xutils.get_argument("show_menu", "true") != "false"
        show_search = xutils.get_argument("show_search", "true") != "false"
        orderby = xutils.get_argument("orderby", None)
        is_iframe = xutils.get_argument("is_iframe", "false")
        token = xutils.get_argument("token", "")
        user_name = xauth.current_name()
        show_add_file = False

        kw = Storage()
        kw.show_left = False
        kw.show_groups = False
        kw.show_aside = True
        kw.groups = []
        kw.recommended_notes = []
        kw.op = op
        kw.template_name = "note/page/view.html"

        if id == "0":
            raise web.found("/")
        # 回收站的笔记也能看到
        file = find_note_for_view(token, id, name)

        if file is None:
            raise web.notfound()

        if token == "":
            check_auth(file, user_name)

        pathlist = NOTE_DAO.list_path(file)
        can_edit = (file.creator == user_name) or (user_name == "admin")
        role = xauth.get_current_role()

        # 定义一些变量
        show_mdate = False
        files = []
        recent_created = []
        amount = 0
        show_recommend = False
        next_note = None
        prev_note = None

        event_ctx = Storage(id=file.id, user_name=user_name)
        xmanager.fire("note.view", event_ctx)

        view_func = VIEW_FUNC_DICT.get(file.type, view_md_func)
        view_func(file, kw)

        if show_recommend and user_name is not None:
            # 推荐系统
            handle_note_recommend(kw, file, user_name)

        if op == "edit":
            kw.show_aside = False
            kw.show_search = False
            kw.show_comment = False

        if is_iframe == "true":
            kw.show_menu = False
            kw.show_search = False

        template_name = kw['template_name']
        del kw['template_name']

        # 如果是页面,需要查出上级目录列表
        handle_left_dir(kw, user_name, file, op)
        return xtemplate.render_by_ua(
            template_name,
            html_title=file.name,
            file=file,
            note_id=id,
            show_mdate=show_mdate,
            show_add_file=show_add_file,
            can_edit=can_edit,
            pathlist=pathlist,
            page_max=math.ceil(amount / pagesize),
            page=page,
            page_url="/note/view?id=%s&orderby=%s&page=" % (id, orderby),
            files=files,
            recent_created=recent_created,
            search_action="/note/timeline",
            search_placeholder="搜索笔记",
            is_iframe=is_iframe,
            **kw)
Пример #26
0
    def POST(self, method='POST'):
        name = xutils.get_argument("name", "")
        tags = xutils.get_argument("tags", "")
        key = xutils.get_argument("key", "")
        content = xutils.get_argument("content", "")
        type = xutils.get_argument("type", "md")
        date = xutils.get_argument("date", "")
        format = xutils.get_argument("_format", "")
        parent_id = xutils.get_argument("parent_id", "0")

        if key == "":
            key = time.strftime("%Y.%m.%d") + dateutil.current_wday()

        type = NOTE_TYPE_MAPPING.get(type, type)

        creator = xauth.current_name()
        note = Storage(name=name)
        note.atime = xutils.format_datetime()
        note.mtime = xutils.format_datetime()
        note.ctime = xutils.format_datetime()
        note.creator = creator
        note.parent_id = str(parent_id)
        note.type = type
        note.content = content
        note.data = ""
        note.size = len(content)
        note.is_public = 0
        note.priority = 0
        note.version = 0
        note.is_deleted = 0
        note.tags = textutil.split_words(tags)

        if note.parent_id == "-1":
            note.archived = True
            note.priority = -1

        heading = T("创建笔记")
        code = "fail"
        error = ""
        ctx = Storage(method=method, date=date)

        try:
            if type not in VALID_NOTE_TYPE_SET:
                raise Exception(u"无效的类型: %s" % type)

            create_func = CREATE_FUNC_DICT.get(type, default_create_func)
            inserted_id = create_func(note, ctx)
            if format == "json":
                return dict(code="success",
                            id=inserted_id,
                            url="/note/edit?id=%s" % inserted_id)
            if inserted_id != None:
                raise web.seeother("/note/edit?id={}".format(inserted_id))
        except web.HTTPError as e1:
            xutils.print_exc()
            raise e1
        except Exception as e:
            xutils.print_exc()
            error = xutils.u(e)
            if format == 'json':
                return dict(code='fail', message=error)

        heading = get_heading_by_type(type)
        template = CREATE_TEMPLATE_DICT.get(type, DEFAULT_CREATE_TEMPLATE)

        return xtemplate.render(template,
                                show_search=False,
                                heading=heading,
                                key="",
                                type=type,
                                name=key,
                                tags=tags,
                                error=error,
                                message=error,
                                NOTE_TYPE_LIST=NOTE_TYPE_LIST,
                                groups=list_groups_for_create(creator),
                                code=code)
Пример #27
0
 def POST(self):
     id = xutils.get_argument("id")
     if id == "":
         return
     return update_message(id, 0)
Пример #28
0
 def GET(self):
     id = xutils.get_argument("id")
     note = check_get_note(id)
     NOTE_DAO.update(id, is_public=0)
     return dict(code="success")
Пример #29
0
 def GET(self):
     id = xutils.get_argument("id", type=int)
     db = xtables.get_file_table()
     db.update(is_public=1,
               where=dict(id=id, creator=xauth.get_current_name()))
     raise web.seeother("/file/view?id=%s" % id)
Пример #30
0
    def POST(self):
        try:
            file = xutils.get_argument("file", {})
            download_res = False            
            address = xutils.get_argument("url", "")
            name    = xutils.get_argument("name", "")
            filename = ""

            if hasattr(file, "filename"):
                filename = file.filename
            plain_text = ""

            if not isempty(address):
                html = readhttp(address)
            else:
                html = ""
                for chunk in file.file:
                    html += chunk.decode("utf-8")

            print("Read html, filename={}, length={}".format(filename, len(html)))
            soup = BeautifulSoup(html, "html.parser")
            element_list = soup.find_all(["script", "style"])
            for element in element_list:
                element.extract()
            plain_text = soup.get_text(separator=" ")
            plain_text = clean_whitespace(plain_text)

            images = soup.find_all("img")
            links  = soup.find_all("a")
            csses  = soup.find_all("link")
            scripts = soup.find_all("script")
            # texts = soup.find_all(["p", "span", "div", "h1", "h2", "h3", "h4"])

            h = HTML2Text(baseurl = address)
            text = "From %s\n\n" % address + h.handle(html)

            texts = [text]

            images = get_addr_list(images)
            scripts = get_addr_list(scripts)
            # texts = get_text_list(texts)

            if download_res:
                download_res_list(images, filename)

            if name != "" and name != None:
                dirname = os.path.join(xconfig.DATA_DIR, time.strftime("archive/%Y/%m/%d"))
                xutils.makedirs(dirname)
                path = os.path.join(dirname, "%s_%s.md" % (name, time.strftime("%H%M%S")))
                xutils.savetofile(path, text)
                print("save file %s" % path)

            if False:
                user_name = xauth.get_current_name()
                def save():
                    xmanager.request("/file/add", method="POST", 
                        data=dict(name=name, content=text, type="md"),
                        headers=dict(COOKIE=xauth.get_user_cookie(user_name)))
                Timer(1, save).start()

            return xtemplate.render(self.template_path,
                images = images,
                links = links,
                csses = csses,
                scripts = scripts,
                texts = texts,
                address = address,
                url = address,
                plain_text = plain_text)
        except Exception as e:
            xutils.print_stacktrace()
            return xtemplate.render(self.template_path,
                error = str(e))