Exemplo n.º 1
0
def main():
    root_dir = 'E:\Test'
    meta_file_path = 'E:\Dev\Python\BitTorrent4\metainfo.libr'
    meta_file = utils.Metainfo(meta_file_path)
    player_id = b'-RO0101-7ec7150dddf3'

    book_list = []
    if player_id is None :
        print('Create player id')
        player_id = utils.generate_player_id()
    print(meta_file.get_file_name())

    print(player_id.decode("utf-8"))
    if os.path.exists(root_dir):
        player_dir = root_dir + '\\' + player_id.decode("utf-8")
        if not os.path.exists(player_dir):
            os.mkdir(player_dir)
        list_file = os.listdir(player_dir)

        if len(list_file) > 0 :
            for file in list_file:
                book_list.append(Books(player_dir+'\\'+file, meta_file))
        else:
            print('Create new stuff')
            book_list.append(Books(player_dir+'\\'+meta_file.get_file_name(), meta_file))


    #test = TestPlayerServer(player_id, meta_file, book_list[0])
    test2= TestPlayerClient(player_id, meta_file, book_list[0])
Exemplo n.º 2
0
def new_book(branch, copies, name, author, publisher, language, edition):
    for i in range(int(copies)):
        isbn = Books.newisbn(name, author, publisher, language, edition)
        copy_no = (Books.newcopy(isbn)) + 1

        with CursorFromConnectionFromPool() as cursor:
            cursor.execute(
                "insert into public.books(isbn,copy_no,name,author,language,publisher,branch_id,edition,issued_by) values(%s,%s,%s,%s,%s,%s,%s,%s,0);",
                (isbn, copy_no, name, author, language, publisher, branch, edition))
Exemplo n.º 3
0
def hello_world():
    books = Books()
    sql_data = books.get_book_info_limit()
    resData = {
        "resCode": 0,  # 非0即错误 1
        "data": sql_data,  # 数据位置,一般为数组
        "message": '图书的信息'
    }
    return jsonify(resData)
Exemplo n.º 4
0
def page_info(book_cate):
    if request.method == 'POST':
        get_data = json.loads(request.get_data(as_text=True))
        pageNo = get_data['pageNo']
        pageSize = get_data['pageSize']
        # key = request.form.get('key')
        print('-----pageNo-----{}'.format(pageNo))
        # secretKey = get_data['secretKey']
        # secret_result = get_secret_key(secretKey)
        # if secret_result['request_time'] == '':
        #     # 如果这边返回的是空的,说明请求的数据已经被破坏了
        #     resData = {
        #         "resCode": 1, # 非0即错误 1
        #         "data": [],# 数据位置,一般为数组
        #         "message": '你猜,你使劲猜'
        #     }
        #     return jsonify(resData)
        # if is_allow_domain_time(secret_result['request_time'], secret_result['request_url']):
        #     resData = {
        #         "resCode": 1, # 非0即错误 1
        #         "data": [],# 数据位置,一般为数组
        #         "message": '你猜,你使劲猜'
        #     }
        #     return jsonify(resData)
        # if is_string_validate(key):
        #     resData = {
        #         "resCode": 1, # 非0即错误 1
        #         "data": [],# 数据位置,一般为数组
        #         "message": '参数错误'
        #     }
        #     return jsonify(resData)
        books = Books()
        search_data = books.get_books_page(book_cate, pageNo, pageSize)
        print(search_data)
        if len(search_data) == 0:
            resData = {
                "resCode": 0,  # 非0即错误 1
                "data": [],  # 数据位置,一般为数组
                "message": '数据为空'
            }
            return jsonify(resData)

        resData = {
            "resCode": 0,  # 非0即错误 1
            "data": search_data,  # 数据位置,一般为数组
            "message": '搜索结果'
        }
        return jsonify(resData)
    else:
        resData = {
            "resCode": 1,  # 非0即错误 1
            "data": [],  # 数据位置,一般为数组
            "message": '请求方法错误'
        }
        return jsonify(resData)
