Example #1
0
def on_search_plugins(ctx):
    if not xauth.is_admin():
        return
    if not ctx.search_tool:
        return
    if ctx.search_dict:
        return
    name = ctx.key
    results = []
    dirname = xconfig.PLUGINS_DIR
    words = textutil.split_words(name)
    for fname in xutils.listdir(dirname):
        unquote_name = xutils.unquote(fname)
        unquote_name, ext = os.path.splitext(unquote_name)
        plugin_context = xconfig.PLUGINS.get(fname)
        if textutil.contains_all(unquote_name, words) \
                or (plugin_context != None and textutil.contains_all(plugin_context.title, words)):
            result = SearchResult()
            result.category = "plugin"
            result.name = u("[插件] " + unquote_name)
            if plugin_context != None:
                # result.raw = u(plugin_context.title)
                # result.name = u("插件 %s (%s)") % (u(plugin_context.title), unquote_name)
                if plugin_context.title != None:
                    result.name = u("[插件] " + plugin_context.title + "(" +
                                    unquote_name + ")")
            result.url = u("/plugins/" + unquote_name)
            result.edit_link = u("/code/edit?path=" +
                                 os.path.join(dirname, fname))
            results.append(result)
    ctx.tools += results
Example #2
0
def on_search_plugins(ctx):
    if not xauth.is_admin():
        return
    if not ctx.search_tool:
        return
    if ctx.search_dict:
        return

    results = []

    for plugin in search_plugins(ctx.key):
        result = SearchResult()
        result.category = "plugin"
        result.icon = "fa-cube"
        result.name = u(plugin.name)
        result.name = u(plugin.title + "(" + plugin.name + ")")
        result.url = u(plugin.url)
        result.edit_link = plugin.edit_link
        results.append(result)

    result_count = len(results)
    if ctx.category != "plugin" and len(results) > 3:
        results = results[:3]
        more = SearchResult()
        more.name = u("查看更多插件(%s)") % result_count
        more.icon = "fa-cube"
        more.url = "/plugins_list?category=plugin&key=" + ctx.key
        results.append(more)
    ctx.tools += results
Example #3
0
def find_plugin_by_name(name):
    plugins = list_plugins("all")
    name, ext = os.path.splitext(name)
    for p in plugins:
        if u(p.name) == u(name):
            return p
    return None
Example #4
0
def on_search_plugins(ctx):
    if not xauth.is_admin():
        return
    if not ctx.search_tool:
        return
    if ctx.search_dict:
        return
    name = ctx.key
    results = []
    words = textutil.split_words(name)
    for name in xconfig.PLUGINS_DICT:
        plugin = xconfig.PLUGINS_DICT[name]
        unquote_name = xutils.unquote(plugin.fname)
        unquote_name, ext = os.path.splitext(unquote_name)
        plugin_context = plugin
        if textutil.contains_all(unquote_name, words) \
                or (textutil.contains_all(plugin_context.title, words)):
            result = SearchResult()
            result.category = "plugin"
            result.icon = "fa-cube"
            result.name = u(unquote_name)
            if plugin_context != None:
                # result.raw = u(plugin_context.title)
                # result.name = u("插件 %s (%s)") % (u(plugin_context.title), unquote_name)
                if plugin_context.title != None:
                    result.name = u(plugin_context.title + "(" + unquote_name +
                                    ")")
            result.url = u(plugin.url)
            result.edit_link = u("/code/edit?path=" + plugin.fpath)
            results.append(result)
    ctx.tools += results
Example #5
0
def search_menu(files, name):
    for category in xconfig.MENU_LIST:
        if category.need_login and not xauth.has_login():
            continue
        if category.need_admin and not xauth.is_admin():
            continue
        for child in category.children:
            if text_contains(u(child.name), u(name)):
                files.append(Storage(name='菜单 - ' + child.name, url=child.url))
Example #6
0
def wrap_results(dicts, origin_key):
    files = []
    for f0 in dicts:
        f = SearchResult()
        f.name = u("翻译 - ") + u(f0[origin_key])
        f.raw = f0["en"] + "\n"
        f.raw += f0["cn"].replace("\\n", "\n")
        f.url = "#"
        files.append(f)
    return files
Example #7
0
 def __init__(self):
     # 输入框的行数
     self.rows = 20
     # 提交请求的方法
     self.method = "POST"
     self.output = u("")
     self.html = u("")
     self.css_style = u("")
     self.show_pagenation = False
     self.page_url = "?page="
     self.option_links = []
