def handle(self, *args, **options):
        parser = get_parser()

        with transaction.atomic():
            count = 0
            for item in NewsItem.objects.select_for_update():
                item.message.rendered = parser.render(item.message.raw)
                item.save(update_fields=['_message_rendered'])
                count += 1
                if count % 10 == 0:
                    print("NewsItem:  {}".format(count))

        with transaction.atomic():
            count = 0
            for item in ForumUser.objects.select_for_update():
                item.signature.rendered = parser.render(item.signature.raw)
                item.save(update_fields=['_signature_rendered'])
                count += 1
                if count % 100 == 0:
                    print("ForumUser: {}".format(count))

        with transaction.atomic():
            count = 0
            for item in ForumPost.objects.select_for_update():
                item.message.rendered = parser.render(item.message.raw)
                item.save(update_fields=['_message_rendered'])
                count += 1
                if count % 1000 == 0:
                    print("ForumPost: {}".format(count))
Esempio n. 2
0
    def get_chapters_data(self, request, *args, **kwargs):
        """Метод получения данных о разделах указанного плана"""
        context = {}

        # Если создаётся новый план - в его id присутствует "new"
        if kwargs['plan_id'] == 'new':
            chapters = []
        else:
            context = add_plan_data(request,
                                    context={},
                                    plan_id=kwargs['plan_id'])
            chapters = []
            #Преобразовываем данных из bbcode (данные из клиента поступают в формате bbcode)
            parcer = get_parser()
            for chapter in context['chapters']:
                chapters.append({
                    'id': chapter.id,
                    'name': parcer.render(chapter.name),
                    'questions': parcer.render(chapter.questions)
                })

        response = HttpResponse(json.dumps({'chapters': chapters}),
                                content_type='application/json')
        response.status_code = 200
        return response
Esempio n. 3
0
def bb_parse(elements):
    parser = get_parser()
    try:
        iter(elements)
        for element in elements:
            element.body = parser.render(str(element.body))
    except TypeError:
        elements.body = parser.render(str(elements.body))
    return elements
Esempio n. 4
0
def bb_parse(elements):
    """Парсит bbcode в постах или комментариях"""
    parser = get_parser()
    try:
        iter(elements)
        for element in elements:
            element.body = parser.render(str(element.body))
    except TypeError:
        elements.body = parser.render(str(elements.body))
    return elements
 def create_smilies(self):
     self.parser = get_parser()
     self.parser_loader = BBCodeParserLoader(parser=self.parser)
     # Set up an image used for doing smilies tests
     f = open(settings.MEDIA_ROOT + '/icon_e_wink.gif', 'rb')
     image_file = File(f)
     self.image = image_file
     # Set up a smiley tag
     smiley = SmileyTag()
     smiley.code = ':test:'
     smiley.image.save('icon_e_wink.gif', self.image)
     smiley.save()
     self.parser_loader.init_bbcode_smilies()
 def create_smilies(self):
     self.parser = get_parser()
     self.parser_loader = BBCodeParserLoader(parser=self.parser)
     # Set up an image used for doing smilies tests
     f = open(settings.MEDIA_ROOT + '/icon_e_wink.gif', 'rb')
     image_file = File(f)
     self.image = image_file
     # Set up a smiley tag
     smiley = SmileyTag()
     smiley.code = ':test:'
     smiley.image.save('icon_e_wink.gif', self.image)
     smiley.save()
     self.parser_loader.init_bbcode_smilies()
Esempio n. 7
0
def render_username(profile):
    # Returns the username rendered in bbcode defined by the users rank.
    a = BOARD_SETTINGS.USERNAME_MODIFIERS_ENABLED
    parser = get_parser()
    if profile.is_banned:
        return 'BANNED'
    if a and profile.username_modifier:
        modifier = profile.username_modifier
        replace_username = modifier.replace('{USER}', profile.user.username)
        return mark_safe(parser.render(replace_username))
    elif a and profile.rank and profile.rank.username_modifier:
        modifier = profile.rank.username_modifier
        replace_username = modifier.replace('{USER}', profile.user.username)
        return mark_safe(parser.render(replace_username))
    else:
        return profile.user.username
Esempio n. 8
0
class BaseView(View):
    template_name = 'index.pug'
    page_name = 'index'
    path_prefix = '/static/images/upload_imgs/'

    try:
        bb_parser = get_parser()
    except BaseException as e:
        print(e)

    def get_feedback(self):
        # More questions?
        return [f.desc for f in Feedback.objects.all()][0]


    def get(self, request):
        return render(request, self.template_name, {'page': self.page_name})
