Example #1
0
    def odm_ui_view_url(self, args: dict = None, **kwargs) -> str:
        """Hook
        """
        target_path = router.url(super().odm_ui_view_url(args, **kwargs), add_lang_prefix=False, as_list=True)[2]

        try:
            target_path = route_alias.get_by_target(target_path, self.language).alias
        except route_alias.error.RouteAliasNotFound:
            pass

        return router.url(target_path, lang=self.language)
Example #2
0
    def as_jsonable(self) -> dict:
        r = {
            'author': {
                'uid': self.author.uid,
                'nickname': self.author.nickname,
                'name': self.author.first_last_name,
                'picture_url': self.author.picture.get_url(width=50, height=50),
            },
            'depth': self.depth,
            'parent_uid': self.parent_uid,
            'permissions': self.permissions,
            'publish_time': {
                'w3c': util.w3c_datetime_str(self.publish_time),
                'pretty_date': lang.pretty_date(self.publish_time),
                'pretty_date_time': lang.pretty_date_time(self.publish_time),
                'ago': lang.time_ago(self.publish_time),
            },
            'children': [c.as_jsonable() for c in self.children],
            'status': self.status,
            'thread_uid': self.thread_uid,
            'uid': self.uid,
            'urls': {
                'delete': http_api.url('comments@delete_comment', {'uid': self.uid}),
                'report': http_api.url('comments@report_comment', {'uid': self.uid}),
                'view': router.url(self.thread_uid, fragment='pytsite-comment-{}'.format(self.uid)),
            },
        }

        if self.status == 'published':
            r.update({
                'body': self.body
            })

        return r
Example #3
0
    def action(self) -> str:
        """Get action's URL
        """
        v = self._attrs['action']

        if v and self.redirect:
            v = _router.url(v, query={'__redirect': self.redirect})

        return v
Example #4
0
    def _get_rule(cls, rule_type: str) -> Optional[str]:
        path = router.current_path()

        ref = router.request().referrer
        ref_path = router.url(ref, add_lang_prefix=False,
                              as_list=True)[2] if ref else ''

        if path.startswith(_ADM_BP) or ref_path.startswith(_ADM_BP):
            rule_type = 'admin_' + rule_type

        return 'odm_ui@' + rule_type
Example #5
0
    def exec(self):
        """Authorization.
        """
        # Check for errors
        error = self.arg('error_description')
        if error:
            _router.session().add_error_message(error)

        # Initializing authorization session
        auth_session = _AuthSession(self.arg('state'))

        return self.redirect(_router.url(auth_session.redirect_uri, query=self.args))
Example #6
0
def url(location: str) -> str:
    """Get URL of an asset.
    """
    if location.startswith('http') or location.startswith('//'):
        return location

    package_name, asset_path = _split_location(location)
    package_name = resolve_package(package_name)
    t = _BUILD_TS.get(package_name) if _BUILD_TS.has(package_name) else 0

    return router.url(f'/assets/{package_name}/{asset_path}',
                      query={'v': t},
                      add_lang_prefix=False)
Example #7
0
def get_user_info(access_token: str, user_id: int) -> dict:
    req_uri = router.url(GET_USER_INFO_URI,
                         query={
                             'access_token': access_token,
                             'user_id': user_id
                         })
    resp = requests.get(req_uri)

    if not resp.ok:
        raise RuntimeError(
            f'Error while querying {req_uri}: {resp.content.decode()}')

    return json.loads(resp.content)
Example #8
0
    def _render_sidebar(sidebar: admin.SideBar) -> htmler.Aside:
        """Render admin's sidebar
        """
        aside = htmler.Aside(css='main-sidebar')
        sidebar_section_em = htmler.Section(css='sidebar')
        aside.append_child(sidebar_section_em)

        root_menu_ul = htmler.Ul(css='sidebar-menu')
        sidebar_section_em.append_child(root_menu_ul)

        sections, menus = sidebar.items

        # Do actual rendering
        for section in sections:
            li = htmler.Li(lang.t(section['title']),
                           css='header',
                           data_section_weight=section['weight'])
            root_menu_ul.append_child(li)

            # Building top level menu item
            for menu in menus[section['sid']]:
                # Link
                a = htmler.A(
                    href=router.url(menu['path'], lang=lang.get_current()))

                # Icon
                if menu['icon']:
                    a.append_child(htmler.I(css=menu['icon']))

                # Title
                a.append_child(htmler.Span(lang.t(menu['title'])))

                # Label
                if menu['label']:
                    label_class = 'label pull-right label-' + menu[
                        'label_class']
                    a.append_child(
                        htmler.Span(lang.t(menu['label']), css=label_class))

                # List element
                li = htmler.Li(data_menu_weight=menu['weight'])

                # Active state
                if menu['active']:
                    li.set_attr('css', 'active')

                li.append_child(a)
                root_menu_ul.append_child(li)

        return aside