Example #8
0
def search_plugins(name):
    results = []
    dirname = xconfig.PLUGINS_DIR
    for fname in xutils.listdir(dirname):
        if name in fname:
            result = SearchResult()
            result.category = "plugin"
            result.name = u("插件 - " + fname)
            result.url = u("/plugins/" + fname)
            result.edit_link = u("/code/edit?path=" +
                                 os.path.join(dirname, fname))
            results.append(result)
    return results
Example #9
0
def build_done_html(message):
    task = None
    done_time = message.done_time

    if message.ref != None:
        task = MSG_DAO.get_by_id(message.ref)

    if task != None:
        message.html = u("完成任务:<br>&gt;&nbsp;") + xutils.mark_text(
            task.content)
    elif done_time is None:
        done_time = message.mtime
        message.html += u("<br>------<br>完成于 %s") % done_time
Example #10
0
def search(name):
    if not xauth.is_admin():
        return None
    results = []
    for fname in xutils.listdir(xconfig.SCRIPTS_DIR):
        if name in fname:
            result = xutils.SearchResult()
            result.name = xutils.u("脚本 - ") + fname
            result.raw = xutils.u("搜索到可执行脚本 - ") + fname
            result.url = xutils.u(
                "/system/script_admin?op=edit&name=%s") % fname
            result.command = xutils.u(
                "/system/script_admin/execute?name=%s") % fname
            results.append(result)
    return results
Example #11
0
def search_plugins(name):
    results = []
    dirname = xconfig.PLUGINS_DIR
    words = textutil.split_words(name)
    for fname in xutils.listdir(dirname):
        unquote_name = xutils.unquote(fname)
        if textutil.contains_all(unquote_name, words):
            result = SearchResult()
            result.category = "plugin"
            result.name = u("插件 - " + unquote_name)
            result.url = u("/plugins/" + fname)
            result.edit_link = u("/code/edit?path=" +
                                 os.path.join(dirname, fname))
            results.append(result)
    return results
Example #12
0
def search(name):
    global _api_name_dict
    results = []
    for task_name in _api_name_dict:
        task_command = _api_name_dict[task_name]
        # task_name = six.u(task_name)
        task_name = xutils.u(task_name)
        # print(name, task_name)
        if name in task_name:
            result = SearchResult()
            result.name = xutils.u("系统接口 - ") + task_name
            result.command = "/api/%s" % task_command
            result.url = result.command
            results.append(result)
    return results
Example #13
0
 def deco(func):
     handler = SearchHandler(event_type, func, description=description)
     # unicode_pat = r"^%s\Z" % u(pattern)
     unicode_pat = u(pattern)
     handler.pattern = re.compile(unicode_pat)
     _event_manager.add_handler(handler)
     return func
Example #14
0
def search_scripts(name):
    results = []
    for fname in xutils.listdir(xconfig.SCRIPTS_DIR):
        fpath = os.path.join(xconfig.SCRIPTS_DIR, fname)
        if not os.path.isfile(fpath):
            continue
        if fname.endswith(".zip"):
            continue
        if name in fname:
            result         = xutils.SearchResult()
            result.name    = xutils.u("脚本 - ") + fname
            result.raw     = xutils.u("搜索到可执行脚本 - ") + fname
            result.url     = xutils.u("/code/edit?path=%s") % fpath
            result.command = xutils.u("/system/script_admin/execute?name=%s") % fname
            results.append(result)
    return results
Example #15
0
    def render(self):
        """图形界面入口"""
        if self.require_admin:
            xauth.check_login("admin")
        input = self.get_input()
        error = u("")
        output = u("")
        try:
            self.page = self.get_page()
            self.category_name = CATEGORY_NAME_DICT.get(self.category, '上级目录')
            output = self.handle(input) or u("")
            if self.get_format() == "text":
                web.header("Content-Type", "text/plain; charset:utf-8")
                return self.output + output

            # 复杂对象交给框架处理
            if isinstance(output, (dict, list)):
                return output

            # 处理侧边栏显示
            if self.aside_html != "" or len(
                    self.option_links) > 0 or self.category:
                self.show_aside = True
        except web.webapi.Redirect:
            # 跳转的异常
            pass
        except:
            error = xutils.print_exc()
            web.ctx.status = "500 Internal Server Error"
        return render("plugins/base_plugin.html",
                      model=self,
                      script_name=globals().get("script_name"),
                      fpath=self.fpath,
                      description=self.description,
                      error=error,
                      html_title=self.title,
                      title=self.title,
                      method=self.method,
                      rows=self.rows,
                      input=input,
                      output=self.output + output,
                      css_style=self.css_style,
                      show_aside=self.show_aside,
                      show_search=self.show_search,
                      html=self.html,
                      search_action=self.search_action,
                      search_placeholder=self.search_placeholder)
