Example #1
0
from plugins import query
from . import _error, _model, _driver

USER_STATUS_ACTIVE = 'active'
USER_STATUS_WAITING = 'waiting'
USER_STATUS_DISABLED = 'disabled'

_authentication_drivers = OrderedDict(
)  # type: Dict[str, _driver.Authentication]
_storage_driver = None  # type: _driver.Storage

_permission_groups = []
permissions = []
_anonymous_user = None
_system_user = None
_access_tokens = cache.create_pool('auth.access_tokens')  # token: token_info
_user_access_tokens = cache.create_pool(
    'auth.user_access_tokens')  # user.uid: tokens
_current_user = {}  # Current users, per thread
_previous_user = {}  # Previous users, per thread
_access_token_ttl = reg.get('auth.access_token_ttl', 86400)  # 24 hours

user_login_rule = validation.rule.Regex(
    msg_id='auth@login_str_rules',
    pattern='^[A-Za-z0-9][A-Za-z0-9.\-_@]{1,64}$')
user_nickname_rule = validation.rule.Regex(
    msg_id='auth@nickname_str_rules',
    pattern='^[A-Za-z0-9][A-Za-z0-9.\-_]{0,31}$')


def hash_password(secret: str) -> str:
Example #2
0
"""PytSite Comments Plugin API Functions
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

from typing import Dict as Dict, Iterable, Mapping
from frozendict import frozendict
from base64 import b32encode
from pytsite import router, reg, lang, cache, mail, tpl, events, util
from plugins import widget, auth
from . import _driver, _error, _model

_default_driver = None  # type: _driver.Abstract
_drivers = {}  # type: Dict[str, _driver.Abstract]
_comments_count = cache.create_pool('comments.count')

COMMENT_STATUS_PUBLISHED = 'published'
COMMENT_STATUS_WAITING = 'waiting'
COMMENT_STATUS_SPAM = 'spam'
COMMENT_STATUS_DELETED = 'deleted'

_COMMENT_STATUSES = [
    COMMENT_STATUS_PUBLISHED,
    COMMENT_STATUS_WAITING,
    COMMENT_STATUS_SPAM,
    COMMENT_STATUS_DELETED,
]


def register_driver(driver: _driver.Abstract):
Example #3
0
"""PytSite Form2 Plugin API Functions
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

from pytsite import cache, logger, router
from pytsite.http import Request
from ._form import Form

_CACHE_TTL = 604800  # 1 week
_FORMS = cache.create_pool('form2@forms')


def store(form: Form):
    """Put a form into the cache
    """
    _FORMS.put(form.uid, form, _CACHE_TTL)


def dispense(uid: str, request: Request = None) -> Form:
    """Dispense a form from the cache
    """
    try:
        if not _FORMS.has(uid):
            raise KeyError(f"Form '{uid}' is not found")

        form = _FORMS.get(uid)
        form.request = request or router.request()
        return form
Example #4
0
"""PytSite Geo IP API Functions
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

import requests as _requests
import re as _re
from pytsite import cache as _cache
from . import _error, _model

_private_ip_re = _re.compile('(127\.|10\.|172\.(1[6-9]|2[0-9]|3[0-2])|192\.168\.)')
_cache_pool = _cache.create_pool('geo_ip')

# external_api_field: our_field
_field_mapping = {
    'as': 'asn',
    'city': 'city',
    'country': 'country',
    'countryCode': 'country_code',
    'isp': 'isp',
    'lat': 'latitude',
    'lon': 'longitude',
    'org': 'organization',
    'region': 'region',
    'regionName': 'region_name',
    'timezone': 'timezone',
}


def resolve(ip: str) -> _model.GeoIP:
Example #5
0
def plugin_load():
    from pytsite import cache

    cache.create_pool('form.form_cid')
    cache.create_pool('form.form_attrs')
    cache.create_pool('form.form_values')
Example #6
0
def plugin_load():
    from pytsite import cache

    cache.create_pool('auth_ui_password.reset_password_tokens')
Example #7
0
"""PytSite Tumblr Plugin Sessions.
"""
__author__ = 'Alexander Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

from requests_oauthlib import OAuth1Session as _OAuthSession
from pytsite import router as _router, validation as _validation, cache as _cache
from . import _error, _api

_API_BASE_URL = 'https://api.tumblr.com/v2/'
_request_tokens = _cache.create_pool('tumblr.tokens')


class Auth:
    def __init__(self,
                 request_token: str = None,
                 callback_uri: str = None,
                 app_key: str = None,
                 app_secret: str = None):
        """Init.
        """
        self._app_key = app_key or _api.get_app_key()
        self._app_secret = app_secret or _api.get_app_secret()
        self._request_token = None
        self._request_secret = None
        self._oauth_session = None
        self._callback_uri = callback_uri if callback_uri else _router.current_url(
        )

        if request_token:
Example #8
0
"""PytSite Telegram Bot
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