Example #9
0
 def get_authorization_url(self,
                           scope='public_profile,email,user_friends'
                           ) -> str:
     """Get authorization URL which used to point user for authorization.
     """
     return _router.url('https://www.facebook.com/dialog/oauth',
                        query={
                            'client_id':
                            self._app_id,
                            'state':
                            self._state,
                            'redirect_uri':
                            _router.rule_url('facebook@authorize'),
                            'scope':
                            scope,
                        })
Example #10
0
    def __init__(self, uid: str, **kwargs):
        """Init.
        """
        super().__init__(uid, **kwargs)

        source_url = kwargs.get('source_url')
        if not source_url:
            raise ValueError('AJAX endpoint is not specified.')

        source_url_query_arg = kwargs.get('source_url_query_arg', self.uid)
        source_url_q = kwargs.get('source_url_args', {})
        source_url_q.update({source_url_query_arg: '__QUERY'})
        source_url = router.url(source_url, query=source_url_q)

        self._data['source_url'] = source_url
        self._data['min_length'] = kwargs.get('typeahead_min_length', 1)
Example #11
0
def nav_link(url: str, anchor: str = '', icon: str = None, **kwargs) -> str:
    """Generate Bootstrap compatible navigation item link
    """
    from pytsite import html, router

    li = html.Li(css=kwargs.pop('li_css', 'nav-item'))

    if not url.startswith('#') and router.url(url, strip_query=True) == router.current_url(strip_query=True):
        li.add_css('active')

    a = html.A(escape_html(anchor), href=url, css=kwargs.pop('a_css', 'nav-link'), **kwargs)
    if icon:
        a.append(html.I(css=icon))

    li.append(a)

    return str(li)
Example #12
0
    def _get_element(self, **kwargs):
        self._data['img_class'] = self._img_css
        self._data['width'] = self._width
        self._data['height'] = self._height

        self._data['img_url'] = router.url('https://maps.googleapis.com/maps/api/staticmap', query={
            'center': '{},{}'.format(self._point.lat, self._point.lng),
            'zoom': self._zoom,
            'scale': self._scale,
            'markers': '|'.join(x for x in self._markers),
            'key': google_maps.helpers.get_google_api_key(),
        })

        if self._linked:
            self._data['link'] = google_maps.maps.link(self._point, zoom=self._zoom)
            self._data['link_target'] = self._link_target

        return htmler.TagLessElement()
Example #13
0
    def get_access_token(self, auth_code: str) -> dict:
        """Get access token from Facebook.
        """
        url = _router.url(_API_REQUEST_URL + 'oauth/access_token',
                          query={
                              'client_id':
                              self._app_id,
                              'client_secret':
                              self._app_secret,
                              'redirect_uri':
                              _router.rule_url('facebook@authorize'),
                              'code':
                              auth_code,
                          })

        r = _requests.get(url).json()
        if 'error' in r:
            raise _error.AuthSessionError(r['error']['message'])

        return r
Example #14
0
    def _get_element(self, **kwargs) -> _html.Element:
        """Render widget.
        :param **kwargs:
        """
        authorize_url = _router.url('https://oauth.vk.com/authorize',
                                    query={
                                        'client_id': self._app_id,
                                        'scope': ','.join(self.scope),
                                        'redirect_uri':
                                        'https://oauth.vk.com/blank.html',
                                        'display': 'page',
                                        'response_type': 'token',
                                        'v': '5.37',
                                    })

        wrapper = _html.TagLessElement()

        wrapper.append(
            _widget.input.Text(
                uid=self.uid + '[access_url]',
                weight=10,
                label=_lang.t('vkontakte@access_url'),
                help=_lang.t('vkontakte@access_url_help',
                             {'link': authorize_url}),
                value=self.access_url,
                required=True,
            ).renderable())

        wrapper.append(
            _widget.input.Integer(uid=self.uid + '[group_id]',
                                  weight=20,
                                  label=_lang.t('vkontakte@group_id'),
                                  value=self.group_id,
                                  h_size='col-sm-2').renderable())

        return wrapper
Example #15
0
def sitemap(url: str, user_agent: str = '*'):
    if user_agent not in __rules:
        __rules[user_agent] = []

    __rules[user_agent].append('Sitemap: {}'.format(_router.url(url)))
Example #16
0
 def _item_url(entity: _model.Menu) -> str:
     return router.url(entity.path)
Example #17
0
 def url(self) -> str:
     return router.url(self._entity.f_get('thread_uid'),
                       fragment='comment-' + self.uid)