Exemplo n.º 5
0
def returnbook():
    if request.method=="POST":
        if "adminsesh" in session:
            isbn=request.form["isbn"]
            email=request.form["email"]
            Books.returnthis(isbn)
            with CursorFromConnectionFromPool() as cursor:
                cursor.execute("UPDATE public.users SET issuedbyisbn=0 WHERE email=%s", (email,))
                cursor.execute("update public.users set returndate=0 where email=%s", (email,))
            flash("book returned")
            return redirect(url_for("adminp"))
    else:
        return render_template("returnbook.html")
Exemplo n.º 6
0
def add_book():
	try:
		new_book = Books(
			title			= request.json["title"],
			description 		= request.json["description"],
			author			= request.json["author"],
			launching		= request.json["launching"]
		)
	
		new_book.save()

		return jsonify({"message": "The book is added"})
	except Exception as e:
		return abort(400, e)
Exemplo n.º 7
0
 def setUp(self):
     """Setup."""
     books = Books()
     self.anchors = {}
     for book in books.books:
         for md_path in book.md_paths:
             anchors = []
             with open(md_path) as f:
                 for line in f:
                     if '<a' in line and 'name=' in line:
                         for m in re.finditer(
                                 r'<a[^>]*name\s*=\s*"(.*)"[^>]*>',
                                 line.strip()):
                             anchors.append(m.group(1))
                     if line.startswith('#'):
                         m = re.match(r'^#{1,4} .*$', line)
                         if m:
                             title = re.sub(r'^#*', '', line)
                             anchors.append(slugify(title))
                     elif line.startswith('%figure'):
                         title = slugify(line.replace('%figure', ''))
                         if title:
                             anchors.append(slugify(title))
                     elif line.startswith('%api'):
                         title = line.replace('%api', '')
                         anchors.append(slugify(title))
                     elif "**wb" in line:
                         for m in re.finditer(r'\*\*(wb[^\*]*)\*\*', line):
                             anchor = m.group(1).replace('\\_', '_')
                             anchors.append(anchor)
             self.anchors[md_path] = anchors
 def add_item_from_json(self, item):
     """ Import an item to the catalog manager from a json formatted object """
     if item["type_"] == "multimedia":
         entity = Multimedia(
             isbn=item["isbn"],
             author=item["author"],
             publisher=item["publisher"],
             title=item["title"],
             genre=item["genre"],
             pub_date=datetime.strptime(item["pub_date"].strip(),
                                        "%Y-%m-%d"),
             is_borrowed=item["is_borrowed"],
             borrow_date=datetime.strptime(item["borrow_date"].strip(),
                                           "%Y-%m-%d"),
             length=(datetime.strptime(item["length"].strip(),
                                       "%H:%M:%S").time()),
             sub_type=item["sub_type"],
             type_=item["type_"])
         self.add_item(entity)
     elif item["type_"] == "books":
         entity = Books(isbn=item["isbn"],
                        author=item["author"],
                        publisher=item["publisher"],
                        title=item["title"],
                        genre=item["genre"],
                        pub_date=datetime.strptime(item["pub_date"].strip(),
                                                   "%Y-%m-%d"),
                        is_borrowed=item["is_borrowed"],
                        borrow_date=item["borrow_date"],
                        length=(item["length"]),
                        sub_type=item["sub_type"],
                        type_=item["type_"])
         self.add_item(entity)
Exemplo n.º 9
0
    def setUp(self):
        """Setup: get all the hyperlinks."""
        self.hyperlinks = []

        books = Books()
        for book in books.books:
            for md_path in book.md_paths:
                # Extract MD content.
                with open(md_path) as f:
                    content = f.read()
                # Remove code statements
                content = re.sub(r'```.+?(?=```)```', '', content, flags=re.S)
                content = re.sub(r'`.+?(?=`)`', '', content, flags=re.S)
                # Remove charts
                content = re.sub(r'%chart.+?(?=%end)%end',
                                 '\n',
                                 content,
                                 flags=re.S)
                # Extract hyperlinks.
                for m in re.finditer(r'[^\!](\[([^\]]*)\]\s*\(([^\)]*)\))',
                                     content):
                    hyperlinkMD = m.group(1)
                    hyperlinkName = m.group(2)
                    hyperlinkUrl = m.group(3)
                    self.hyperlinks.append({
                        'md': hyperlinkMD,
                        'name': hyperlinkName,
                        'url': hyperlinkUrl,
                        'file': md_path
                    })