Esempio n. 9
0
class HallsChange(View):
    darkhall_imgs = []
    lighthall_imgs = []
    list_imgs = []
    halls_list = ['dark', 'light']
    path_prefix = '/static/images/upload_imgs/'
    title = ''
    desc = ''
    hallsize = ''
    price = -1
    pug = ''
    bb_parser = get_parser()

    def get(self, request):
        self.request.session['view'] = self.request.GET['view']

        if self.request.is_ajax:
            for i in self.halls_list:
                if self.request.session['view'] == i:
                    self.list_imgs = [
                        self.path_prefix + h.file.url for h in PicHalls.objects.filter(
                            galleryHalls__service_name=i)
                    ]

                    random.shuffle(self.list_imgs)

                    hall = Hall.objects.get(service_name=i)
                    self.title = hall.title.upper()
                    self.desc = hall.desc
                    self.price = hall.price
                    self.hallsize = hall.hall_size

                pug = loader.render_to_string(
                    'includes/universal_slider_inc.html',
                    {'imgs_list': self.list_imgs})

            return JsonResponse({
                'response': 'ok',
                'html': pug,
                'title': self.title,
                'desc': self.desc,
                'hallsize': self.hallsize,
                'price': self.price
            })

        return HttpResponse('ok', content_type='text/html')
Esempio n. 10
0
def postprocess_bbcode_img(model, object_id, field_name):
    obj = model.objects.select_for_update().get(pk=object_id)
    text = getattr(obj, field_name)
    hits = match_url.findall(text.raw)
    urls = set([h[1] for h in hits])
    if urls:
        # Fetch urls to cache
        refresh = False
        for url in urls:
            if BBCodeImage.objects.filter(source_url=url).exists():
                log.warning("Source url %s is already loaded", url)
                continue
            if cache_bbcode_image(url):
                refresh = True
        if refresh:
            # Re-render bbcode
            model.objects.filter(id=obj.id).update(**{
                '_{}_rendered'.format(field_name):
                get_parser().render(text.raw)
            })
Esempio n. 11
0
def dont_escape(text):
    parser = get_parser()
    return mark_safe(parser.render(text))
 def setup_method(self, method):
     self.parser = get_parser()
Esempio n. 13
0
 def save(self, *args, **kwargs):  # override save to parse bbcode first
     if self.text:
         parser = get_parser()
         self.html_text = parser.render(self.text)
     super().save(*args, **kwargs)
Esempio n. 14
0
 def to_representation(self, instance):
     data = super().to_representation(instance)
     parser = get_parser()
     data["html"] = parser.render(instance.text)
     return data
Esempio n. 15
0
 def setup_method(self, method):
     self.parser = get_parser()
     self.parser.add_bbcode_tag(SizeTag)
     self.parser.add_bbcode_tag(ErroredSizeTag)
     self.parser.add_bbcode_tag(DayTag)
Esempio n. 16
0
def render_example_username(rank, username):
    parser = get_parser()
    if not rank:
        return username
    return mark_safe(
        parser.render(rank.username_modifier.replace('{USER}', username)))
Esempio n. 17
0
def render_bbcodes(text):
    """
    Given an input text, calls the BBCode parser to get the corresponding HTML output.
    """
    parser = get_parser()
    return parser.render(text)
Esempio n. 18
0
    def process(self, board, _ip, thread):
        """
        Add new post/thread.

        :param self: form that needs to handle
        :param board: thread or reply board
        :param _ip: ip of poster
        :param thread: thread id if we work with reply
        :return: True if form is valid and processed
        """
        for banned in Ban.current_banned():
            if ip_address(_ip) >= banned[0] and ip_address(_ip) <= banned[1]:
                return False
        name = self.cleaned_data['name']
        email = self.cleaned_data['email']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        password = self.cleaned_data['password']
        time = datetime.timestamp(datetime.now())
        if thread is None and len(self.files) == 0:
            return False
        if len(self.files) > config['max_images']:
            return False
        if len(body) == 0 and len(self.files) == 0:
            return False
        if spam(body):
            return False
        if len(self.files):
            files = handle_files(self.files, str(time), board)
            if not files:
                return False
        else:
            files = []
        _board = Board.objects.get(uri=board)
        _board.posts += 1
        _board.save()
        new_post = Post.objects.create(id=_board.posts,
                                       time=int(time),
                                       board=Board.objects.get(uri=board),
                                       sage=0,
                                       cycle=0,
                                       locked=0,
                                       sticky=0)
        new_post.name = name
        new_post.num_files = len(files)
        new_post.subject = subject
        new_post.email = email
        bb_parser = get_parser()
        gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
        country_code = gi.country_code_by_addr(_ip)
        nomarkup = '\
            {0}\n<tinyboard flag>{1}</tinyboard>\
            \n<tinyboard proxy>{2}</tinyboard>'.format(body, country_code, _ip)
        body = markup(bb_parser.render(body), board) if len(body) else ''
        new_post.body = body
        new_post.files = json.dumps(files)
        new_post.body_nomarkup = nomarkup
        new_post.password = password
        new_post.ip = _ip
        new_post.thread = thread
        if not new_post.sage and new_post.thread:
            op_post = Post.objects.get(board__uri=board, id=thread)
            op_post.bump = int(time)
            op_post.save()
        new_post.bump = time
        new_post.save()
        return new_post.id
def render_bbcodes(text):
    """
    Given an input text, calls the BBCode parser to get the corresponding HTML output.
    """
    parser = get_parser()
    return parser.render(text)
 def setup_method(self, method):
     self.parser = get_parser()
Esempio n. 21
0
def convert_all_comments():
    parser = get_parser()
    for comment in Comment.objects.exclude(text__exact=''):
        comment.html_text = parser.render(comment.text)
        comment.save()