Exemplo n.º 1
0
    def detailview_display(self, context):
        request = context['request']
        user = request.user
        reloading_info = self.reloading_info or {}

        item_count_str = str(
            request.GET.get('count') or reloading_info.get('count', ''))
        item_count = int(item_count_str) if item_count_str.isdigit() else 20

        images = TEST_IMAGE_URLS
        image_count = len(images)
        image_ids = [*range(0, image_count - 1)]

        data = []

        for item_id in range(item_count):
            image_name, image_url = images[random_choice(image_ids)]
            data.append(
                Dummy('Dummy ({}) - {}'.format(item_id + 1, image_name), user,
                      media_url(image_url)))

        return self._render(
            self.get_template_context(
                context,
                data,
                reloading_info={'count': item_count},
            ))
Exemplo n.º 2
0
def _render_include_media(bundle, variation):
    variation = variation.copy()
    filetype = os.path.splitext(bundle)[-1].lstrip('.')

    # The "media" variation is special and defines CSS media types
    media_types = None
    if filetype == 'css':
        media_types = variation.pop('media', None)

    if MEDIA_DEV_MODE:
        root = _load_root_filter(bundle)
        variations = root._get_variations_with_input()
        variation_map = [(key, variation.pop(key))
                         for key in sorted(variations.keys())]
        if variation:
            raise ValueError('Bundle %s does not support the following variation(s): %s'
                             % (bundle, ', '.join(variation.keys())))
        _refresh_dev_names()
        bundle_key = _get_key(bundle, variation_map)
        urls = [settings.MEDIA_URL + key for key in _generated_names[bundle_key]]
    else:
        variation_map = tuple((key, variation[key]) for key in sorted(variation.keys()))
        urls = (media_url(_get_key(bundle, variation_map)),)

    if filetype == 'css':
        if media_types:
            tag = u'<link rel="stylesheet" type="text/css" href="%%s" media="%s" />' % media_types
        else:
            tag = u'<link rel="stylesheet" type="text/css" href="%s" />'
    elif filetype == 'js':
        tag = u'<script type="text/javascript" src="%s"></script>'
    else:
        raise ValueError("""Don't know how to include file type "%s".""" % filetype)

    return '\n'.join(tag % url for url in urls)
Exemplo n.º 3
0
def profile_image_url(profile, size):
    if profile and profile.photo:
        return resize(profile.photo, size)
    else:
        square_side = min((int(i) for i in size.split('x')))
        return media_url('img/generic_user_%dx%d.png' %
                         (square_side, square_side))
Exemplo n.º 4
0
    def fixurls(self, match):
        url = match.group(1)

        hashid = ''
        if '#' in url:
            url, hashid = url.split('#', 1)
            hashid = '#' + hashid

        url_query = None
        if '?' in url:
            url, url_query = url.split('?', 1)

        if ':' not in url and not url.startswith('/'):
            rebased_url = posixpath.join(self.base_path, url)
            rebased_url = posixpath.normpath(rebased_url)
            try:
                if GENERATE_DATA_URIS:
                    path = find_file(rebased_url)
                    if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and \
                            not IGNORE_PATTERN.match(rebased_url):
                        data = b64encode(open(path, 'rb').read())
                        mime = guess_type(path)[0] or 'application/octet-stream'
                        return 'url(data:%s;base64,%s)' % (mime, data)
                url = media_url(rebased_url)
            except:
                logging.error('URL not found: %s' % url)

        if url_query is None:
            url_query = ''
        elif '?' in url:
            url_query = '&' + url_query
        else:
            url_query = '?' + url_query

        return 'url(%s%s%s)' % (url, url_query, hashid)
