Esempio n. 1
0
def _main():
    """
    Main Logic
    :return:
    """
    # Initialization
    login = Login()
    article_id_spider = ArticleIdSpider()
    article_content_spider = ArticleContentSpider()
    print("Backup Path : %s" % GLO_CONFIG['download_path'])
    print("Download Picture Or Not ?  %s" % GLO_CONFIG['download_img'])

    # login in csdn and get user data
    user = login.dologin(GLO_CONFIG['username'], GLO_CONFIG['password'])

    # backup article
    global HOME_URL
    article_ids = article_id_spider.getArticleId(
        HOME_URL + user['username'], HOME_URL + user['username'] + PAGE_URL)
    article_content_spider.getArticle(GLO_CONFIG['download_path'],
                                      GLO_CONFIG['download_img'], MARKDOWN_URL,
                                      article_ids, user['cookies'])

    # end
    print('')
    print(
        "User %s have a total of %s articles, It's all finished. Please check it."
        % (user['username'], str(len(article_ids))))

    input("--------------------end-----------------------")
Esempio n. 2
0
def main():
    debug = False

    def version():
        log.info_log('version %s' % __version__)

    try:
        opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
    except getopt.GetoptError as err:
        log.error_log(u"Try ee-book --help for more options")
        sys.exit(2)
    for option, args in opts:
        if option in ('-V', '--version'):
            version()
            sys.exit()
        elif option in ('-d', '--debug'):
            print u"Debug mode..."
            debug = True
        elif option in ('-h', '--help'):
            version()
            print(help_info)
            sys.exit()
        elif option in ('-g', '--gui'):
            print(u"Under developing...")
            sys.exit()
            # graphviz = GraphvizOutput(output_file='filter_gui.png')
            # with PyCallGraph(output=graphviz, config=config):
            # from PyQt4.QtGui import QApplication
            # from PyQt4.QtGui import QIcon
            # from src.gui.ui import MainWindow
            # from src.resources import qrc_resources
            # app = QApplication(sys.argv)
            # app.setWindowIcon(QIcon(":/icon.png"))
            # app.setApplicationName('EE-Book')
            # window = MainWindow()
            # window.show()
            # sys.exit(app.exec_())
        elif option in ('-l', '--login'):
            url = args
            try:
                recipe_kind = Match.get_url_kind(url)
            except UnsupportTypeException, e:
                print e
                print u"Please try again."
                sys.exit()
            zhihu = EEBook(
                recipe_kind=recipe_kind
            )  # Init path, e.g. config, only zhihu are supported now
            login = Login(recipe_kind=recipe_kind)
            login.start()
            sys.exit()
        elif option in ('-u', '--url'):
            url = args
            try:
                recipe_kind = Match.get_website_kind(url)
            except UnsupportTypeException, e:
                print e
                print u"Please check url."
                sys.exit()
Esempio n. 3
0
def main():
    debug = False

    def version():
        log.info_log('version %s' % __version__)
    try:
        opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
    except getopt.GetoptError as err:
        log.error_log(u"Try ee-book --help for more options")
        sys.exit(2)
    for option, args in opts:
        if option in ('-V', '--version'):
            version()
            sys.exit()
        elif option in ('-d', '--debug'):
            print u"Debug mode..."
            debug = True
        elif option in ('-h', '--help'):
            version()
            print(help_info)
            sys.exit()
        elif option in ('-g', '--gui'):
            print(u"Under developing...")
            sys.exit()
            # graphviz = GraphvizOutput(output_file='filter_gui.png')
            # with PyCallGraph(output=graphviz, config=config):
            # from PyQt4.QtGui import QApplication
            # from PyQt4.QtGui import QIcon
            # from src.gui.ui import MainWindow
            # from src.resources import qrc_resources
            # app = QApplication(sys.argv)
            # app.setWindowIcon(QIcon(":/icon.png"))
            # app.setApplicationName('EE-Book')
            # window = MainWindow()
            # window.show()
            # sys.exit(app.exec_())
        elif option in ('-l', '--login'):
            url = args
            try:
                recipe_kind = Match.get_url_kind(url)
            except UnsupportTypeException, e:
                print e
                print u"Please try again."
                sys.exit()
            zhihu = EEBook(recipe_kind=recipe_kind)    # Init path, e.g. config, only zhihu are supported now
            login = Login(recipe_kind=recipe_kind)
            login.start()
            sys.exit()
        elif option in ('-u', '--url'):
            url = args
            try:
                recipe_kind = Match.get_website_kind(url)
            except UnsupportTypeException, e:
                print e
                print u"Please check url."
                sys.exit()
