Exemple #1
0
def on_msg(msg):
    msg_type = msg.type
    from_user = msg.member.name
    now = msg.create_time
    # 处理撤回的消息
    if msg_type == wxpy.NOTE:
        revoked = ETree.fromstring(msg.raw['Content'].replace(
            '&lt;', '<').replace('&gt;', '>')).find('revokemsg')
        if revoked:
            # 根据找到的撤回消息 id 找到 bot.messages 中的原消息
            revoked_msg = bot.messages.search(
                id=int(revoked.find('msgid').text))[0]
            if not revoked_msg:
                return
            with locks[from_user]:
                session = Session()
                title_or_thinking = get_column(revoked_msg.type)
                sharing = session.query(Sharing).filter(
                    Sharing.name == from_user).filter(
                        getattr(Sharing, title_or_thinking) ==
                        revoked_msg.text).first()
                setattr(sharing, title_or_thinking, None)
    else:
        with locks[from_user]:
            c = get_column(msg_type)
            min_length = getattr(settings, 'min_thinking_len', 1)
            if c == 'title' or len(msg.text) >= min_length:
                upsert(from_user, c, msg.text, now)
            else:
                logger.warning(msg.text + ' of length %d less than %d' %
                               (len(msg.text), min_length))
Exemple #2
0
def send_report():
    from_time = settings.from_time
    session = Session()
    res = '累计打卡(%s起)\n' % from_time
    for row in session.query(Sharing.name, func.count().label('credit'))\
                               .filter(Sharing.title.isnot(None) & Sharing.thinking.isnot(None))\
                               .group_by(Sharing.name)\
                               .order_by(desc('credit')):
        res += '    %s: %.1f\n' % (row.name, row.credit * 0.2)
    with engine.connect() as con:
        today_daka = pd.read_sql_query(
            "select * from sharing where date(time) >= current_date order by id desc",
            con)
        today_daka.rename(inplace=True,
                          columns={
                              'id': '序号',
                              'name': '姓名',
                              'title': '标题',
                              'thinking': '感想',
                              'time': '时间'
                          })
        now = datetime.datetime.now()
        if not os.path.isdir('daka'):
            os.mkdir('daka')
        filename = "daka/%s(00.00.00-%s).xlsx" % (
            now.date().strftime('%Y-%m-%d'), now.time().strftime('%H.%M.%S'))
        to_excel(today_daka, filename)

    for group in bot.groups().search(settings.notice_group_name):
        group.send(res)
        group.send_file(filename)
Exemple #3
0
def postHost(request):
    ip = request.POST.get('ip', '')
    uname = request.POST.get('username', '')
    pwd = request.POST.get('password', '')
    Client(ip=ip, uname=uname, pwd=pwd)
    session = Session(ip=ip)
    session.setHost()
    return HttpResponse(json.dumps({"info": "success"}))
Exemple #4
0
def get_user(chat_id=None, id=None):
    if not chat_id and not id:
        return None

    if chat_id:
        _res = [
            x for x in Session().query(User).filter(User.chat_id == chat_id)
        ]
        return _res[0] if _res else None

    if id:
        _res = [x for x in Session().query(User).filter(User.id == id)]
        return _res[0] if _res else None