import json
from typing import Union, Mapping
from werkzeug.utils import cached_property
from pytsite import cache, reg, logger, lang, util
from . import _api, types, error
from .reply_markup import ReplyMarkup

_cache_pool = cache.create_pool('telegram.bot_state')


class Bot:
    def __init__(self, token: str):
        """Init
        """
        if not token:
            raise ValueError('Empty token')

        self._id = util.md5_hex_digest(str(self.__class__))
        self._state_ttl = reg.get('telegram.bot_state_ttl', 86400)
        self._token = token
        self._me = None
        self._sender = None  # type: types.User
        self._chat = None  # type: types.Chat
        self._last_message_id = None  # type: int
        self._command_aliases = {}
Example #9
0
"""PytSite Maintenance Mode API
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

from pytsite import console as _console, lang as _lang, cache as _cache

_cache_pool = _cache.create_pool('pytsite.maintenance')


def is_enabled() -> bool:
    """Check whether maintenance mode is enabled.
    """
    return _cache_pool.has('enabled')


def enable(silent: bool = False):
    """Enable maintenance mode.
    """
    if not is_enabled():
        _cache_pool.put('enabled', True)
        if not silent:
            _console.print_success(_lang.t('pytsite.maintenance@maintenance_mode_enabled'))


def disable(silent: bool = False):
    """Disable maintenance mode.
    """
    if is_enabled():
        _cache_pool.rm('enabled')
Example #10
0
"""PytSite Queue API Functions
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '*****@*****.**'
__license__ = 'MIT'

from pytsite import cache as _cache, util as _util, threading as _threading
from typing import Any as _Any, Union as _Union, Callable as _Callable

_POOL = _cache.create_pool('pytsite.queue')


class Task:
    def __init__(self, handler: str, *args, **kwargs):
        if isinstance(handler, str):
            handler = _util.get_module_attr(handler)

        self._handler = handler
        self._args = args
        self._kwargs = kwargs

    def exec(self):
        self._handler(*self._args, **self._kwargs)


class Queue:
    def __init__(self, name: str):
        """Init
        """
        self._name = name
Example #11
0
import subprocess as subprocess
import json
from typing import Dict, List, Tuple, Union, Optional
from os import path, chdir, makedirs, getcwd, symlink, mkdir, listdir
from shutil import rmtree
from importlib.util import find_spec
from pytsite import router, threading, util, reg, console, lang, events, logger, package_info, cache
from . import _error

_packages = {}  # type: Dict[str, Tuple[str, str]]
_inline_js = {}
_building_translations = []

_DEBUG = reg.get('debug', False)
_NODE_BIN_DIR = path.join(reg.get('paths.root'), 'node_modules', '.bin')
_BUILD_TS = cache.create_pool('assetman@timestapms')


def _run_process(cmd: list,
                 passthrough: bool = _DEBUG) -> subprocess.CompletedProcess:
    """Run process.
    """
    stdout = stderr = subprocess.PIPE if not passthrough else None

    return subprocess.run(cmd, stdout=stdout, stderr=stderr)


def _run_node_bin(bin_name: str,
                  args: List[str],
                  passthrough: bool = _DEBUG) -> subprocess.CompletedProcess:
    """Run Node's binary