Esempio n. 4
0
    def row_clicked(self, index):
        u"""
        哪一行被选中了
        :return:
        """
        url = str(self.recipes.model().data(index, QtCore.Qt.UserRole))
        self.now_url = url

        self.detail_box.setVisible(True)
        if url == 'zhihu':  # TODO: 改掉硬编码, 这里的信息(是否需要登录)应该用xml或数据库记录
            self.detail_box.setVisible(True)
            self.account.setVisible(True)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s<br/>
            %(description)s
            </p>
            ''' % dict(
                title='zhihu',
                cb='Created by: Frank',
                description=u'https://github.com/knarfeh/EE-Book <br/>第一次使用,请登录!\
                      若不登录,将尝试用程序内置账号登陆,私人收藏夹将无法爬取'))
            self.zhihu = EEBook(recipe_kind='zhihu')  # 目前只有知乎需要登陆 需要将Path初始化
            self.login = Login(recipe_kind='zhihu', from_ui=True)
        elif url == 'jianshu':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText(
                '''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' %
                dict(title='jianshu',
                     cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/jianshu2e-book'))
        elif url == 'sinablog':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' % dict(
                title='sinablog',
                cb='Created by: Frank',
                description=u'https://github.com/knarfeh/SinaBlog2e-book'))
        else:
            self.detail_box.setVisible(False)
        return self.recipes.model().data(index, QtCore.Qt.UserRole)
Esempio n. 5
0
 def test_login_passes_with_valid_form(self):
     form = {
         'email': '*****@*****.**',
         'name': 'customer_1',
         'mobile': '9876543210'
     }
     self.assertEqual(Login().validate(form), True)
Esempio n. 6
0
def main():

    # application specifics
    app = QApplication(sys.argv)

    # TODO: remove this, hardcoding it for testing
    QLocale.setDefault(QLocale(QLocale.Portuguese, QLocale.Brazil))

    # login dialog
    login_dialog = Login()
    if login_dialog.exec_() == QDialog.Accepted:
        # validation complete, open main interface
        window = MainWindow(login_dialog.get_user_data())
        window.showMaximized()
        # solves mainwindow focusing on windows/xfce
        app.setActiveWindow(window)
        # start main loop
        sys.exit(app.exec_())
Esempio n. 7
0
    def setupUi(self):
        login = Login()
        login.exec_()

        if login.isLogged():
            if login.getRole() == "Alumno": uic.loadUi("src/ui/main.ui", self)
            elif login.getRole() == "Profesor":
                uic.loadUi("src/ui/main.ui", self)
            elif login.getRole() == "Admin":
                uic.loadUi("src/ui/Administrador.ui", self)
                self.nID.setText(str(login.getId()))
                self.name.setText(login.getFullName())
                self.userManagerBtn.clicked.connect(self.userManagerClicked)
                self.scheduleBtn.clicked.connect(self.scheduleClicked)
                self.addUserBtn.clicked.connect(self.addUserClicked)
                self.acceptAddUser.clicked.connect(self.addUser)
                self.updateUserBtn.clicked.connect(self.EditUser)
                self.deleteUserBtn.clicked.connect(self.DelUser)

            self.showFullScreen()
            self.dbConfigAction.triggered.connect(self.dbConfigDialog)
        else:
            self.close()