Exemplo n.º 10
0
    def test_all_images_are_used(self):
        """Test that all the image files are referenced somewhere."""
        books = Books()
        for book in books.books:
            # search for all images
            images_paths = []  # ['image/sonar.png', 'image/sphere.png', ...]
            for root, dirnames, filenames in os.walk(book.path):
                if 'scenes' in root.replace(books.project_path, ''):
                    continue
                for filename in fnmatch.filter(filenames, '*.png'):
                    image_path = os.path.join(root, filename)
                    image_path = image_path[(len(book.path) + 1):]
                    images_paths.append(image_path)
            self.assertGreater(len(images_paths),
                               0,
                               msg='No image found in book "%s"' % (book.name))

            # check the image reference can be found in at least one MD file
            for image_path in images_paths:
                found = False
                for md_path in book.md_paths:
                    if image_path in open(md_path).read():
                        found = True
                        break
                self.assertTrue(
                    found,
                    msg='Image "%s" not referenced in any MD file.' %
                    (image_path))
Exemplo n.º 11
0
    def setUp(self):
        """Setup: get all the hyperlinks."""
        self.hyperlinks = []

        books = Books()
        for book in books.books:

            # we don't want to maintain links posted on Discord
            if book.name == 'discord':
                continue

            for md_path in book.md_paths:
                # Extract MD content.
                args = {} if sys.version_info[0] < 3 else {'encoding': 'utf-8'}
                with open(md_path, **args) as f:
                    content = f.read()
                # Remove code statements
                content = re.sub(r'```.+?(?=```)```', '', content, flags=re.S)
                content = re.sub(r'`.+?(?=`)`', '', content, flags=re.S)
                # Remove charts
                content = re.sub(r'%chart.+?(?=%end)%end', '\n', content, flags=re.S)
                # Extract hyperlinks.
                for m in re.finditer(r'[^\!](\[([^\]]*)\]\s*\(([^\)]*)\))', content):
                    hyperlinkMD = m.group(1)
                    hyperlinkName = m.group(2)
                    hyperlinkUrl = m.group(3)
                    self.hyperlinks.append({
                        'md': hyperlinkMD,
                        'name': hyperlinkName,
                        'url': hyperlinkUrl,
                        'file': md_path
                    })
Exemplo n.º 12
0
    def setUp(self):
        """Setup: get all the titles."""
        self.titles = []
        books = Books()
        for book in books.books:

            # we are not responsible of the content of the discord chats
            if book.name == 'discord':
                continue

            for md_path in book.md_paths:
                # Extract MD content.
                args = {} if sys.version_info[0] < 3 else {'encoding': 'utf-8'}
                with open(md_path, **args) as f:
                    content = f.read()

                # Remove annoying string sequences.
                # - Multiline code sections.
                content = re.sub(r'```.+?(?=```)```', '', content, flags=re.S)
                # Extract titles.
                for match in re.finditer(r'^#+ .*',
                                         content):  # Title on the first line.
                    title = content[match.start():match.end()]
                    self.titles.append({'title': title, 'md': md_path})
                for match in re.finditer(r'\n#+ .*', content):
                    title = content[match.start() +
                                    1:match.end()]  # Title(s) on other lines.
                    self.titles.append({'title': title, 'md': md_path})
 def __init__(
     self,
     lib_name: str,
 ):
     """Initializes constructor"""
     if self._valid_string(lib_name, "library_name"):
         self._lib_name = lib_name.strip()
     self._catalog = list(Books.select()) + list(Multimedia.select())