Exemplo n.º 5
0
    def fixurls(self, match):
        url = match.group(1)

        hashid = ''
        if '#' in url:
            url, hashid = url.split('#', 1)
            hashid = '#' + hashid

        url_query = None
        if '?' in url:
            url, url_query = url.split('?', 1)

        if ':' not in url and not url.startswith('/'):
            rebased_url = posixpath.join(self.base_path, url)
            rebased_url = posixpath.normpath(rebased_url)
            try:
                if GENERATE_DATA_URIS:
                    path = find_file(rebased_url)
                    if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and \
                            not IGNORE_PATTERN.match(rebased_url):
                        data = b64encode(open(path, 'rb').read())
                        mime = guess_type(path)[0] or 'application/octet-stream'
                        return 'url(data:%s;base64,%s)' % (mime, data)
                url = media_url(rebased_url)
            except:
                logging.error('URL not found: %s' % url)

        if url_query is None:
            url_query = ''
        elif '?' in url:
            url_query = '&' + url_query
        else:
            url_query = '?' + url_query

        return 'url(%s%s%s)' % (url, url_query, hashid)
Exemplo n.º 6
0
 def fixurls(self, match):
     url = match.group(1)
     if ':' not in url and not url.startswith('/'):
         try:
             url = media_url(url)
         except:
             logging.error('URL not found: %s' % url)
     return 'url(%s)' % url
Exemplo n.º 7
0
def narrow_buttons(request, title, url, buttons=SHOW_SOCIAL_BUTTONS):
    base_url = "http%s://%s" % ("s" if request.is_secure() else "", request.get_host())
    data = _get_url_data(request, title, url)
    code = []
    for name in buttons:
        button = NARROW_BUTTONS[name]
        if not isinstance(button, dict):
            button = {"url": button}
        title = escape(button.get("title", DEFAULT_TITLE % name))
        url = escape(button["url"] % data)
        icon = escape(button.get("icon", media_url("simplesocial/icons32/%s.png" % name.lower())))
        if not icon.startswith(("http://", "https://")):
            icon = base_url + icon
        code.append(BASE_BUTTON % {"title": title, "url": url, "icon": icon})
    return NARROW_BUTTONS_DIV % "\n".join(code)
Exemplo n.º 8
0
    def javascript(self):
        return mark_safe(u'''
                var uploader =  new plupload.Uploader({
                    runtimes : 'flash',
                    use_query_string: false,
                    multipart: true,
                    url: '%(aws_prefix)s',
                    multi_selection: %(multi_selection)s,
                    form: $('#%(id)s').closest('form'),
                    signature_url: '%(signature_url)s',
                    auto_upload: '%(auto_upload)s',
                    browse_button : '%(id)s-upload',
                    filelistelement: $('#%(id)s-filelist'),
                    max_file_size : '%(max_file_size)s',
                    flash_swf_url : '%(swf_url)s',
                    file_data_name: 'file',
                    file_input_name: '%(name)s',
                    filters : [
                        {title : "Supported files (%(allowed_types)s)", extensions : "%(allowed_types)s"}
                    ],
		            resize : {width : 1920, height : 1080, quality : 90}
                });
                uploader.init();
                uploader.bind('FilesAdded', onPluploadFilesAdded);
                uploader.bind('UploadFile', onPluploadUploadFile);
                uploader.bind('UploadProgress', onPluploadUploadProgress);
                uploader.bind('Error', onPluploadError);
                uploader.bind('FileUploaded', onPluploadFileUploaded);
                '''
                % {
                    'multi_selection': 'true' if self.multi_selection else 'false',
                    'signature_url': self.signature_url,
                   # swf: '%ss3_upload.swf',
                    'swf_url': media_url('plupload/plupload.flash.swf'),
                   # $('#%s').val('');
                    'id': self.attrs['id'],
                    # /* auto_upload */
                    'auto_upload': 'true' if self.auto_upload else 'false',
                   # document.getElementById('%s').value='%s' + '%s' + filename;
                    'aws_prefix': settings.AWS_PREFIX,
                   # document.getElementById('%s').value='%s' + '%s' + filename;
                    'name': self.name,
                    'allowed_types': self.allowed_types,
                    'max_file_size': settings.AWS_MAX_FILE_SIZE,
                   } )