Example #16
0
    def test_create_name_exits(self):
        create_note_for_test("md", "name-test")
        result = json_request("/note/create",
                              method="POST",
                              data=dict(name="name-test"))
        self.assertEqual(xutils.u('name-test 已存在'), result['message'])

        delete_note_for_test("name-test")
Example #17
0
 def handle(self, input):
     self.description = '''请输入插件名称'''
     self.title = '通过模板创建插件'
     self.btn_text = '创建'
     self.rows = 1
     if input != '':
         name = os.path.join(xconfig.PLUGINS_DIR, input)
         if not name.endswith(".py"):
             name += ".py"
         if os.path.exists(name):
             return u("文件[%s]已经存在!") % u(name)
         user_name = xauth.get_current_name()
         code = xconfig.get("NEW_PLUGIN_TEMPLATE", DEFAULT_PLUGIN_TEMPLATE)
         code = code.replace("$since", xutils.format_datetime())
         code = code.replace("$author", user_name)
         xutils.writefile(name, code)
         log_plugin_visit(os.path.basename(name))
         raise web.seeother('/code/edit?path=%s' % name)
Example #18
0
 def handle(self, input):
     self.title = '通过模板创建命令扩展'
     self.description = '''请输入命令扩展名称'''
     self.btn_text = '创建'
     self.rows = 1
     self.editable = False
     if input != '':
         name = os.path.join(xconfig.COMMANDS_DIR, input)
         if not name.endswith(".py"):
             name += ".py"
         if os.path.exists(name):
             return u("文件[%s]已经存在!") % u(name)
         user_name = xauth.get_current_name()
         code = xconfig.get("NEW_COMMAND_TEMPLATE", DEFAULT_COMMAND_TEMPLATE)
         code = code.replace("$since", xutils.format_datetime())
         code = code.replace("$author", user_name)
         xutils.writefile(name, code)
         raise web.seeother('/code/edit?path=%s' % name)
Example #19
0
def search(ctx, name):
    global _api_name_dict
    if not xauth.is_admin():
        return
    if not ctx.search_tool:
        return
    results = []
    for task_name in _api_name_dict:
        task_command = _api_name_dict[task_name]
        # task_name = six.u(task_name)
        task_name = xutils.u(task_name)
        # print(name, task_name)
        if name in task_name:
            result = SearchResult()
            result.name = xutils.u("系统接口 - ") + task_name
            result.command = "/api/%s" % task_command
            result.url = result.command
            results.append(result)
    return results
    def GET(self):
        city_code = xutils.get_argument("city_code", "101020100")
        city_name = xutils.get_argument("city_name", "上海")
        city_name = xutils.u(city_name)

        message = None

        db = xtables.get_record_table()
        record = db.select_one(where="type='weather' AND DATE(ctime)=$date_str AND key=$key", 
            vars=dict(date_str=xutils.format_date(), key=city_name))
        if record is not None:
            message = record.value
        else:
            url = "http://www.weather.com.cn/weather1d/%s.shtml" % city_code
            html = six.moves.urllib.request.urlopen(url).read()
            if html == b"<!-- empty -->":
                return dict(code="fail", message=u("city_code错误"))
            soup = BeautifulSoup(html, "html.parser")
            elements = soup.find_all(id="hidden_title")
            # print(elements)
            # print(len(html))
            # return html
            if len(elements) > 0:
                weather = elements[0]
                message = weather.attrs["value"]
                message = message.replace("/", u("至"))
                db.insert(ctime=xutils.format_datetime(), 
                    cdate=xutils.format_date(),
                    type="weather",
                    key=city_name,
                    value=message
                )

        if message is not None:
            message = u(message)
            if not xconfig.is_mute():
                xutils.say("%s %s" % (city_name, message))
            # six.print_(type(message), message)
            return dict(code="success", data=message)
        else:
            return dict(code="fail", message="结果为空")