Esempio n. 8
0
    def __init__(self, name=__name__):
        # Host from parameters
        Database.connect(host=args.mongo_host)

        # Make sure default config is on
        default_config = {
            'voting_round': 1,
            'voting_enabled': False,
            'proposing_enabled': True
        }

        for key, value in default_config.items():
            try:
                get_config(key)
            except:
                Database.theme_slaughter.config.insert_one({
                    '_id': key,
                    'value': value
                })

        # App
        app = Flask(name)

        # Github config
        app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
        app.config['GITHUB_CLIENT_ID'] = os.environ['GITHUB_CLIENT_ID']
        app.config['GITHUB_CLIENT_SECRET'] = os.environ['GITHUB_CLIENT_SECRET']
        self.github = GitHub(app)

        # Server side sessions
        app.config['SESSION_TYPE'] = 'mongodb'
        app.config['SESSION_MONGODB'] = Database.session
        Session(app)

        # Create rules
        app.add_url_rule('/', view_func=Index.as_view('index'))
        app.add_url_rule('/propose', view_func=Propose.as_view('propose'))
        app.add_url_rule('/vote', view_func=Vote.as_view('vote'))
        app.add_url_rule('/login/<next_uri>', view_func=Login.as_view('login'))
        app.add_url_rule('/do-login',
                         view_func=Authorize(self.github).as_view('do-login'))

        # Github login related rules
        app.add_url_rule('/github-callback',
                         view_func=self.github.authorized_handler(
                             AuthenticationHandler.as_view('github-callback')))
        AuthenticationToken(self.github)
        AuthenticationBefore(app, self.github)

        self.app = app