Exemplo n.º 9
0
def narrow_buttons(request, title, url, buttons=SHOW_SOCIAL_BUTTONS):
    base_url = 'http%s://%s' % ('s' if request.is_secure() else '',
                                request.get_host())
    data = _get_url_data(request, title, url)
    code = []
    for name in buttons:
        button = NARROW_BUTTONS[name]
        if not isinstance(button, dict):
            button = {'url': button}
        title = escape(button.get('title', DEFAULT_TITLE % name))
        url = escape(button['url'] % data)
        icon = escape(button.get('icon',
                                 media_url('simplesocial/icons32/%s.png'
                                           % name.lower())))
        if not icon.startswith(('http://', 'https://')):
            icon = base_url + icon
        code.append(BASE_BUTTON % {'title': title, 'url': url, 'icon': icon})
    return NARROW_BUTTONS_DIV % '\n'.join(code)
Exemplo n.º 10
0
def narrow_buttons(request, title, url, buttons=SHOW_SOCIAL_BUTTONS):
    base_url = 'http%s://%s' % ('s' if request.is_secure() else '',
                                request.get_host())
    data = _get_url_data(request, title, url)
    code = []
    for name in buttons:
        button = NARROW_BUTTONS[name]
        if not isinstance(button, dict):
            button = {'url': button}
        title = escape(button.get('title', DEFAULT_TITLE % name))
        url = escape(button['url'] % data)
        icon = escape(button.get('icon',
                                 media_url('simplesocial/icons32/%s.png'
                                           % name.lower())))
        if not icon.startswith(('http://', 'https://')):
            icon = base_url + icon
        code.append(BASE_BUTTON % {'title': title, 'url': url, 'icon': icon})
    return NARROW_BUTTONS_DIV % '\n'.join(code)
Exemplo n.º 11
0
    def fixurls(self, match):
        url = original_url = match.group(1)

        hashid = ''
        if '#' in url:
            url, hashid = url.split('#', 1)
            hashid = '#' + hashid

        url_query = None
        if '?' in url:
            url, url_query = url.split('?', 1)

        if ':' not in url and not url.startswith('/'):
            rebased_url = posixpath.join(self.base_path, url)
            rebased_url = posixpath.normpath(rebased_url)
            try:
                if GENERATE_DATA_URIS:
                    path = find_file(rebased_url)
                    if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and \
                            not IGNORE_PATTERN.match(rebased_url):
                        data = b64encode(open(path, 'rb').read())
                        mime = guess_type(
                            path)[0] or 'application/octet-stream'
                        return 'url(data:{};base64,{})'.format(mime, data)

                url = media_url(rebased_url)
            # except:
            except KeyError:
                # logger.error('URL not found: %s' % url)
                global_errors['filters.cssurl'][
                    original_url] = 'URL not found: ' + original_url
            else:
                global_errors['filters.cssurl'].pop(original_url, None)

        if url_query is None:
            url_query = ''
        elif '?' in url:
            url_query = '&' + url_query
        else:
            url_query = '?' + url_query

        return 'url({}{}{})'.format(url, url_query, hashid)
Exemplo n.º 12
0
 def fixurls(self, match):
     url = match.group(1)
     hashid = ""
     if "#" in url:
         url, hashid = url.split("#", 1)
         hashid = "#" + hashid
     if ":" not in url and not url.startswith("/"):
         rebased_url = posixpath.join(self.base_path, url)
         rebased_url = posixpath.normpath(rebased_url)
         try:
             if GENERATE_DATA_URIS:
                 path = find_file(rebased_url)
                 if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and not IGNORE_PATTERN.match(rebased_url):
                     data = b64encode(open(path, "rb").read())
                     mime = guess_type(path)[0] or "application/octet-stream"
                     return "url(data:%s;base64,%s)" % (mime, data)
             url = media_url(rebased_url)
         except:
             logging.error("URL not found: %s" % url)
     return "url(%s%s)" % (url, hashid)