Exemple #5
0
def upsert(user, title_or_thinking, text, time):
    # ensure unique
    today = time.date()
    tomorrow = today + timedelta(days=1)
    session = Session()
    count = session.query(func.count(Sharing.id))\
        .filter(
            (Sharing.time >= today) &
            (Sharing.time < tomorrow) &
            (Sharing.name == user) &
            (Sharing.title.isnot(None)) &
            (Sharing.thinking.isnot(None))
        ).scalar()
    if count >= settings.max_daka_per_day:
        return

    sharing = session.query(Sharing).filter(
        (Sharing.time >= today) & (Sharing.time < tomorrow)
        & (Sharing.name == user)
        & (getattr(Sharing, title_or_thinking) == None)).first()
    if sharing is None:
        sharing = Sharing(**{'name': user})
        session.add(sharing)
    sharing.time = time
    setattr(sharing, title_or_thinking, text)
    try:
        session.commit()
    except IntegrityError as e:
        logger.error(str(e))
        logger.warning('conflict %s from %s: %s' %
                       (title_or_thinking, user, text))
    except StaleDataError as e:
        logger.error(str(e))
        logger.warning('conflict %s from %s: %s' %
                       (title_or_thinking, user, text))
    def __init__(self, gitRepo, app, system, settings):
        QWidget.__init__(self)

        from errors import ErrorHandler, DialogErrorView

        self.settings = settings

        self.errors = ErrorHandler(DialogErrorView(self, app))

        self.session = Session(gitRepo, self.errors)

        self.text_saved = True

        self.buttons_bar = QWidget()

        self.project_tree = SourcesTree(self.session, system, self.errors)
        self.project_tree.source_selection_changed.connect(
            self._on_file_selection_)
        self.session.sources_changed.connect(self.project_tree.update_model)

        self.editor = EditorPanel(self.settings)
        self.session.content_changed.connect(self.editor.displayText)
        self.editor.content_changed.connect(
            lambda: self.session.set_active_file_content(self.editor.plainText
                                                         ))

        self.webview = QWebView()

        self.images_gallery = ImagesPanel(self.session, self.settings)

        self.session.html_output_changed.connect(
            lambda: self.display_local_html_file(self.session.
                                                 active_file_output))

        self.session.html_content_changed.connect(
            lambda: self.webview.reload())

        self.images_gallery.on_insert_image.connect(
            self.insert_image_in_current_position)

        self.layout_toolbar()

        self.layout_components()

        self.session.start()

        any_file = find_first_file(self.session.get_sources_structure())
        if any_file:
            self.project_tree.setSelectedFile(any_file)
Exemple #7
0
def operations(msg):
    if True or msg.is_at:
        text = get_text_without_at_bot(msg).strip()
        if '今日打卡' == text:
            send_report()
        elif '打卡改名为' in text:
            if msg.sender != bot.self:
                return "没有权限"
            origin, new = text.split('打卡改名为')
            session = Session()
            sharings = session.query(Sharing).filter(
                Sharing.name.like('%' + origin + '%')).all()
            for s in sharings:
                s.name = new
            session.commit()
Exemple #8
0
    def post(self):
        """
        param: {
            'user_name': email or telephone,
            'password': password,
            'verify_code': verify code,
            'verify_key': verify key
         }
        """
        param_dict = escape.json_decode(self.request.body)
        if not self.is_param_valid(param_dict):
            self.write_rows(code=-1, msg="Param can not be empty.")
            return
        try:
            user_name = param_dict['user_name'].encode('utf-8').strip()
            is_verified = user_cache.is_code_verified(
                param_dict['verify_code'], param_dict['verify_key'])
            if user_name.startswith("email_"):
                user_name = user_name[6:]
                user_hash = hashlib.md5(user_name).hexdigest().encode('utf-8')
            elif user_name.startswith("phone_"):
                username = user_name.replace("phone_", "")
                result = yield user_model.get_user_hash_by_phone(username)
                if not result:
                    self.write_rows(code=-1, msg='User does not exist.')
                    return
                user_hash = result.get('user_hash')
            else:
                self.write_rows(code=-1, msg='Param error.')
                return

            login_res = yield user_model.user_login(
                user_hash, param_dict['password'].strip())
            if login_res == 1:
                user_info = yield user_model.get_info_by_hash(user_hash)
                Session.create_session(user_info, self)
                self.write_rows(msg=u'登陆成功', rows=user_info)
            elif login_res == -2:
                self.write_rows(code=-1, msg=u'用户名或密码错误')
            elif login_res == -1:
                self.write_rows(code=-1, msg=u'用户被禁用')
            elif login_res == 0:
                self.write_rows(code=-1, msg=u'用户未激活')
        except KeyError:
            self.write_rows(code=-1, msg='Missing argument.')
Exemple #9
0
def add_user(id: int, chat_id: int, status="inactive") -> User:
    _user = User(id=id, chat_id=chat_id, status=status)
    _sess = Session()
    _sess.add(_user)
    _sess.commit()

    return _user