Esempio n. 9
0
    def row_clicked(self, index):
        u"""
        哪一行被选中了
        :return:
        """
        url = str(self.recipes.model().data(index, QtCore.Qt.UserRole))
        self.now_url = url

        self.detail_box.setVisible(True)
        if url == 'zhihu':          # TODO: 改掉硬编码, 这里的信息(是否需要登录)应该用xml或数据库记录
            self.detail_box.setVisible(True)
            self.account.setVisible(True)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s<br/>
            %(description)s
            </p>
            ''' % dict(title='zhihu', cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/EE-Book <br/>第一次使用,请登录!\
                      若不登录,将尝试用程序内置账号登陆,私人收藏夹将无法爬取'))
            self.zhihu = EEBook(recipe_kind='zhihu')    # 目前只有知乎需要登陆 需要将Path初始化
            self.login = Login(recipe_kind='zhihu', from_ui=True)
        elif url == 'jianshu':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' % dict(title='jianshu', cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/jianshu2e-book'))
        elif url == 'sinablog':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' % dict(title='sinablog', cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/SinaBlog2e-book'))
        else:
            self.detail_box.setVisible(False)
        return self.recipes.model().data(index, QtCore.Qt.UserRole)
Esempio n. 10
0
 def test_login_fails_with_numeric_emailId(self):
     # Make test fail
     form = {'email': 100}
     self.assertEqual(Login().validate(form), False)
Esempio n. 11
0
# -*- coding: utf-8 -*-
"""
Created on Mon May  6 21:57:12 2019

@author: xiong
"""

import unittest
import sys
sys.path.append("..")
from src.login import Login
login = Login(2109236844, b"123456xx")


# MD51(b'123456xx')
# 6D 43 EB D3 1B 9E 35 25 37 61 77 7E BA E5 D9 CF
# MD51 + hex(用户名)
# 6D 43 EB D3 1B 9E 35 25 37 61 77 7E BA E5 D9 CF
# 00 00 00 00 7D B8 66 6C
# MD52:
# B3 E2 EA AB C4 9B 6D 9F 6F DB C4 CF B8 E5 58 39
class TestLogin(unittest.TestCase):
    """Test src/login.py"""
    def test_get_md2(self):
        """Test methodshow_user()"""
        #self.login = Login(2109236844, b"123456xx")
        self.assertEqual("b3e2eaabc49b6d9f6fdbc4cfb8e55839", login.get_md2())


if __name__ == '__main__':
    unittest.main()
Esempio n. 12
0
class DownloadDialog(QDialog, Ui_Dialog):
    download = pyqtSignal(object)

    def __init__(self, recipe_model, book_view, parent=None):
        QDialog.__init__(self, parent)
        self.now_url = ''
        self.book_view = book_view

        self.setAttribute(Qt.WA_DeleteOnClose)      # 每次关闭对话框删除对话框所占的内存
        self.setupUi(self)
        self.recipe_model = recipe_model
        self.recipe_model.showing_count = 3     # TODO, 改掉这里的硬编码
        self.count_label.setText(
            # NOTE: Number of news sources
            ('%s news sources') % self.recipe_model.showing_count)

        self.download_button.setVisible(False)

        self.initialize_detail_box()
        self.detail_box.setVisible(False)

        self.recipes.setFocus(Qt.OtherFocusReason)
        self.recipes.setModel(self.recipe_model)
        self.recipes.setAlternatingRowColors(True)
        self.recipes.setHeaderHidden(False)

        self.show_password.stateChanged[int].connect(self.set_pw_echo_mode)
        self.download_button.clicked.connect(self.download_button_clicked)
        self.login_button.clicked.connect(self.login_button_clicked)

        self.setWindowTitle("Download")


        QtCore.QObject.connect(self.recipes, QtCore.SIGNAL("clicked (QModelIndex)"), self.row_clicked)

    def set_pw_echo_mode(self, state):
        self.password.setEchoMode(self.password.Normal if state == Qt.Checked else self.password.Password)

    def row_clicked(self, index):
        u"""
        哪一行被选中了
        :return:
        """
        url = str(self.recipes.model().data(index, QtCore.Qt.UserRole))
        self.now_url = url

        self.detail_box.setVisible(True)
        if url == 'zhihu':          # TODO: 改掉硬编码, 这里的信息(是否需要登录)应该用xml或数据库记录
            self.detail_box.setVisible(True)
            self.account.setVisible(True)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s<br/>
            %(description)s
            </p>
            ''' % dict(title='zhihu', cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/EE-Book <br/>第一次使用,请登录!\
                      若不登录,将尝试用程序内置账号登陆,私人收藏夹将无法爬取'))
            self.zhihu = EEBook(recipe_kind='zhihu')    # 目前只有知乎需要登陆 需要将Path初始化
            self.login = Login(recipe_kind='zhihu', from_ui=True)
        elif url == 'jianshu':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' % dict(title='jianshu', cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/jianshu2e-book'))
        elif url == 'sinablog':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' % dict(title='sinablog', cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/SinaBlog2e-book'))
        else:
            self.detail_box.setVisible(False)
        return self.recipes.model().data(index, QtCore.Qt.UserRole)

    def initialize_detail_box(self,):
        # self.previous_urn = urn
        self.detail_box.setVisible(True)
        self.download_button.setVisible(True)
        self.detail_box.setCurrentIndex(0)

    def login_button_clicked(self):
        account = str(self.username.text())
        password = str(self.password.text())
        captcha = str(self.captcha.text())

        if not self.login.login(account=account, password=password, captcha=captcha):
            click_ok = QtGui.QMessageBox.information(self, u"登陆失败", u"啊哦,登录失败,可能需要输入验证码\n请尝试输入验证码")
            if click_ok:
                self.login.get_captcha(from_ui=True)
                return
        Config.remember_account_set = True
        Config._save()
        QtGui.QMessageBox.information(self, u"登陆成功", u"恭喜, 登陆成功, 登陆信息已经保存")
        self.username.setText('')
        self.password.setText('')
        self.captcha.setText('')

    def download_button_clicked(self):
        tags = str(self.custom_tags.text())

        # url_id = self.recipes.model.data(1, QtCore.Qt.UserRole)    # TODO: 获得选中的recipes
        url_id = str(self.row_clicked(self.recipes.currentIndex()))

        if url_id == 'None':
            QtGui.QMessageBox.information(self, u"Error", u"选择需要爬取的网站!")
            return

        readlist_content = self.plainTextEdit.toPlainText()

        if readlist_content == '':
            QtGui.QMessageBox.information(self, u"Error", u"请在文本框中输入网址")
            return

        read_list_path = Path.read_list_path

        readList_file = open(read_list_path, 'w')
        readList_file.write(readlist_content)

        readList_file.close()

        game = EEBook(recipe_kind=url_id)

        progress_dlg = QProgressDialog(self)        # TODO: 设置大小, 区域
        progress_dlg.setWindowModality(Qt.WindowModal)
        progress_dlg.setMinimumDuration(5)
        progress_dlg.setWindowTitle(u"请等待")
        progress_dlg.setLabelText(u"制作中...请稍候")
        progress_dlg.setCancelButtonText(u"取消")
        progress_dlg.resize(350, 250)
        progress_dlg.show()
        progress_dlg.setRange(0, 20)

        for i in range(0, 15):
            progress_dlg.setValue(i)
            QThread.msleep(100)

        for i in range(15, 20):
            progress_dlg.setValue(i)
            QThread.msleep(100)
            if progress_dlg.wasCanceled():
                QtGui.QMessageBox.information(self, u"Error", u"电子书制作失败, 请重新操作")
                return

            try:
                filename = game.begin()      # TODO: 一次只能生成一本书
            except TypeError:
                QtGui.QMessageBox.information(self, u"Error", u"第一次使用请登录")
                progress_dlg.close()
                return
            progress_dlg.close()

            info_filename = ','.join(filename)
            QtGui.QMessageBox.information(self, u"info", u"电子书"+str(info_filename)+u"制作成功")

            for item in filename:
                file_path = EPUBSTOR_DIR + '/' + item
                Path.copy(str(file_path+'.epub'), LIBRARY_DIR)
                file_name = os.path.basename(str(file_path))
                book_id = file_name.split('.epub')[0]

                Path.mkdir(LIBRARY_DIR + book_id)
                shutil.move(LIBRARY_DIR+book_id+'.epub', LIBRARY_DIR+book_id)

                book = Book(str(book_id))
                book.date = time.strftime(ISOTIMEFORMAT, time.localtime())
                book.tags += tags.replace(' ', '')
                book.tags += ','+str(self.now_url)
                if self.add_title_tag.isChecked():
                    book.tags += ','+str(book.title)
                insert_library(book)
            return