Example #18
0
def generate_rss(model: str, filename: str, lng: str = '*',
                 finder_setup: Callable[[odm.SingleModelFinder], None] = None,
                 item_setup: Callable[[feed.xml.Serializable, Content], None] = None, length: int = 20):
    """Generate RSS feeds
    """
    # Setup finder
    finder = find(model, language=lng)
    if finder_setup:
        finder_setup(finder)

    # Preparing output directory
    output_dir = path.join(reg.get('paths.static'), 'feed')
    if not path.exists(output_dir):
        makedirs(output_dir, 0o755, True)

    # Create generator
    content_settings = reg.get('content')
    parser = feed.rss.Parser()

    # Get <channel> element
    channel = parser.get_children('channel')[0]

    # Channel title
    channel.append_child(feed.rss.em.Title(content_settings.get('home_title_' + lng) or 'UNTITLED'))

    # Channel description
    channel.append_child(feed.rss.em.Description(content_settings.get('home_description_' + lng)))

    # Channel link
    channel.append_child(feed.rss.em.Link(router.base_url()))

    # Channel language
    channel.append_child(feed.rss.em.Language(lng))

    # Channel logo
    logo_url = router.url(reg.get('content.rss_logo_url', 'assets/app/img/logo-rss.png'))
    channel.append_child(feed.rss.yandex.Logo(logo_url))
    square_logo_url = router.url(reg.get('content.rss_square_logo_url', 'assets/app/img/logo-rss-square.png'))
    channel.append_child(feed.rss.yandex.Logo(square_logo_url, square=True))

    # Append channel's items
    for entity in finder.get(length):
        item = feed.rss.em.Item()
        try:
            item.append_child(feed.rss.em.Title(entity.title))
            item.append_child(feed.rss.em.Link(entity.url))
            item.append_child(feed.rss.em.PdaLink(entity.url))
            item.append_child(feed.rss.em.Description(entity.description if entity.description else entity.title))
            item.append_child(feed.rss.em.PubDate(entity.publish_time))
            item.append_child(feed.rss.em.Author('{} ({})'.format(entity.author.login, entity.author.first_last_name)))
        except odm.error.FieldNotDefined:
            pass

        # Section
        if entity.has_field('section'):
            item.append_child(feed.rss.em.Category(entity.section.title))

        # Tags
        if entity.has_field('tags'):
            for tag in entity.tags:
                item.append_child(feed.rss.pytsite.Tag(tag.title))

        # Images
        if entity.has_field('images') and entity.images:
            # Attaching all the images as enclosures
            for img in entity.images:
                item.append_child(feed.rss.em.Enclosure(url=img.get_url(), length=img.length, type=img.mime))

        # Video links
        if entity.has_field('video_links') and entity.video_links:
            m_group = item.append_child(feed.rss.media.Group())
            for link_url in entity.video_links:
                m_group.add_widget(feed.rss.media.Player(url=link_url))

        # Body
        if entity.has_field('body'):
            item.append_child(feed.rss.yandex.FullText(entity.f_get('body', process_tags=False, remove_tags=True)))
            item.append_child(feed.rss.content.Encoded(entity.f_get('body', process_tags=False, remove_tags=True)))
            item.append_child(feed.rss.pytsite.FullText(entity.f_get('body', process_tags=False)))

        if item_setup:
            item_setup(item, entity)

        channel.append_child(item)

    # Write feed content
    out_path = path.join(output_dir, '{}-{}.xml'.format(filename, lng))
    with open(out_path, 'wt', encoding='utf-8') as f:
        f.write(parser.generate())

    logger.info("RSS feed successfully written to '{}'.".format(out_path))
Example #19
0
def _generate_sitemap():
    """Generate content sitemap
    """
    global _sitemap_generation_works

    if _sitemap_generation_works:
        raise RuntimeError('Sitemap generation is still in progress')

    _sitemap_generation_works = True
    logger.info('Sitemap generation start.')

    output_dir = path.join(reg.get('paths.static'), 'sitemap')
    if path.exists(output_dir):
        rmtree(output_dir)
    makedirs(output_dir, 0o755, True)

    sitemap_index = sitemap.Index()
    links_per_file = 50000
    loop_count = 1
    loop_links = 1
    sm = sitemap.Sitemap()
    sm.add_url(router.base_url(), datetime.now(), 'always', 1)
    for lng in lang.langs():
        for model in reg.get('content.sitemap_models', ()):
            logger.info(
                "Sitemap generation started for model '{}', language '{}'".
                format(model, lang.lang_title(lng)))

            for entity in _api.find(model,
                                    language=lng):  # type: ContentWithURL
                sm.add_url(entity.url, entity.publish_time)
                loop_links += 1

                # Flush sitemap
                if loop_links >= links_per_file:
                    loop_count += 1
                    loop_links = 0
                    sitemap_path = sm.write(
                        path.join(output_dir, 'data-%02d.xml' % loop_count),
                        True)
                    logger.info(
                        "'{}' successfully written with {} links".format(
                            sitemap_path, loop_links))
                    sitemap_index.add_url(
                        router.url('/sitemap/{}'.format(
                            path.basename(sitemap_path))))
                    del sm
                    sm = sitemap.Sitemap()

    # If non-flushed sitemap exist
    if len(sm):
        sitemap_path = sm.write(
            path.join(output_dir, 'data-%02d.xml' % loop_count), True)
        logger.info("'{}' successfully written with {} links.".format(
            sitemap_path, loop_links))
        sitemap_index.add_url(
            router.url('/sitemap/{}'.format(path.basename(sitemap_path))))

    if len(sitemap_index):
        sitemap_index_path = sitemap_index.write(
            path.join(output_dir, 'index.xml'))
        logger.info("'{}' successfully written.".format(sitemap_index_path))

    logger.info('Sitemap generation stop.')
    _sitemap_generation_works = False