Example #21
0
def add_rule(pattern, func_str):
    global _RULES
    try:
        mod, func_name = func_str.rsplit('.', 1)
        # mod = __import__(mod, None, None, [''])
        mod = six._import_module("handlers.search." + mod)
        func = getattr(mod, func_name)
        func.modfunc = func_str
        rule = BaseRule(r"^%s\Z" % u(pattern), func)
        _RULES.append(rule)
    except Exception as e:
        xutils.print_exc()
Example #22
0
File: fs.py Project: ydx2099/xnote
 def GET(self, path):
     path = xutils.unquote(path)
     path = xutils.get_real_path(path)
     path = u(path)
     if not self.is_path_allowed(path):
         xauth.check_login("admin")
     data_prefix = u(xconfig.DATA_DIR)
     if not path.startswith("static"):
         newpath = os.path.join(data_prefix, path)
     else:
         newpath = path
         # 兼容static目录数据
         if not os.path.exists(newpath):
             # len("static/") = 7
             newpath = os.path.join(data_prefix, newpath[7:])
     path = newpath
     if not os.path.isfile(path):
         # 静态文件不允许访问文件夹
         web.ctx.status = "404 Not Found"
         return "Not Readable %s" % path
     return self.handle_get(path)
Example #23
0
def on_search_message(ctx):
    key = ctx.key
    touch_key_by_content(ctx.user_name, 'key', key)

    messages, count = MSG_DAO.search(ctx.user_name, key, 0, 3)
    for message in messages:
        item = SearchResult()
        if message.content != None and len(
                message.content) > xconfig.SEARCH_SUMMARY_LEN:
            message.content = message.content[:xconfig.
                                              SEARCH_SUMMARY_LEN] + "......"
        process_message(message)
        item.name = u('记事 - ') + message.ctime
        item.html = message.html
        ctx.messages.append(item)
        # print(message)
    if count > 3:
        more = SearchResult()
        more.name = "查看更多记事(%s)" % count
        more.url = "/message?key=" + ctx.key
        ctx.messages.append(more)
Example #24
0
    def render(self):
        """图形界面入口"""
        if self.require_admin:
            xauth.check_login("admin")
        input = self.get_input()
        error = ""
        output = u("")
        try:
            self.page = self.get_page()
            output = self.handle(input) or ""
            if self.get_format() == "text":
                web.header("Content-Type", "text/plain; charset:utf-8")
                return self.output + output

            # 复杂对象交给框架处理
            if isinstance(output, (dict, list)):
                return output

            # 处理侧边栏显示
            if self.aside_html != "" or len(
                    self.option_links) > 0 or self.category:
                self.show_aside = True
        except:
            error = xutils.print_exc()
        return render("plugins/base_plugin.html",
                      model=self,
                      script_name=globals().get("script_name"),
                      description=self.description,
                      error=error,
                      html_title=self.title,
                      title=self.title,
                      method=self.method,
                      rows=self.rows,
                      input=input,
                      output=self.output + output,
                      css_style=self.css_style,
                      show_aside=self.show_aside,
                      html=self.html,
                      search_action=self.search_action,
                      search_placeholder=self.search_placeholder)
Example #25
0
 def writehtml(self, html):
     self.html += u(html)
Example #26
0
 def test_create_note_invalid_type(self):
     result = json_request("/note/create",
                           method="POST",
                           data=dict(type="invalid", name="invalid-test"))
     self.assertEqual(xutils.u("无效的类型: invalid"), result["message"])
Example #27
0
 def test_create_name_empty(self):
     result = json_request("/note/create",
                           method="POST",
                           data=dict(name=""))
     self.assertEqual(xutils.u('标题为空'), result['message'])
Example #28
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")
        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 = 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)

        heading = T("创建笔记")
        code = "fail"
        error = ""
        ctx = Storage(method = method)
        
        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)

        return xtemplate.render("note/page/create.html", 
            show_search = False,
            heading  = heading,
            key      = "", 
            type     = type,
            name     = key, 
            tags     = tags, 
            error    = error,
            message  = error,
            NOTE_TYPE_LIST = NOTE_TYPE_LIST,
            groups   = NOTE_DAO.list_group(creator),
            code     = code)
Example #29
0
File: fs.py Project: ydx2099/xnote
 def GET(self):
     user_name = xauth.current_name()
     datapath = u(os.path.abspath(xconfig.DATA_DIR))
     homepath = os.path.join(datapath, "files", user_name)
     raise web.seeother("/fs/%s" % homepath)
Example #30
0
 def writetemplate(self, template, **kw):
     html = render_text(template, **kw)
     self.html += u(html.decode("utf-8"))