Exemple #10
0
def add_user(ip: str) -> User:
    salt = ''.join([chr(randint(97, 122)) for _ in range(15)])
    hash = md5((ip + salt).encode('utf-8')).hexdigest()
    _user = User(ip=ip, hash=hash, salt=salt)
    _sess = Session()
    _sess.add(_user)
    _sess.commit()

    return _user
Exemple #11
0
class SessionPanel(QWidget):
    def __init__(self, gitRepo, app, system, settings):
        QWidget.__init__(self)

        from errors import ErrorHandler, DialogErrorView

        self.settings = settings

        self.errors = ErrorHandler(DialogErrorView(self, app))

        self.session = Session(gitRepo, self.errors)

        self.text_saved = True

        self.buttons_bar = QWidget()

        self.project_tree = SourcesTree(self.session, system, self.errors)
        self.project_tree.source_selection_changed.connect(
            self._on_file_selection_)
        self.session.sources_changed.connect(self.project_tree.update_model)

        self.editor = EditorPanel(self.settings)
        self.session.content_changed.connect(self.editor.displayText)
        self.editor.content_changed.connect(
            lambda: self.session.set_active_file_content(self.editor.plainText
                                                         ))

        self.webview = QWebView()

        self.images_gallery = ImagesPanel(self.session, self.settings)

        self.session.html_output_changed.connect(
            lambda: self.display_local_html_file(self.session.
                                                 active_file_output))

        self.session.html_content_changed.connect(
            lambda: self.webview.reload())

        self.images_gallery.on_insert_image.connect(
            self.insert_image_in_current_position)

        self.layout_toolbar()

        self.layout_components()

        self.session.start()

        any_file = find_first_file(self.session.get_sources_structure())
        if any_file:
            self.project_tree.setSelectedFile(any_file)

    def setSyncScrolling(self, flag):
        if flag:
            self.editor.verticalScrollBar().valueChanged.connect(
                self._sync_webview_scroll_)
        else:
            self.editor.verticalScrollBar().valueChanged.disconnect(
                self._sync_webview_scroll_)

    def _sync_webview_scroll_(self, value):
        scrollRange = self.editor.verticalScrollBar().maximum()
        if scrollRange == 0:
            return
        fraction = float(value) / scrollRange
        frame = self.webview.page().mainFrame()
        pnt = frame.scrollPosition()
        size = frame.contentsSize()
        self.webview.page().mainFrame().setScrollPosition(
            QPoint(pnt.x(), fraction * size.height()))

    def insert_image_in_current_position(self, path):
        from editr_actions import format_image
        self.editor.insert_directive_in_current_position(
            format_image(path, width=self.settings.figure_width))

    def _on_file_selection_(self, selected_file):
        if selected_file and not selected_file.is_dir:
            self.session.set_active_file(selected_file.local_path)
            self.images_gallery.show_source_images(selected_file.local_path)

    def display_local_html_file(self, file_path_string):
        import os
        if not file_path_string:
            self.errors.show("Can't show Null html file")
            return

        if not os.path.exists(file_path_string):
            self.errors.show(
                'Could not load html file {} because it does not exist'.format(
                    file_path_string))
        else:
            self.webview.load(QUrl.fromLocalFile(file_path_string))

    def display_url(self, url_string):
        self.webview.load(QUrl(url_string))

    def layout_toolbar(self):
        import icons
        # save = QPushButton("Save")
        # save.clicked.connect(lambda: self.errors.show("Hi, nice to meet you"))

        # sync_scroll = QSlideSwitch()
        sync_scroll = QCheckBox()
        sync_scroll.setText('Sync Scroll')
        sync_scroll.clicked.connect(
            lambda: self.setSyncScrolling(sync_scroll.isChecked()))
        if self.settings.sync_scrolling:
            sync_scroll.animateClick()

        repo = QComboBox()
        repo.setEditable(True)
        repo.setMinimumWidth(200)

        remote = self.session.remote_address

        # Async repos check
        repo.addItem(remote.split(':')[1])

        def collect_repo_names(local_dirs):
            collection = []
            print local_dirs
            for recent in local_dirs:
                r = GitRepository(recent)
                if r.address != remote:
                    collection.append(r.address.split(':')[1])
            return collection

        def apply_names(names):
            print names
            for name in names:
                repo.addItem(name)

        collect_repos = CustomRoutine(collect_repo_names)
        collect_repos.when_finished.connect(apply_names)
        collect_repos.start(self.settings.recent_existing)

        # UI thread repos check
        # repo.addItem(remote.split(':')[1])
        # for recent in self.settings.recent_existing:
        #     r = GitRepository(recent)
        #     if r.address != remote:
        #         repo.addItem(r.address.split(':')[1])

        update = QPushButton("Update")
        update.clicked.connect(lambda: self.errors.ask_yes_no("Do you?"))

        commit = QPushButton("Commit")

        loadExternal = QPushButton()
        loadExternal.setIcon(icons.webbrowser())
        loadExternal.setToolTip('Open webpage in external browser')
        loadExternal.clicked.connect(self.open_build_external)

        layout = QHBoxLayout()
        layout.addWidget(repo)
        layout.addSpacing(20)
        layout.addWidget(update)
        layout.addWidget(commit)
        layout.addStretch(0)
        layout.addWidget(sync_scroll)
        layout.addStretch(0)
        layout.addWidget(loadExternal)

        self.buttons_bar.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed))
        self.buttons_bar.setLayout(layout)

    def show_url(self, url_string):
        self.webview.load(QUrl(url_string))

    def open_build_external(self):
        import webbrowser
        webbrowser.open('file://' + self.session.active_file_output)

    def layout_components(self):
        container = QSplitter()
        container.setOrientation(Qt.Horizontal)

        left_widget = QSplitter()
        pal = left_widget.palette()
        pal.setColor(QPalette.Background, QColor(226, 226, 226))
        left_widget.setPalette(pal)
        left_widget.setMaximumWidth(300)
        left_widget.setOrientation(Qt.Vertical)
        left_widget.addWidget(self.project_tree)
        left_widget.addWidget(self.images_gallery)

        container.addWidget(left_widget)

        container.addWidget(self.editor)
        self.editor.setMinimumWidth(600)

        container.addWidget(self.webview)

        layout = QVBoxLayout()
        layout.addWidget(self.buttons_bar)
        layout.setSpacing(0)
        layout.addWidget(ThinLine())
        layout.addWidget(container)
        layout.setContentsMargins(0, 0, 0, 0)

        self.setLayout(layout)
