Beispiel #1
0
    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = u"../test/testwiki"
        removeWiki(self.path)

        self.rootwiki = WikiDocument.create(self.path)

        WikiPageFactory.create(self.rootwiki, u"Страница 2", [])

        self.testPage = self.rootwiki[u"Страница 2"]
        self.testPage.content = self.content

        files = [
            u"accept.png", u"add.png", u"anchor.png", u"filename.tmp",
            u"файл с пробелами.tmp", u"картинка с пробелами.png", "image.jpg",
            "image.jpeg", "image.png", "image.tif", "image.tiff", "image.gif",
            "first.jpg", "first_rotate.jpg"
        ]

        fullFilesPath = [
            os.path.join(self.filesPath, fname) for fname in files
        ]

        # Прикрепим к двум страницам файлы
        Attachment(self.testPage).attach(fullFilesPath)
Beispiel #2
0
    def testRemoveAttaches2(self):
        attach = Attachment(self.page)
        attach2 = Attachment(self.page)

        attach.attach(self.fullFilesPath)

        attach.removeAttach([self.files[0]])

        self.assertEqual(len(attach2.attachmentFull),
                         len(self.fullFilesPath[1:]))

        attachBasenames = [os.path.basename(path)
                           for path in attach2.attachmentFull]

        for path in self.fullFilesPath[1:]:
            self.assertTrue(os.path.basename(path) in attachBasenames, path)
Beispiel #3
0
    def testAttachPath2(self):
        attach = Attachment(self.page)

        # Получить путь до прикрепленных файлов, не создавая ее
        path = attach.getAttachPath()
        # Вложенных файлов еще нет, поэтому нет и папки
        self.assertFalse(os.path.exists(path))
    def testCacheSubdir(self):
        attach = Attachment(self.testPage)

        # Только создали страницу, кешировать нельзя
        cache = HtmlCache(self.testPage, self.application)
        self.assertFalse(cache.canReadFromCache())

        cache.saveHash()

        # После того, как один раз сгенерили страницу, если ничего не
        # изменилось, можно кешировать
        self.assertTrue(cache.canReadFromCache())

        # Добавим файл в dir
        with open(os.path.join(attach.getAttachPath(), "dir", "temp.tmp"),
                  "w") as fp:
            fp.write("bla-bla-bla")

        self.assertFalse(cache.canReadFromCache())

        cache.saveHash()

        # Добавим еще одну вложенную директорию
        subdir = os.path.join(attach.getAttachPath(), "dir", "subdir_2")
        os.mkdir(subdir)
        self.assertFalse(cache.canReadFromCache())

        cache.saveHash()

        # Добавим файл в dir/subdir_2
        with open(os.path.join(subdir, "temp2.tmp"), "w") as fp:
            fp.write("bla-bla-bla")

        self.assertFalse(cache.canReadFromCache())
    def testCache1(self):
        # Только создали страницу, кешировать нельзя
        cache = HtmlCache(self.testPage, self.application)
        self.assertFalse(cache.canReadFromCache())

        # После того, как один раз сгенерили страницу, если ничего не
        # изменилось, можно кешировать
        cache.saveHash()
        self.assertTrue(cache.canReadFromCache())

        self.testPage.content = "бла-бла-бла"

        # Изменили содержимое страницы, опять нельзя кешировать
        self.assertFalse(cache.canReadFromCache())

        cache.saveHash()

        self.assertTrue(cache.canReadFromCache())

        # Добавим файл
        attach = Attachment(self.testPage)
        attach.attach([os.path.join(self.filesPath, "add.png")])

        self.assertFalse(cache.canReadFromCache())
        cache.saveHash()

        self.assertTrue(cache.canReadFromCache())