Exemplo n.º 14
0
 def test_md_filenames_dont_contain_prohibited_keywords(self):
     """Test that the MD filenames don't contain prohibited keywords."""
     books = Books()
     for book in books.books:
         # 'advertising' causes issues with ad blocking software.
         self.assertFalse('advertising' in book.md_paths,
                          msg='MD file "%s" contains "advertising"' %
                          (book.md_paths))
Exemplo n.º 15
0
    def setUp(self):
        """Setup: get all the paragraphs."""
        self.paragraphs = []
        books = Books()
        for book in books.books:

            # we are not responsible of the content of the discord chats
            if book.name == 'discord':
                continue

            for md_path in book.md_paths:
                # Extract MD content.
                args = {} if sys.version_info[0] < 3 else {'encoding': 'utf-8'}
                with open(md_path, **args) as f:
                    content = f.read()

                # Remove annoying string sequences.
                # - Multiline code sections.
                content = re.sub(r'```.+?(?=```)```', '\n', content, flags=re.S)
                content = re.sub(r'\n`.+?(?=`\n)`\n', '\n', content, flags=re.S)
                # - Notes.
                content = re.sub(r'\n\s*>.+?(?=\n\n)', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*>.+?(?=\n$)', '\n', content, flags=re.S)
                # - Showdown extensions.
                content = re.sub(r'%chart.+?(?=%end)%end', '\n', content, flags=re.S)
                content = re.sub(r'%figure.+?(?=%end)%end', '\n', content, flags=re.S)
                content = re.sub(r'%api.+?(?=%end)%end', '\n', content, flags=re.S)
                content = re.sub(r'%spoiler.+?(?=%end)%end', '\n', content, flags=re.S)
                content = re.sub(r'%tab-component.+?(?=%end)%end', '\n', content, flags=re.S)
                content = re.sub(r'%robot.*\n', '\n', content, flags=re.S)
                # - Headers.
                content = re.sub(r'^#.*', '\n', content)
                content = re.sub(r'\n#.*', '\n', content)
                # - Items.
                content = re.sub(r'\n\s*-.+?(?=\n\n)', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*-.+?(?=\n$)', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*\d+\..+?(?=\n\n)', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*\d+\..+?(?=\n$)', '\n', content, flags=re.S)
                content = re.sub(r'\n    .+?(?=\n)', '\n', content, flags=re.S)
                content = re.sub(r'\n        .+?(?=\n)', '\n', content, flags=re.S)
                # - HTML statements
                content = re.sub(r'\n<.+?>\n', '\n', content, flags=re.S)
                content = re.sub(r'\n---\n', '\n', content, flags=re.S)
                # - Single hyperlinks
                content = re.sub(r'\n\!?\[.+\)\n', '\n', content, flags=re.S)
                # - Special statements
                content = re.sub(r'\nRelease {{.+?}}\n', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*\*\*.+?\n', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*\*.+?\*\n', '\n', content, flags=re.S)
                content = re.sub(r'\n\s*\{.+?\n', '\n', content, flags=re.S)

                # Extract paragraphs.
                for match in re.finditer(r'(?s)((?:[^\n][\n]?)+)', content):
                    paragraph = content[match.start():match.end() - 1]
                    # - Arrays.
                    if paragraph.startswith('| ') or paragraph.startswith('> '):
                        continue
                    self.paragraphs.append({'paragraph': paragraph, 'md': md_path})
Exemplo n.º 16
0
    def return_book():
        Books.display_issued_books()
        issue_id = int(input('Enter the issue id of book which you want to return:') )
        issued_ids = Books.get_issued_ids() 

        if issue_id in issued_ids:
            query = 'SELECT issuedBook FROM issued WHERE id = {}'.format(issue_id)
            book_id = DbInterface.execute_query(query)
            book_id = book_id[0][0]

            query = "UPDATE books SET copiesIssued = copiesIssued - 1 WHERE bookId = '{}' ".format(book_id)
            DbInterface.execute_query(query)

            query = "DELETE FROM issued WHERE id = {}".format(issue_id)
            DbInterface.execute_query(query)
            
        else:
            print('Invalid issue id.')
Exemplo n.º 17
0
    def issue_book():
        name = input('Enter your Name:')
        Books.display_available_books()
        try:
            book_id = int(input('Choose the bookId which you want to issue:') )
        except ValueError:
            print('Book Id should be an integer')
            return
        book_ids = Books.get_available_book_ids()

        if book_id in book_ids:
            query = "INSERT INTO issued(name, issuedBook) VALUES('{}',{})".format(name, book_id )
            DbInterface.execute_query(query)

            query = "UPDATE books SET copiesIssued = copiesIssued + 1 WHERE bookId = '{}' ".format(book_id)
            DbInterface.execute_query(query)
        else:
            print('Invalid book Id.')
 def get_item_by_isbn(self, isbn):
     """Returns item in the catalog with matching ISBN"""
     if self._is_valid_isbn(isbn):
         try:
             item = (Books.select().where(Books.isbn == isbn)
                     or Multimedia.select().where(
                         Multimedia.isbn == isbn)).get()
             return item
         except:
             return None
 def get_items_by_type(self, type_):
     """Returns items by type"""
     if self._valid_string(type_, "type"):
         items = []
         if type_ == "books":
             return Books.select()
         elif type_ == "multimedia":
             return Multimedia.select()
         else:
             return items
Exemplo n.º 20
0
def search():
    if request.method == "POST":

        name = request.form["firstname"]
        isbn = request.form["lastname"]
        author = request.form["psw"]
        language = request.form["email"]
        publisher = request.form["pnumber"]
        results = Books.search(name, isbn, author, language, publisher)
        return redirect(url_for("results", result=results))
    else:
        return render_template("search.html")
Exemplo n.º 21
0
 def setUp(self):
     """Creates catalog manager object for testing"""
     test_db.bind([Books, Multimedia])
     test_db.create_tables([Books, Multimedia])
     self.catalog_manager1 = CatalogManager("Catalog1")
     self.valid_multimedia = Multimedia(isbn=1234567891023, author="Eric N", publisher="BE Publishing", title="1000 night at school",
                                        genre="romantic", pub_date=datetime.date(2020, 1, 30), length="01:32:24", sub_type="CD", type_="multimedia")
     self.valid_borrowed_multimedia = Multimedia(isbn=1234567891024, author="Eric K", publisher="KE Publishing", title="BCIT First look",
                                                 genre="informative", pub_date=datetime.date(2018, 2, 13), length="01:32:24", sub_type="Bluray", type_="multimedia")
     self.valid_borrowed_multimedia.borrow(datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d"))
     self.valid_overdue_multimedia = Multimedia(isbn=1234567891025, author="Eric W", publisher="CA Publishing", title="Fairies",
                                                genre="romantic", pub_date=datetime.date(1998, 1, 30), length="01:32:24", sub_type="VHS", type_="multimedia")
     self.valid_overdue_multimedia.borrow("1999-02-03")
     self.valid_Books = Books(isbn=1234567891026, author="Eric N", publisher="BE Publishing", title="1000 night at school",
                              genre="romantic", pub_date=datetime.date(2020, 1, 30), length=324, sub_type="hardcover", type_="books")
     self.valid_borrowed_Books = Books(isbn=1234567891027, author="Eric K", publisher="KE Publishing", title="BCIT First look",
                                       genre="informative", pub_date=datetime.date(2018, 2, 13), length=134, sub_type="softcover", type_="books")
     self.valid_borrowed_Books.borrow(datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d"))
     self.valid_overdue_Books = Books(isbn=1234567891028, author="Eric W", publisher="CA Publishing", title="Fairies",
                                      genre="romantic", pub_date=datetime.date(1998, 1, 30), length=688, sub_type="softcover", type_="books")
     self.valid_overdue_Books.borrow("1999-02-03")
Exemplo n.º 22
0
 def test_md_file_contents_dont_contain_prohibited_keywords(self):
     """Test that the MD file contents don't contain prohibited keywords."""
     books = Books()
     for book in books.books:
         for md_path in book.md_paths:
             with open(md_path) as f:
                 content = f.readlines()
             for line in content:
                 # π crashes QtWebEngine on Windows.
                 self.assertFalse('π' in line,
                                  msg='MD file "%s" contains "π"' %
                                  (md_path))
Exemplo n.º 23
0
def search():
    if request.method == "POST":
        name = request.form["name"]
        isbn = request.form["isbn"]
        author = request.form["author"]
        language = request.form["language"]
        publisher = request.form["publisher"]
        edition = request.form["edition"]

        resultsr = Books.search(name, isbn, author, language, publisher, edition)

        return render_template('search.html', resultsr=resultsr)
    return render_template('search.html')
Exemplo n.º 24
0
 def test_anchors_are_unique(self):
     """Test that the anchors are unique."""
     books = Books()
     for book in books.books:
         for md_path in book.md_paths:
             anchors = self.anchors[md_path]
             s = set()
             for a in anchors:
                 if a in s:
                     self.assertTrue(False,
                                     msg='%s: Anchors "%s" are not unique' %
                                     (md_path, a))
                 s.add(a)
Exemplo n.º 25
0
 def test_md_file_contents_dont_contain_prohibited_keywords(self):
     """Test that the MD file contents don't contain prohibited keywords."""
     books = Books()
     for book in books.books:
         for md_path in book.md_paths:
             args = {} if sys.version_info[0] < 3 else {'encoding': 'utf-8'}
             with open(md_path, **args) as f:
                 content = f.readlines()
             for line in content:
                 # π crashes QtWebEngine on Windows.
                 self.assertFalse(
                     'π' in line,
                     msg='MD file "%s" contains "π"' % (md_path)
                 )
Exemplo n.º 26
0
 def test_images_are_valid(self):
     """Test that the MD files refer to valid URLs."""
     books = Books()
     for book in books.books:
         for md_path in book.md_paths:
             with open(md_path) as f:
                 content = f.read()
             for match in re.finditer(r"!\[(.*?)\]\((.*?)\)", content):
                 # remove parameters
                 is_youtube_video = match.group(1) == "youtube video"
                 if not is_youtube_video:
                     image_ref = match.group(2).split(' ')[0]
                     image_path = os.path.join(book.path, image_ref)
                     self.assertTrue(os.path.isfile(image_path),
                                     msg='%s: "%s" not found' %
                                     (md_path, image_path))
Exemplo n.º 27
0
 def test_md_files_exist(self):
     """Test that the MD files exist."""
     books = Books()
     self.assertGreater(len(books.books), 0, msg='No books found')
     for book in books.books:
         self.assertGreater(len(book.md_paths),
                            0,
                            msg='No MD files found in book "%s"' % book)
         for md_filename in book.md_paths:
             self.assertTrue(os.path.isfile(md_filename),
                             msg='MD file "%s" is not existing' %
                             (md_filename))
             with open(md_filename) as f:
                 content = f.read()
             self.assertGreater(len(content),
                                0,
                                msg='MD file "%s" is empty' % (md_filename))
Exemplo n.º 28
0
    def setUp(self):
        """Setup."""
        books = Books()
        self.anchors = {}
        for book in books.books:

            # we are not responsible of the content of the discord chats
            if book.name == 'discord':
                continue

            for md_path in book.md_paths:
                anchors = []
                args = {} if sys.version_info[0] < 3 else {'encoding': 'utf-8'}
                with open(md_path, **args) as f:
                    skipUntil = ''
                    for line in f:
                        if skipUntil:
                            if skipUntil in line:
                                skipUntil = ''
                            continue
                        if '<a' in line and 'name=' in line:
                            for m in re.finditer(
                                    r'<a[^>]*name\s*=\s*"(.*)"[^>]*>',
                                    line.strip()):
                                anchors.append(m.group(1))
                        if re.match(r'```', line):
                            skipUntil = '```'
                            continue
                        elif line.startswith('#'):
                            m = re.match(r'^#{1,4} .*$', line)
                            if m:
                                title = re.sub(r'^#*', '', line)
                                anchors.append(slugify(title))
                        elif line.startswith('%figure'):
                            title = slugify(line.replace('%figure', ''))
                            if title:
                                anchors.append(slugify(title))
                        elif line.startswith('%api'):
                            title = line.replace('%api', '')
                            anchors.append(slugify(title))
                        elif "**wb" in line:
                            for m in re.finditer(r'\*\*(wb[^\*]*)\*\*', line):
                                anchor = m.group(1).replace('\\_', '_')
                                anchors.append(anchor)
                self.anchors[md_path] = anchors
Exemplo n.º 29
0
 def test_images_are_valid(self):
     """Test that the MD files refer to valid URLs."""
     books = Books()
     for book in books.books:
         for md_path in book.md_paths:
             args = {} if sys.version_info[0] < 3 else {'encoding': 'utf-8'}
             with open(md_path, **args) as f:
                 content = f.read()
             for match in re.finditer(r"!\[(.*?)\]\((.*?)\)", content):
                 # remove parameters
                 is_youtube_video = match.group(1) == "youtube video"
                 image_ref = match.group(2).split(' ')[0]
                 if not is_youtube_video and not image_ref.startswith(
                         'http'):
                     image_path = os.path.join(book.path, image_ref)
                     self.assertTrue(os.path.isfile(image_path),
                                     msg='%s: "%s" not found' %
                                     (md_path, image_path))
Exemplo n.º 30
0
    def test_anchors_are_unique(self):
        """Test that the anchors are unique."""
        books = Books()
        for book in books.books:

            # we are not responsible of the content of the discord chats
            if book.name == 'discord':
                continue

            for md_path in book.md_paths:
                anchors = self.anchors[md_path]
                s = set()
                for a in anchors:
                    if a in s:
                        self.assertTrue(False,
                                        msg='%s: Anchors "%s" are not unique' %
                                        (md_path, a))
                    s.add(a)
Exemplo n.º 31
0
#!/usr/bin/env python
from books import Books
import sqlite3
import sys

conn = sqlite3.connect('../db/books.db')
conn.row_factory = sqlite3.Row
if len(sys.argv) == 1:
    books = Books()
elif len(sys.argv) == 4:
    books = Books(sys.argv[1:4])
else:
    print("ERROR: Either field, operator and value or empty arguments can be specified.")
    conn.close()
    sys.exit(1)

books.delete(conn)
conn.close()
Exemplo n.º 32
0
#!/usr/bin/env python
from books import Books
import sqlite3
import sys

conn = sqlite3.connect('../db/books.db')
conn.row_factory = sqlite3.Row
if len(sys.argv) != 6:
    print("ERROR: Search field, operator, search value, updated field, and new value must be specified.")
    conn.close()
    sys.exit(1)
else:
    books = Books(sys.argv[1:4])

books.update(conn, sys.argv[4], sys.argv[5])
conn.close()
Exemplo n.º 33
0
#!/usr/bin/env python
from books import Books
import sqlite3
import sys

conn = sqlite3.connect('../db/books.db')
conn.row_factory = sqlite3.Row
if len(sys.argv) == 1:
    books = Books()
elif len(sys.argv) == 4:
    books = Books(sys.argv[1:4])
else:
    print("ERROR: Either field, operator and value or empty arguments can be specified.")
    conn.close()
    sys.exit(1)

books.list(conn)
conn.close()
Exemplo n.º 34
0
#enables color coded error messages
import cgitb
cgitb.enable()

from books import Books
from htmltable import HtmlTable
from utils import date2str

# process form inputs
form = cgi.FieldStorage()
term = form.getvalue('term', '')
clear= form.getvalue('clear')
order_by= form.getvalue('order_by', '')

# build report body:
books = Books()
results = books.retrieveCoreData(term, order_by)

# build html table
table = HtmlTable(border=1, cellpadding=3)

# table header
header = ['#',
          '<a href= "main2.py?order_by=title">Title</a>',
          '<a href= "main2.py?order_by=author">Author</a>',
          '<a href= "main2.py?order_by=notes">Notes</a>',
          '<a href= "main2.py?order_by=when_read">Date</a>']
table.addHeader(header)

# table body
i = 0