Exemplo n.º 13
0
    def fixurls(self, match):
        url = match.group(1)

        hashid = ''
        if '#' in url:
            url, hashid = url.split('#', 1)
            hashid = '#' + hashid

        url_query = None
        if '?' in url:
            url, url_query = url.split('?', 1)

        if ':' not in url and not url.startswith('/'):
            rebased_url = posixpath.join(self.base_path, url)
            rebased_url = posixpath.normpath(rebased_url)
            try:
                if GENERATE_DATA_URIS:
                    path = find_file(rebased_url)
                    if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and \
                            not IGNORE_PATTERN.match(rebased_url):
                        data = b64encode(open(path, 'rb').read())
                        mime = guess_type(path)[0] or 'application/octet-stream'
                        return 'url(data:%s;base64,%s)' % (mime, data)
                url = media_url(rebased_url)
            except:
                if settings.PRODUCTION:
                    # Removing this from local dev env so we can have a less
                    # cluttered console. Will warn us of issues while testing
                    # on GAE environment.
                    logging.error('URL not found: %s' % url)

        if url_query is None:
            url_query = ''
        elif '?' in url:
            url_query = '&' + url_query
        else:
            url_query = '?' + url_query

        return 'url(%s%s%s)' % (url, url_query, hashid)
Exemplo n.º 14
0
def _render_include_media(bundle, variation):
    if MEDIA_DEV_MODE:
        root = _load_root_filter(bundle)
        variations = root._get_variations_with_input()
        variation_map = [(key, variation[key])
                         for key in sorted(variations.keys())]
        _refresh_dev_names()
        bundle_key = _get_key(bundle, variation_map)
        urls = [settings.MEDIA_URL + key for key in _generated_names[bundle_key]]
    else:
        variation_map = tuple((key, variation[key]) for key in sorted(variation.keys()))
        urls = (media_url(_get_key(bundle, variation_map)),)

    filetype = os.path.splitext(bundle)[-1].lstrip('.')
    if filetype == 'css':
        tag = u'<link rel="stylesheet" type="text/css" href="%s" />'
    elif filetype == 'js':
        tag = u'<script type="text/javascript" src="%s"></script>'
    else:
        raise ValueError("""Don't know how to include file type "%s".""" % filetype)

    return '\n'.join(tag % url for url in urls)
Exemplo n.º 15
0
def get_discipline(request):
    codigo = request.POST["codigo"]
    senha = request.POST["senha"]

    queryset = DisciplineMetadata.objects.filter(cod_turma=codigo, senha=senha)
    if not queryset.exists():
        return HttpResponse(
            '{"status":"erro","mensagem":"Não foi possível localizar uma disciplina com os dados informados"}'
        )

    discipline = queryset[0].discipline

    imagem = "<img style='float:left' src='%s' width='50px' heighth='50px'/>" % media_url("images/books.png")
    if discipline.picture:
        thumb = Picture.get_thumbnail(discipline.picture, 50, 50)
        imagem = "<img style='float:left' src='/image/%d/' width='%dpx' heighth='%dpx'/>" % (
            thumb.id,
            thumb.width,
            thumb.height,
        )

    return HttpResponse(
        u'{"status":"ok","nome":"%s","id":"%s","imagem":"%s"}' % (discipline.name, discipline.id, imagem)
    )
Exemplo n.º 16
0
def media_url(url):
    return utils.media_url(url)
Exemplo n.º 17
0
def profile_image_url(profile, size):
    if profile and profile.photo:
        return resize(profile.photo, size)
    else:
        square_side = min((int(i) for i in size.split("x")))
        return media_url("img/generic_user_%dx%d.png" % (square_side, square_side))