Esempio n. 13
0
def login():
    return Login.login()
Esempio n. 14
0
def main():
    debug = False

    def version():
        log.info_log('version %s' % __version__)
    try:
        opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
    except getopt.GetoptError as err:
        log.error_log(u"Try ee-book --help for more options")
        sys.exit(2)
    for option, args in opts:
        if option in ('-V', '--version'):
            version()
            sys.exit()
        elif option in ('-d', '--debug'):
            print u"Debug mode..."
            debug = True
        elif option in ('-h', '--help'):
            version()
            print(help_info)
            sys.exit()
        elif option in ('-g', '--gui'):
            print(u"Under developing...")
            sys.exit()
            # graphviz = GraphvizOutput(output_file='filter_gui.png')
            # with PyCallGraph(output=graphviz, config=config):
            # from PyQt4.QtGui import QApplication
            # from PyQt4.QtGui import QIcon
            # from src.gui.ui import MainWindow
            # from src.resources import qrc_resources
            # app = QApplication(sys.argv)
            # app.setWindowIcon(QIcon(":/icon.png"))
            # app.setApplicationName('EE-Book')
            # window = MainWindow()
            # window.show()
            # sys.exit(app.exec_())
        elif option in ('-l', '--login'):
            url = args
            recipe_kind = Match.get_url_kind(url)
            if recipe_kind != 'zhihu':
                print("Unsupport type! Only zhihu are supported now.\n Please try again.")
                sys.exit()
            zhihu = EEBook(recipe_kind=recipe_kind)    # Init path, e.g. config, only zhihu are supported now
            login = Login(recipe_kind=recipe_kind)
            login.start()
            sys.exit()
        elif option in ('-u', '--url'):
            url = args
            recipe_kind = Match.get_website_kind(url)
            if recipe_kind == 'Unsupport type':
                print("Unsupported type!\n Please try again.")
                sys.exit()
            game = EEBook(recipe_kind=recipe_kind, url=url, debug=debug)
            game.begin()
            sys.exit()
        elif option in ('-i', '--info'):
            url = args
            url_kind = Match.get_url_kind(url)
            if url_kind == 'Unknown type':
                print('Unsupported website or url type. \nPlease check url.')
            else:
                info = url_info[url_kind]
                print(info)
            sys.exit()
        elif option in('-r', '--file'):
            file_name = args
            log.print_log(u'read from %s' % file_name)

            counter = 1
            try:
                with open(file_name, 'r') as read_list:
                    read_list = read_list.readlines()
                    line = read_list[0]
                    recipe_kind = Match.get_website_kind(line)
                    counter += 1
                    if recipe_kind == 'Unsupport type':
                        print('Unsupported website or url type. \nPlease check url.')
                        sys.exit()
            except IOError as e:
                Debug.logger.debug(u"\nCreating " + file_name + "...")
                with open(file_name, 'w') as read_list:
                    read_list.close()
            if 1 == counter:
                print(u"\nOops! No content in " + file_name + u". Please check it out.")
                sys.exit()

            print(u"website type:" + str(recipe_kind))
            game = EEBook(recipe_kind=recipe_kind, url=None, read_list=file_name)
            game.begin()
            sys.exit()
        elif option in('-c', '--cookies'):
            cookie_file = args
            print("Cookie_file:" + cookie_file)
            print("TODO: read from cookie to login")
            # with open(cookie_file) as f:
            #     content = f.read()
            # game = EEBook(recipe_kind='zhihu')
            # from src.tools.db import DB
            # from src.tools.extra_tools import ExtraTools
            # DB.execute('delete from LoginRecord')  # 登陆成功后清除数据库中原有的登录记录,避免下次登陆时取到旧记录
            # data = dict()
            # data['account'] = '*****@*****.**'
            # data['password'] = '******'
            # data['recordDate'] = ExtraTools.get_today()
            # data['cookieStr'] = content
            # DB.save(data, 'LoginRecord')
            # DB.commit()
            sys.exit()
    file_name = 'ReadList.txt'
    log.print_log(u'read from %s' % file_name)

    counter = 1
    try:
        with open(file_name, 'r') as read_list:
            read_list = read_list.readlines()
            line = read_list[0]
            recipe_kind = Match.get_website_kind(line)
            counter += 1
            if recipe_kind == 'Unsupport type':
                print('Unsupported website or url type. \nPlease check url.')
                sys.exit()
    except IOError as e:
        Debug.logger.debug(u"\nCreating " + file_name + "...")
        with open(file_name, 'w') as read_list:
            read_list.close()
    if 1 == counter:
        print(u"\nOops! No content in " + file_name + u". Please check it out.")
        sys.exit()

    print(u"website type:" + str(recipe_kind))
    game = EEBook(recipe_kind=recipe_kind, url=None, read_list=file_name)
    game.begin()
    sys.exit()