Exemple #12
0
def set_args(args: dict, user: User) -> None:
    _sess = Session()
    _sess.query(User).filter(User.id == user.id). \
        update(args, synchronize_session=False)
    _sess.commit()
Exemple #13
0
def is_hash_unique(hash: str) -> bool:
    return not bool(
        [x for x in Session().query(User).filter(User.hash == hash)])
Exemple #14
0
 def get_session(self):
     return Session.get_session(self)
Exemple #15
0
        import qdarkstyle
        from PyQt5 import QtGui
        from PyQt5.QtWidgets import QApplication
        from GUI import MainWindow

        if "local" in args.session:
            from core import Local_session as Session
        else:
            from core import Live_session as Session

        app = QApplication(sys.argv)
        app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        launch = MainWindow(
            Session(mode=args.mode,
                    config=args.config,
                    contract_type='classic'))
        launch.show()
        sys.exit(app.exec_())

    elif args.build:
        from core import Local_session as Session
        args.build = "PPO"
        session = Session(mode=args.mode,
                          config=args.config,
                          contract_type='classic',
                          agent=args.build)
        session._stop()

    else:
        if "local" in args.session:
Exemple #16
0
def get_user(ip: str) -> User:
    _res = [x for x in Session().query(User).filter(User.ip == ip)]
    return _res[0] if _res else None
Exemple #17
0
 def get(self):
     Session.logout(self)
     self.write_response()
Exemple #18
0
 def session(self):
     sessionid = self.get_secure_cookie('sid')
     session = Session(self.application.session_store, sessionid)
     if not sessionid:
         self.set_secure_cookie('sid', session._sessionid)
     return session