Beispiel #6
0
    def testParseSortDescendDate(self):
        files = [
            "add.png", "Anchor.png", "image2.png", "image.png", "add.png2",
            "файл с пробелами.tmp", "filename"
        ]

        fullFilesPath = [
            os.path.join("testdata/samplefiles/for_sort", fname)
            for fname in files
        ]

        attach = Attachment(self.testPage)
        attach.attach(fullFilesPath)

        os.utime(attach.getFullPath(files[3]), (1000000000, 1000000000))
        os.utime(attach.getFullPath(files[0]), (1000000000, 1100000000))
        os.utime(attach.getFullPath(files[2]), (1000000000, 1200000000))
        os.utime(attach.getFullPath(files[6]), (1000000000, 1300000000))
        os.utime(attach.getFullPath(files[4]), (1000000000, 1400000000))
        os.utime(attach.getFullPath(files[5]), (1000000000, 1500000000))
        os.utime(attach.getFullPath(files[1]), (1000000000, 1600000000))

        text = "(:attachlist sort=descenddate:)"
        result = self.parser.toHtml(text)

        names = [
            files[1], files[5], files[4], files[6], files[2], files[0],
            files[3]
        ]
        titles = names[:]

        self._compareResult(titles, names, result)
Beispiel #7
0
    def test_thumbnail_before(self):
        Attachment(self.testPage).attach(['testdata/images/icon.png'])

        text = "текст %thumb width=32%Attach:icon.png%% %class-red%бла-бла-бла%% текст"
        result = 'текст <a href="__attach/icon.png"><img src="__attach/__thumb/th_width_32_icon.png"/></a> <span class="class-red">бла-бла-бла</span> текст'

        self.assertEqual(result, self.parser.toHtml(text))
Beispiel #8
0
    def testEmpty(self):
        text = '(:plot:)'

        self.page.content = text

        generator = HtmlGenerator(self.page)
        result = generator.makeHtml(Style().getPageStyle(self.page))

        attachpath = Attachment(self.page).getAttachPath()

        self.assertIn(
            '<div id="graph-0" style="width:700px; height:300px;"></div>',
            result)
        self.assertIn('excanvas.min.js">', result)
        self.assertIn('jquery.min.js">', result)
        self.assertIn('highcharts.js">', result)
        self.assertIn("$('#graph-0').highcharts({", result)

        self.assertTrue(
            os.path.exists(
                os.path.join(attachpath, '__thumb', '__js',
                             'excanvas.min.js')))

        self.assertTrue(
            os.path.exists(
                os.path.join(attachpath, '__thumb', '__js', 'jquery.min.js')))

        self.assertTrue(
            os.path.exists(
                os.path.join(attachpath, '__thumb', '__js', 'highcharts.js')))
Beispiel #9
0
    def updateAttachments(self):
        """
        Обновить список прикрепленных файлов
        """
        self.__attachList.Freeze()
        self.__attachList.ClearAll()
        if self._application.selectedPage is not None:
            files = Attachment(self._application.selectedPage).attachmentFull
            files = self.__sortFilesList(files)

            for fname in files:
                if (not os.path.basename(fname).startswith("__")
                        or not os.path.isdir(fname)):
                    # Отключим уведомления об ошибках во всплывающих окнах
                    # иначе они появляются при попытке прочитать
                    # испорченные иконки
                    # На результат работы это не сказывается,
                    # все-равно бракованные иконки отлавливаются.
                    wx.Log.EnableLogging(False)

                    imageIndex = self.__fileIcons.getFileImage(fname)

                    # Вернем всплывающие окна с ошибками
                    wx.Log.EnableLogging(True)

                    self.__attachList.InsertItem(0, os.path.basename(fname),
                                                 imageIndex)

        self.__attachList.Thaw()