Esempio n. 15
0
class DownloadDialog(QDialog, Ui_Dialog):
    download = pyqtSignal(object)

    def __init__(self, recipe_model, book_view, parent=None):
        QDialog.__init__(self, parent)
        self.now_url = ''
        self.book_view = book_view

        self.setAttribute(Qt.WA_DeleteOnClose)  # 每次关闭对话框删除对话框所占的内存
        self.setupUi(self)
        self.recipe_model = recipe_model
        self.recipe_model.showing_count = 3  # TODO, 改掉这里的硬编码
        self.count_label.setText(
            # NOTE: Number of news sources
            ('%s news sources') % self.recipe_model.showing_count)

        self.download_button.setVisible(False)

        self.initialize_detail_box()
        self.detail_box.setVisible(False)

        self.recipes.setFocus(Qt.OtherFocusReason)
        self.recipes.setModel(self.recipe_model)
        self.recipes.setAlternatingRowColors(True)
        self.recipes.setHeaderHidden(False)

        self.show_password.stateChanged[int].connect(self.set_pw_echo_mode)
        self.download_button.clicked.connect(self.download_button_clicked)
        self.login_button.clicked.connect(self.login_button_clicked)

        self.setWindowTitle("Download")

        QtCore.QObject.connect(self.recipes,
                               QtCore.SIGNAL("clicked (QModelIndex)"),
                               self.row_clicked)

    def set_pw_echo_mode(self, state):
        self.password.setEchoMode(self.password.Normal if state ==
                                  Qt.Checked else self.password.Password)

    def row_clicked(self, index):
        u"""
        哪一行被选中了
        :return:
        """
        url = str(self.recipes.model().data(index, QtCore.Qt.UserRole))
        self.now_url = url

        self.detail_box.setVisible(True)
        if url == 'zhihu':  # TODO: 改掉硬编码, 这里的信息(是否需要登录)应该用xml或数据库记录
            self.detail_box.setVisible(True)
            self.account.setVisible(True)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s<br/>
            %(description)s
            </p>
            ''' % dict(
                title='zhihu',
                cb='Created by: Frank',
                description=u'https://github.com/knarfeh/EE-Book <br/>第一次使用,请登录!\
                      若不登录,将尝试用程序内置账号登陆,私人收藏夹将无法爬取'))
            self.zhihu = EEBook(recipe_kind='zhihu')  # 目前只有知乎需要登陆 需要将Path初始化
            self.login = Login(recipe_kind='zhihu', from_ui=True)
        elif url == 'jianshu':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText(
                '''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' %
                dict(title='jianshu',
                     cb='Created by: Frank',
                     description=u'https://github.com/knarfeh/jianshu2e-book'))
        elif url == 'sinablog':
            self.detail_box.setVisible(True)
            self.account.setVisible(False)
            self.blurb.setText('''
            <p>
            <b>%(title)s</b><br>
            %(cb)s <br/>
            %(description)s
            </p>
            ''' % dict(
                title='sinablog',
                cb='Created by: Frank',
                description=u'https://github.com/knarfeh/SinaBlog2e-book'))
        else:
            self.detail_box.setVisible(False)
        return self.recipes.model().data(index, QtCore.Qt.UserRole)

    def initialize_detail_box(self, ):
        # self.previous_urn = urn
        self.detail_box.setVisible(True)
        self.download_button.setVisible(True)
        self.detail_box.setCurrentIndex(0)

    def login_button_clicked(self):
        account = str(self.username.text())
        password = str(self.password.text())
        captcha = str(self.captcha.text())

        if not self.login.login(
                account=account, password=password, captcha=captcha):
            click_ok = QtGui.QMessageBox.information(
                self, u"登陆失败", u"啊哦,登录失败,可能需要输入验证码\n请尝试输入验证码")
            if click_ok:
                self.login.get_captcha(from_ui=True)
                return
        Config.remember_account_set = True
        Config._save()
        QtGui.QMessageBox.information(self, u"登陆成功", u"恭喜, 登陆成功, 登陆信息已经保存")
        self.username.setText('')
        self.password.setText('')
        self.captcha.setText('')

    def download_button_clicked(self):
        tags = str(self.custom_tags.text())

        # url_id = self.recipes.model.data(1, QtCore.Qt.UserRole)    # TODO: 获得选中的recipes
        url_id = str(self.row_clicked(self.recipes.currentIndex()))

        if url_id == 'None':
            QtGui.QMessageBox.information(self, u"Error", u"选择需要爬取的网站!")
            return

        readlist_content = self.plainTextEdit.toPlainText()

        if readlist_content == '':
            QtGui.QMessageBox.information(self, u"Error", u"请在文本框中输入网址")
            return

        read_list_path = Path.read_list_path

        readList_file = open(read_list_path, 'w')
        readList_file.write(readlist_content)

        readList_file.close()

        game = EEBook(recipe_kind=url_id)

        progress_dlg = QProgressDialog(self)  # TODO: 设置大小, 区域
        progress_dlg.setWindowModality(Qt.WindowModal)
        progress_dlg.setMinimumDuration(5)
        progress_dlg.setWindowTitle(u"请等待")
        progress_dlg.setLabelText(u"制作中...请稍候")
        progress_dlg.setCancelButtonText(u"取消")
        progress_dlg.resize(350, 250)
        progress_dlg.show()
        progress_dlg.setRange(0, 20)

        for i in range(0, 15):
            progress_dlg.setValue(i)
            QThread.msleep(100)

        for i in range(15, 20):
            progress_dlg.setValue(i)
            QThread.msleep(100)
            if progress_dlg.wasCanceled():
                QtGui.QMessageBox.information(self, u"Error",
                                              u"电子书制作失败, 请重新操作")
                return

            try:
                filename = game.begin()  # TODO: 一次只能生成一本书
            except TypeError:
                QtGui.QMessageBox.information(self, u"Error", u"第一次使用请登录")
                progress_dlg.close()
                return
            progress_dlg.close()

            info_filename = ','.join(filename)
            QtGui.QMessageBox.information(
                self, u"info", u"电子书" + str(info_filename) + u"制作成功")

            for item in filename:
                file_path = EPUBSTOR_DIR + '/' + item
                Path.copy(str(file_path + '.epub'), LIBRARY_DIR)
                file_name = os.path.basename(str(file_path))
                book_id = file_name.split('.epub')[0]

                Path.mkdir(LIBRARY_DIR + book_id)
                shutil.move(LIBRARY_DIR + book_id + '.epub',
                            LIBRARY_DIR + book_id)

                book = Book(str(book_id))
                book.date = time.strftime(ISOTIMEFORMAT, time.localtime())
                book.tags += tags.replace(' ', '')
                book.tags += ',' + str(self.now_url)
                if self.add_title_tag.isChecked():
                    book.tags += ',' + str(book.title)
                insert_library(book)
            return