Exemplo n.º 18
0
def user_info(request, user_id):
    user      = User.objects.get(pk=user_id)
    user_info = user.get_profile()

    horario_tbl = None

    if user_info.schedule_cache:
        horario_tbl = user_info.schedule_cache
    else:
        dias      = ('segunda', 'terca', 'quarta', 'quinta', 'sexta', 'sabado')
        cores     = ('#BFCFF2', '#F1c8c8', '#FFCBB6', '#FFFFAA', '#D7BCF2', '#BBBBFF', '#A1EDB2', '#BBFFFF', '#FFF7D7')
        cor_atual = 0
        horarios  = []

        if user_info.is_teacher or user_info.get_disciplines_studies():
            disciplinas = []

            if user_info.is_teacher:
                disciplinas = [d.disciplinemetadata_set.all()[0] for d in user_info.get_disciplines_teaches() if d.disciplinemetadata_set.exists()]
            else:
                disciplinas = [d.disciplinemetadata_set.all()[0] for d in user_info.get_disciplines_studies() if d.disciplinemetadata_set.exists()]

            horario_tbl = u'<h2>Horário</h2>'
            horario_tbl += u'<table id="horario_table">\n'
            horario_tbl += u'<thead><tr><th>&nbsp;</th><th>Segunda</th><th>Terça</th><th>Quarta</th><th>Quinta</th><th>Sexta</th><th>Sábado</th></tr></thead>\n'
            horario_tbl += u'<tbody>\n'

            for d in disciplinas:
                for dia in range(0, 6):
                    if d.__dict__[dias[dia]] and d.__dict__[dias[dia]] != 'null':
                        horarios += get_hora_inicio_fim(d.__dict__[dias[dia]])
            horarios = set(horarios)
            horarios = list(horarios)
            horarios.sort()

            rowspan_map     = {}
            rowspan_app_map = {}

            for hora in horarios:
                for dia in range(0, 6):
                    for d in disciplinas:
                        if d.__dict__[dias[dia]] and d.__dict__[dias[dia]] != 'null':
                            horario = get_hora_inicio_fim(d.__dict__[dias[dia]])
                            if hora >= horario[0] and hora < horario[1]:
                                key = (dia, d)
                                qtd = 0
                                if rowspan_map.has_key(key): qtd = rowspan_map[key]
                                rowspan_map[key] = qtd + 1

            for i in range(len(horarios)):
                hora = horarios[i]
                qtd_hora = 0

                if i < len(horarios) - 1:
                    hora_fim = horarios[i + 1]
                    horario_tmp = u'<tr><th>%02d:%02d<br/>%02d:%02d</th>' % (hora.hour, hora.minute,hora_fim.hour, hora_fim.minute)
                else:
                    horario_tmp = u'<tr><th>%02d:%02d</th>' % (hora.hour, hora.minute)

                for dia in range(0, 6):
                    qtd_dia = 0
                    for d in disciplinas:
                        if d.__dict__[dias[dia]] and d.__dict__[dias[dia]] != 'null':
                            horario = get_hora_inicio_fim(d.__dict__[dias[dia]])

                            if hora >= horario[0] and hora < horario[1]:
                                qtd_dia  += 1
                                qtd_hora += 1

                                key = (dia, d)

                                if not rowspan_app_map.has_key(key):
                                    rowspan_app_map[key] = True

                                    tooltip = u''

                                    if d.discipline.picture:
                                        tooltip += u"<img src='/image/%d/'/>" % Picture.get_thumbnail(d.discipline.picture, 50, 50).id
                                    else:
                                        tooltip += u"<img src='%s' width='50px' height='50px'/>" % media_url('images/books.png')
                                    tooltip += u'%s<br/>'% d.discipline.name
                                    tooltip += u'<b>Sala:</b> %s<br/>' % d.discipline.get_sala()
                                    tooltip += u'<b>Horário:</b> %s' % d.discipline.get_horario().replace('\n', '<br/>')

                                    link = reverse('portal.disciplines.views.detail', args=[d.discipline.course.institution.slug, d.discipline.course.slug, d.discipline.slug])

                                    img = None
                                    if d.discipline.picture:
                                        img = u"<img src='/image/%d/'/>" % Picture.get_thumbnail(d.discipline.picture, 10, 10).id
                                    else:
                                        img = u"<img src='%s' width='10px' height='10px'/>" % media_url('images/books.png')
                                    horario_tmp += u'<td rowspan="%d" class="filled" style="background-color:%s" title="%s"><div>%s<a href="%s">%s</a></div></td>' % (rowspan_map[key], cores[cor_atual], tooltip, img, link, d.discipline.name.split('-')[0])
                                    cor_atual = (cor_atual + 1) % len(cores)
                                break;
                    if qtd_dia == 0:
                        horario_tmp += u'<td>&nbsp;</td>'
                horario_tmp += u'</tr>\n'
                if qtd_hora > 0:
                    horario_tbl += horario_tmp
            horario_tbl += u'</tbody></table>'
        if len(horarios) == 0:
            horario_tbl = ''
            disciplinas = []

            if user_info.is_teacher:
                disciplinas = user_info.get_disciplines_teaches()
            else:
                disciplinas = user_info.get_disciplines_studies()

            if len(disciplinas) > 0:
                horario_tbl += '<h2>Disciplinas</h2>'
                horario_tbl += '<ul class="item_list">'

                for d in disciplinas:
                    horario_tbl += '<li>'
                    horario_tbl += '<a href="%s">' % reverse('portal.disciplines.views.detail', args=[d.course.institution.slug, d.course.slug, d.slug])
                    if d.picture:
                        horario_tbl += '<img src="/image/%d/"/>' % Picture.get_thumbnail(d.picture, 50, 50).id
                    else:
                        horario_tbl += '<img src="%s" width="50px" height="50px"/>' % media_url('images/books.png')
                    horario_tbl += '<p>%s</p>' % d.name
                    horario_tbl += '</a>'
                    horario_tbl += '</li>'

                horario_tbl += '</ul>'
        user_info.schedule_cache = horario_tbl
        user_info.save()

    msg_form = MessageForm(user.get_profile())
    upload_url, upload_data = prepare_upload(request, reverse('portal.messages.views.attach_file'))

    ctx = {
        'user_obj'   : user,
        'profile'    : user.get_profile(),
        'horario'    : horario_tbl,
        'msg_form'   : msg_form,
        'attach_form': AttachmentForm(),
        'upload_url' : upload_url,
        'upload_data': upload_data,
        'next'       : request.get_full_path(),
    }

    return direct_to_template(request, 'registration/profile.html', ctx)