Beispiel #10
0
    def testAttachListComments2(self):
        text = u"""Бла-бла-бла
        (:thumblist:)
            Attach:first.jpg    | Первый
            Attach:particle_01.PNG|Комментарий к картинке
        (:thumblistend:)
        бла-бла-бла"""

        files = [
            u"first.jpg", u"image_01.JPG", u"particle_01.PNG", u"image.png",
            u"html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue(u'<A HREF="__attach/first.jpg">' in result)
        self.assertTrue(u"__thumb" in result)

        self.assertTrue(u'<A HREF="__attach/particle_01.PNG">' in result)
        self.assertFalse(u'<A HREF="__attach/image_01.JPG">' in result)

        self.assertFalse(u"html.txt" in result)
        self.assertTrue(u"<table" not in result)
Beispiel #11
0
    def testTable2(self):
        text = u"""Бла-бла-бла
        (:thumblist cols=1:)
        бла-бла-бла"""

        files = [
            u"first.jpg", u"image_01.JPG", u"particle_01.PNG", u"image.png",
            u"html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue(u'<A HREF="__attach/first.jpg">' in result)
        self.assertTrue(u"__thumb" in result)

        self.assertTrue(u'<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue(u'<A HREF="__attach/image_01.JPG">' in result)

        self.assertFalse(u"html.txt" in result)

        self.assertTrue(u"<table" in result)

        # В таблице две строки
        self.assertEqual(len(result.split("<tr")), 4 + 1)
Beispiel #12
0
    def testAttachListSize2(self):
        text = u"""Бла-бла-бла
        (:thumblist px=100:)

            Attach:first.jpg


            Attach:particle_01.PNG


        (:thumblistend:)
        бла-бла-бла"""

        files = [
            u"first.jpg", u"image_01.JPG", u"particle_01.PNG", u"image.png",
            u"html.txt"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue(u'<A HREF="__attach/first.jpg">' in result)
        self.assertTrue(u"maxsize_100_first.jpg" in result)
        self.assertTrue(u"__thumb" in result)

        self.assertTrue(u'<A HREF="__attach/particle_01.PNG">' in result)
        self.assertTrue("maxsize_100_particle_01.PNG" in result)

        self.assertFalse(u'<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse(u"maxsize_100_image_01.JPG" in result)

        self.assertFalse(u"html.txt" in result)
        self.assertTrue(u"<table" not in result)
Beispiel #13
0
    def testAttachGallerySpaces2(self):
        text = u"""Бла-бла-бла
        (:thumbgallery:)

            Attach:first.jpg


            картинка с пробелами.png


        (:thumbgalleryend:)
        бла-бла-бла"""

        files = [
            u"first.jpg", u"image_01.JPG", u"particle_01.PNG", u"image.png",
            u"html.txt", u"картинка с пробелами.png"
        ]
        fullpath = [os.path.join(self.filesPath, fname) for fname in files]
        Attachment(self.testPage).attach(fullpath)

        result = self.parser.toHtml(text)

        self.assertTrue(u'<A HREF="__attach/first.jpg">' in result)
        self.assertTrue(u"_first.jpg" in result)
        self.assertTrue(u"__thumb" in result)

        self.assertTrue(u"картинка с пробелами.png" in result)
        self.assertTrue(u"_картинка с пробелами.png" in result)

        self.assertFalse(u'<A HREF="__attach/image_01.JPG">' in result)
        self.assertFalse(u"_image_01.JPG" in result)

        self.assertFalse(u"html.txt" in result)
        self.assertTrue(u"<table" not in result)
Beispiel #14
0
    def testCacheSubdir(self):
        attach = Attachment(self.testPage)
        hashCalculator = WikiHashCalculator(Application)
        hash_src = hashCalculator.getHash(self.testPage)

        # Добавим файл в dir
        with open(os.path.join(attach.getAttachPath(), "dir", "temp.tmp"),
                  "w") as fp:
            fp.write("bla-bla-bla")

        hash2 = hashCalculator.getHash(self.testPage)
        self.assertNotEqual(hash_src, hash2)

        # Добавим еще одну вложенную директорию
        subdir = os.path.join(attach.getAttachPath(), "dir", "subdir_2")
        os.mkdir(subdir)

        hash3 = hashCalculator.getHash(self.testPage)
        self.assertNotEqual(hash2, hash3)
        self.assertNotEqual(hash_src, hash3)

        # Добавим файл в dir/subdir_2
        with open(os.path.join(subdir, "temp2.tmp"), "w") as fp:
            fp.write("bla-bla-bla")

        hash4 = hashCalculator.getHash(self.testPage)
        self.assertNotEqual(hash3, hash4)
        self.assertNotEqual(hash2, hash4)
        self.assertNotEqual(hash_src, hash4)
Beispiel #15
0
    def testHeads_01 (self):
        text = u'''(:htmlhead:)
excanvas.min.js
(:htmlheadend:)
(:plot:)'''

        self.page.content = text

        generator = HtmlGenerator (self.page)
        result = generator.makeHtml (Style().getPageStyle (self.page))

        attachpath = Attachment (self.page).getAttachPath ()

        self.assertIn (u'<div id="graph-0" style="width:700px; height:300px;"></div>', result)

        self.assertNotIn (u'excanvas.min.js">', result)
        self.assertIn (u'jquery.min.js">', result)
        self.assertIn (u'highcharts.js">', result)

        self.assertIn (u"$('#graph-0').highcharts({", result)

        self.assertFalse (os.path.exists (os.path.join (attachpath,
                                                        u'__thumb',
                                                        u'__js',
                                                        u'excanvas.min.js')))

        self.assertTrue (os.path.exists (os.path.join (attachpath,
                                                       u'__thumb',
                                                       u'__js',
                                                       u'jquery.min.js')))

        self.assertTrue (os.path.exists (os.path.join (attachpath,
                                                       u'__thumb',
                                                       u'__js',
                                                       u'highcharts.js')))
Beispiel #16
0
    def __getDirContent(self, page, filescontent, dirname="."):
        """
        Сформировать строку для расчета хеша по данным вложенной поддиректории dirname (путь относительно __attach)
        page - страница, для которой собираем список вложений
        filescontent - список, содержащий строки, описывающие вложенные файлы
        """
        attach = Attachment(page)
        attachroot = attach.getAttachPath()

        attachlist = attach.getAttachRelative(dirname)
        attachlist.sort(key=str.lower)

        for fname in attachlist:
            fullpath = os.path.join(attachroot, dirname, fname)

            # Пропустим директории, которые начинаются с __
            if not os.path.isdir(fname) or not fname.startswith("__"):
                try:
                    filescontent.write(fname)
                    filescontent.write(str(os.stat(fullpath).st_mtime))

                    if os.path.isdir(fullpath):
                        self.__getDirContent(page, filescontent,
                                             os.path.join(dirname, fname))
                except OSError:
                    # Если есть проблемы с доступом к файлу, то здесь на это не
                    # будем обращать внимания
                    pass
Beispiel #17
0
    def __createThumb (self, page, fname, size, file_prefix, func):
        """
        Создание превьюшки на все случаи жизни :)
        page - страница, внутри которой создается превьюшка
        fname - имя исходной картинки (без полного пути). Полный путь определяется по пути до страницы
        size - размер превьюшки
        file_prefix - дополнение к имени файла
        func - указатель на функцию, которая будет создавать превьюшку (из self.thumbmaker)
        """
        thumb = Thumbnails (page)
        path_thumbdir = thumb.getThumbPath (True)

        path_src = os.path.join (Attachment (page).getAttachPath(), fname)

        # Имя файла для превьюшки
        fname_res = self.thumbsTemplate % (file_prefix, size, fname)

        # wx не умеет сохранять в GIF, поэтому преобразуем в PNG
        if fname_res.lower().endswith (".gif"):
            fname_res = fname_res.replace (".gif", ".png")

        path_res = os.path.join (path_thumbdir, fname_res)

        # Путь, относительный к корню страницы
        relative_path = os.path.join (Thumbnails.getRelativeThumbDir(), fname_res)

        if os.path.exists (path_res):
            return relative_path

        # Возможно исключение ThumbException
        func (path_src, size, path_res)

        return relative_path
Beispiel #18
0
    def testSelectedAttach_html(self):
        Attachment(self._testpage).attach(self.files)
        parent = LinkDialog(self.mainWindow)
        Tester.dialogTester.appendOk()
        selectedString = '{}/add.png'.format(PAGE_ATTACH_DIR)

        controller = HtmlLinkDialogController(self._testpage, parent,
                                              selectedString)
        controller.showDialog()

        self.assertIn('{}/accept.png'.format(PAGE_ATTACH_DIR),
                      parent.linkText.GetItems())
        self.assertIn('{}/add.png'.format(PAGE_ATTACH_DIR),
                      parent.linkText.GetItems())
        self.assertIn('{}/html.txt'.format(PAGE_ATTACH_DIR),
                      parent.linkText.GetItems())

        self.assertEqual(controller.link, '{}/add.png'.format(PAGE_ATTACH_DIR))
        self.assertEqual(controller.comment,
                         '{}/add.png'.format(PAGE_ATTACH_DIR))
        self.assertEqual(
            controller.linkResult,
            '<a href="{attach}/add.png">{attach}/add.png</a>'.format(
                attach=PAGE_ATTACH_DIR))

        self.assertEqual(parent.linkText.GetValue(),
                         '{}/add.png'.format(PAGE_ATTACH_DIR))
Beispiel #19
0
    def testRemoveError2(self):
        page1 = self.wikiroot["Страница 2"]
        page2 = self.wikiroot["Страница 2/Страница 3"]

        pagepath = page1.path

        attach2 = Attachment(page2)
        attachname = "add.png"
        attach2.attach([os.path.join("testdata/samplefiles", attachname)])

        with open(attach2.getFullPath("111.txt", True), "w"):
            try:
                page1.remove()
            except IOError:
                self.assertTrue(os.path.exists(pagepath))
                self.assertNotEqual(self.wikiroot["Страница 2"], None)
                self.assertTrue(
                    os.path.exists(self.wikiroot["Страница 2"].path))
                self.assertEqual(len(self.wikiroot), 3)
                self.assertNotEqual(self.wikiroot["Страница 2/Страница 3"],
                                    None)
                self.assertNotEqual(
                    self.wikiroot["Страница 2/Страница 3/Страница 4"], None)
            else:
                self.assertEqual(self.wikiroot["Страница 2"], None)
                self.assertFalse(os.path.exists(pagepath))
Beispiel #20
0
    def testAttachPath4(self):
        attach = Attachment(self.page)

        # Получить путь до прикрепленных файлов, создав ее
        path = attach.getAttachPath(create=True)
        # Вложенных файлов еще нет, поэтому нет и папки
        self.assertTrue(os.path.exists(path))
Beispiel #21
0
    def __createWiki(self):
        # Здесь будет создаваться вики
        self.path = mkdtemp(prefix='Абырвалг абыр')

        self.wikiroot = WikiDocument.create(self.path)

        factory = WikiPageFactory()
        factory.create(self.wikiroot, "Страница 2", [])
        factory.create(self.wikiroot["Страница 2"], "Страница3", [])
        factory.create(self.wikiroot["Страница 2"], "Страница 4", [])
        self.testPage = self.wikiroot["Страница 2"]

        files = [
            "accept.png", "add.png", "anchor.png", "filename.tmp",
            "файл с пробелами.tmp", "картинка с пробелами.png", "image.jpg",
            "image.jpeg", "image.png", "image.tif", "image.tiff", "image.gif",
            "image_01.JPG", "dir", "dir.xxx", "dir.png"
        ]

        fullFilesPath = [
            os.path.join(self.filesPath, fname) for fname in files
        ]

        # Прикрепим к двум страницам файлы
        Attachment(self.testPage).attach(fullFilesPath)
Beispiel #22
0
def attachFiles(parent: wx.Window,
                page: 'outwiker.core.tree.WikiPage',
                files: List[str]):
    """
    Attach files to page. Show overwrite dialog if necessary
    parent - parent for dialog window
    page - page to attach
    files - list of the files to attach
    """
    if page.readonly:
        raise outwiker.core.exceptions.ReadonlyException

    oldAttachesFull = Attachment(page).attachmentFull
    oldAttaches = {os.path.basename(fname).lower(): fname
                   for fname in oldAttachesFull}

    # Список файлов, которые будут добавлены
    newAttaches = []

    with OverwriteDialog(parent) as overwriteDialog:
        for fname_new in files:
            # Overwrite yourself checking
            if fname_new in oldAttachesFull:
                continue

            fname_new_lower = os.path.basename(fname_new).lower()
            if fname_new_lower in oldAttaches.keys():
                text = _("File '{}' exists already").format(os.path.basename(fname_new))
                old_file_stat = os.stat(oldAttaches[fname_new_lower])
                new_file_stat = os.stat(fname_new)
                result = overwriteDialog.ShowDialog(text,
                                                    old_file_stat,
                                                    new_file_stat)

                if result == overwriteDialog.ID_SKIP:
                    continue
                elif result == wx.ID_CANCEL:
                    break

            newAttaches.append(fname_new)

        try:
            Attachment(page).attach(newAttaches)
        except (IOError, shutil.Error) as e:
            text = _('Error copying files\n{0}').format(str(e))
            logger.error(text)
            showError(Application.mainWindow, text)
Beispiel #23
0
    def _getDefaultPage(self):
        assert self._currentpage is not None

        if (len(self._currentpage.content) > 0
                or len(Attachment(self._currentpage).attachmentFull) > 0):
            return self.RESULT_PAGE_INDEX

        return self.CODE_PAGE_INDEX
Beispiel #24
0
 def run (self, params):
     if self._application.selectedPage is not None:
         folder = Attachment (self._application.selectedPage).getAttachPath (create=True)
         try:
             getOS().startFile (folder)
         except OSError:
             text = _(u"Can't open folder '{}'".format (folder))
             MessageBox (text, _(u"Error"), wx.ICON_ERROR | wx.OK)
Beispiel #25
0
 def testEmptyAttaches(self):
     """
     Тест страницы без папки с аттачами
     """
     wiki = WikiDocument.load(self.path)
     page = wiki["Страница без аттачей"]
     self.assertEqual(len(Attachment(page).attachmentFull), 0)
     page.datetime = self.defaultdate
Beispiel #26
0
    def _start_watch(self):
        if self._application.selectedPage is None:
            return

        self._watchedPage = self._application.selectedPage
        attach = Attachment(self._watchedPage)
        self._oldFilesList = attach.getAttachRelative()
        self._timer.Start(self._period)
Beispiel #27
0
    def testSelectedAttach4(self):
        Attachment(self.testPage).attach(self.fullFilesPath)
        controller = ExampleThumbDialogController(None, self.testPage,
                                                  "  Attach:accept.png   ", 0,
                                                  "", ThumbDialog.WIDTH)
        controller.showDialog()

        self.assertEqual(controller.dlg.selectedFile, "accept.png")
Beispiel #28
0
    def testGetAttachRelative4 (self):
        attach = Attachment (self.page)
        attach.attach (self.fullFilesPath)

        attach_right = set ([u"attach.png", u"dir.xxx", u"subdir"])

        attach_names = set (attach.getAttachRelative(u"dir"))
        self.assertEqual (attach_right, attach_names)
Beispiel #29
0
    def testGetAttachRelative3 (self):
        attach = Attachment (self.page)
        attach.attach (self.fullFilesPath)

        attach_right = set (self.files)

        attach_names = set (attach.getAttachRelative())
        self.assertEqual (attach_right, attach_names)
Beispiel #30
0
    def testRemoveAttachDir1 (self):
        attach = Attachment (self.page)

        attach.attach (self.fullFilesPath)

        attach.removeAttach ([u"dir"])

        self.assertEqual (len (attach.attachmentFull), len (self.fullFilesPath[1:]))