Esempio n. 16
0
 def test_login_fails_with_missing_mobile(self):
     form = {
         'email': '*****@*****.**',
         'name': '9876543210',
     }
     self.assertEqual(Login().validate(form), False)
Esempio n. 17
0
 def test_login_fails_with_missing_emailId(self):
     form = {'name': 'customer_1', 'mobile': '9876543210'}
     self.assertEqual(Login().validate(form), False)
Esempio n. 18
0
from pygame.locals import *

from support.color import Color
from support.client import Client
from src.login import Login
from src.start import Start
from src.homepage import HomePage

# declaration of screen info
screen_size = (700, 500)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Manager App")

# links of the project that are store in a dict, where the keys are the page name
# and the value is an instance of the class that represent that it
links = {"start": Start(screen, screen_size), "login": Login(screen, screen_size),\
        "homePage":HomePage(screen, screen_size)\
    }

# current_layout = "start"
current_layout = "homePage"
events = None

# clock = pygame.time.Clock()

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            exit()
Esempio n. 19
0
from sys import exit

from logging import getLogger, INFO, basicConfig

logger = getLogger(__name__)
format_ = "[%(asctime)s]:%(filename)s:%(lineno)s:%(message)s"
basicConfig(format=format_, level=INFO, filename="c4N4Re.log", filemode='w')