Exemplo n.º 19
0
 def mime_icon(self):
     return media_url('images/txt.png')
Exemplo n.º 20
0
def get_creme_media_url(theme, url):
    return media_url('{}/{}'.format(theme, url))
Exemplo n.º 21
0
    def detailview_display(self, context):
        request = context['request']
        user = request.user
        reloading_info = self.reloading_info or {}

        item_count_str = str(request.GET.get('count') or reloading_info.get('count', ''))
        item_count = int(item_count_str) if item_count_str.isdigit() else 20

        images = TEST_IMAGE_URLS
        image_count = len(images)
        image_ids = list(range(0, image_count - 1))

        data = []

        for item_id in range(item_count):
            image_name, image_url = images[random_choice(image_ids)]
            data.append(Dummy('Dummy ({}) - {}'.format(item_id + 1, image_name), user, media_url(image_url)))

        # return self._render(self.get_block_template_context(
        return self._render(self.get_template_context(
                    context, data,
                    reloading_info={'count': item_count}
                    # update_url='/creme_core/blocks/reload/basic/%s/' % self.id_
                    # update_url=reverse('creme_core__set_block_state', args=(self.id_,)),
        ))
Exemplo n.º 22
0
def media_url(url):
    return utils.media_url(url)
Exemplo n.º 23
0
def get_creme_media_url(theme: str, url: str) -> str:
    return media_url(f'{theme}/{url}')