if __name__ == "__main__":
    config = ConfigParser()
    config.read("config.ini")

    if (not config.has_section("login")
            or not config.has_option("login", "email")
            or not config.has_option("login", "app_pass")):
        login = Login(config=config)
        try:
            login.env_login()
        except:
            logger.critical(
                "Unable to retrieve email or app password values from config file."
            )

    try:
        watcher = Watcher(config=config)
        watcher.watch()
    except KeyboardInterrupt:
        logger.info("Captured KeyboardInterrupt exception. Exiting program")
        exit(1)
    except Exception as e:
        logger.critical(f"Exception -> {e}")
Esempio n. 20
0
 def switchScene(self):
     
     preData = self.window.scene.data
     
     if(self.window.scene.NAME == 'LAUNCHER'):
         
         if(self.window.scene.MODE == 'MENU'):
             w, h = getResol('./cnf/config.ini')
             self.window.scene = None
             self.changeResolution(w, h)
             self.window.setScene(Menu(preData))
     else:
             
         if(self.window.scene.MODE == 'AJUSTES'):
             self.window.setScene(Ajustes(preData))
             
         if(self.window.scene.MODE == 'PRINCIPAL'):
             self.window.setScene(Principal(preData))
             
         if(self.window.scene.MODE == 'AYUDA'):
             self.window.setScene(Ayuda(preData))
             
         if(self.window.scene.MODE == 'MENU'):
             self.window.setScene(Menu(preData))
             
         if(self.window.scene.MODE == 'REGISTRO'):
             preData['dbcon'] = self.db
             self.window.setScene(Registro(preData))
             
         if(self.window.scene.MODE == 'LOGIN'):
             preData['dbcon'] = self.db
             self.window.setScene(Login(preData))
         
         if(self.window.scene.MODE == 'NIVELES'):
             preData['dbcon'] = self.db
             self.window.setScene(Niveles(preData))
             
         if(self.window.scene.MODE == 'NIVEL1'):
             self.window.setScene(Nivel1(preData))
             
         if(self.window.scene.MODE == 'EJERCICIO2_N1'):
             self.window.setScene(Ejercicio2_n1(preData))
             
         if(self.window.scene.MODE == 'EJERCICIO3_N1'):
             self.window.setScene(Ejercicio3_n1(preData))
             
         if(self.window.scene.MODE == 'EJERCICIO1_N2'):
             self.window.setScene(Ejercicio1_n2(preData))
             
         if(self.window.scene.MODE == 'EJERCICIO2_N2'):
             self.window.setScene(Ejercicio2_n2(preData))
 
         if(self.window.scene.MODE == 'EJERCICIO3_N2'):
             self.window.setScene(Ejercicio3_n2(preData))
         
         if(self.window.scene.MODE == 'EJERCICIO1_N3'):
             self.window.setScene(Ejercicio1_n3(preData))    
             
         if(self.window.scene.MODE == 'EJERCICIO2_N3'):
             self.window.setScene(Ejercicio2_n3(preData))   
             
         if(self.window.scene.MODE == 'EJERCICIO3_N3'):
             self.window.setScene(Ejercicio3_n3(preData))   
Esempio n. 21
0
def login_obj(chr_driver):
    return Login(driver=chr_driver)