Compare commits

..

No commits in common. "master" and "stable" have entirely different histories.

33 changed files with 170 additions and 239 deletions

View File

@ -29,6 +29,29 @@ steps:
commands:
- . .drone/github-mirror.sh
###
### Synchronize the `stable` branch to the new release
###
- name: sync-stable-branch
image: alpine
environment:
SSH_PUBKEY:
from_secret: ssh_pubkey
SSH_PRIVKEY:
from_secret: ssh_privkey
PGP_KEY:
from_secret: pgp_key
PGP_KEY_ID:
from_secret: pgp_key_id
commands:
- . .drone/sync-stable-branch.sh
when:
event:
- tag
###
### Rebuild the docs
###
@ -46,6 +69,9 @@ steps:
event:
- tag
depends_on:
- sync-stable-branch
###
### Run the tests
###
@ -194,34 +220,6 @@ steps:
commands:
- . .drone/update-deb-packages.sh
###
### Update the Ubuntu (latest) packages
###
- name: update-ubuntu-packages
image: ubuntu:latest
volumes:
- name: repos
path: /repos
environment:
DEB_VERSION: ubuntu
WORKDIR: /tmp/workdir
APT_ROOT: /repos/apt
PKG_NAME: platypush
when:
branch:
- master
event:
- push
depends_on:
- update-components-cache
commands:
- . .drone/update-deb-packages.sh
###
### Updates the APT repository after new packages have been pushed
###
@ -249,7 +247,6 @@ steps:
depends_on:
- update-debian-stable-packages
- update-debian-oldstable-packages
- update-ubuntu-packages
commands:
- . .drone/update-apt-repo.sh
@ -292,7 +289,7 @@ steps:
###
- name: update-pip-package
image: alpine
image: python:3.11-alpine
environment:
TWINE_USERNAME:
from_secret: pypi_user

View File

@ -14,6 +14,7 @@ git clone 'https://git.platypush.tech/platypush/platypush.wiki.git' wiki
echo "Linking the wiki to the Sphinx index"
cd wiki
ln -s Home.md index.md
cd "$APPDIR/docs"
make html
rm -f config*.yaml

18
.drone/sync-stable-branch.sh Executable file
View File

@ -0,0 +1,18 @@
#!/bin/sh
. .drone/macros/configure-git.sh
. .drone/macros/configure-ssh.sh
. .drone/macros/configure-gpg.sh
# Git configuration
git remote rm origin
git remote add origin git@git.platypush.tech:platypush/platypush.git
# Merge and push to the `stable` branch
git checkout stable
git rebase master
git push -u origin stable
git checkout master
# Restore the original git configuration
mv "$TMP_GIT_CONF" "$GIT_CONF"

View File

@ -1,5 +1,6 @@
#!/bin/sh
[ -f .skipci ] && exit 0
echo "-- Installing dependencies"
@ -20,7 +21,7 @@ done
echo "-- Updating Packages files"
echo "stable\noldstable\nubuntu" | while read distro; do
echo "stable\noldstable" | while read distro; do
echo "main\ndev" | while read branch; do
branch_dir="$TMP_APT_ROOT/pool/$distro/$branch"
echo "Checking pool folder: $branch_dir"
@ -57,7 +58,7 @@ add_hashes() {
done
}
echo "stable\noldstable\nubuntu" | while read distro; do
echo "stable\noldstable" | while read distro; do
dist_dir="$TMP_APT_ROOT/dists/$distro"
components=$(find "$dist_dir" -name Packages | awk -F '/' '{print $(NF-2)}' | uniq | tr '\n' ' ')
release_file="$dist_dir/Release"
@ -81,7 +82,7 @@ done
echo "-- Generating list files"
mkdir -p "$TMP_APT_ROOT/lists"
for distro in stable oldstable ubuntu; do
for distro in stable oldstable; do
for branch in main dev; do
echo "deb https://apt.platypush.tech/ $distro $branch" > "$TMP_APT_ROOT/lists/platypush-$distro-$branch.list"
done
@ -104,43 +105,39 @@ Steps:
1. Add this repository's PGP key to your apt keyring
====================================================
# wget -q -O \\\
$ sudo wget -q -O \\\
/etc/apt/trusted.gpg.d/platypush.asc \\\
https://apt.platypush.tech/pubkey.txt
2. Add the repository to your sources
=====================================
# wget -q -O \\\
$ sudo wget -q -O \\\
/etc/apt/sources.list.d/platypush.list \\\
https://apt.platypush.tech/lists/platypush-<deb_version>-<branch>.list
Where:
- deb_version can be:
- *stable* - current Debian stable version
- *oldstable* - previous Debian stable version
- *ubuntu* - latest Ubuntu version
- branch can be either:
- *main* - latest stable release
- *dev* a package always in sync with the git version
- deb_version can be either *stable* (for the current Debian stable version) or
*oldstable* (for the previous Debian stable version)
- branch can be either *main* (for the latest releases) or *dev* (for a package
that is always in sync with the git version)
For example, to install the latest stable tags on Debian stable:
# wget -q -O \\\
$ sudo wget -q -O \\\
/etc/apt/sources.list.d/platypush.list \\\
https://apt.platypush.tech/lists/platypush-stable-main.list
3. Update your repos
====================
# apt update
$ sudo apt update
4. Install Platypush
====================
# apt install platypush
$ sudo apt install platypush
EOF
echo "-- Importing and refreshing PGP key"

View File

@ -9,7 +9,6 @@ cp -r "$PWD" "$SRCDIR"
cd "$SRCDIR"
echo "-- Installing dependencies"
export DEBIAN_FRONTEND=noninteractive
apt update
apt install -y curl dpkg-dev gpg git python3 python3-pip python3-setuptools

View File

@ -1,5 +1,5 @@
#!/bin/sh
apk add --update --no-cache py3-twine py3-setuptools py3-wheel py3-pip
apk add --update --no-cache py3-twine
python setup.py sdist bdist_wheel
twine upload dist/platypush-$(python setup.py --version).tar.gz

View File

@ -235,16 +235,16 @@ Steps:
1. Add the repository to your sources
=====================================
# yum config-manager --add-repo https://rpm.platypush.tech/platypush.repo
$ sudo yum config-manager --add-repo https://rpm.platypush.tech/platypush.repo
2. Install Platypush
====================
# yum install platypush
$ sudo yum install platypush
Or, if you want to install a version always up-to-date with the git repo:
# yum install platypush-git
$ sudo yum install platypush-git
EOF
cat <<EOF > "$TMP_RPM_ROOT/pubkey.txt"

View File

@ -1,44 +1,6 @@
# Changelog
## [1.0.6] - 2024-06-01
- 🐛 Bug fix on one of the entities modules that prevented the application from
loading when `.` is part of `PYTHONPATH`.
## [1.0.5] - 2024-06-01
- A proper solution for the `utcnow()` issue.
It was a bit trickier than expected to solve, but now Platypush uses a
`utcnow()` facade that always returns a UTC datetime in a timezone-aware
representation.
The code should however also handle the case of timestamps stored on the db in
the old format.
## [1.0.4] - 2024-05-31
- Fixed regression introduced by
[c18768e61fef62924f4c1fac3089ecfb83666dab](https://git.platypush.tech/platypush/platypush/commit/c18768e61fef62924f4c1fac3089ecfb83666dab).
Python seems to have introduced a breaking change from the version 3.12 -
`datetime.utcnow()` is not deprecated, but `datetime.UTC`, the suggested
alternative, isn't available on older versions of Python. Added a workaround
that makes Platypush compatible with both the implementations.
## [1.0.3] - 2024-05-31
- [[#368](https://git.platypush.tech/platypush/platypush/issues/368)] Added
Ubuntu packages.
- Fixed bug that didn't get hooks to match events imported through the new
`platypush.events` symlinked module.
## [1.0.2] - 2024-05-26
- Fixed regression introduced by the support of custom names through the
`@procedure` decorator.
## [1.0.0] - 2024-05-26
## [1.0.0 release candidate]
Many, many changes for the first major release of Platypush after so many
years.

View File

@ -795,49 +795,51 @@ or tags.
#### Debian/Ubuntu
1. Add the Platypush APT key to your trusted keyring:
Currently the following releases are supported:
```
# wget -q -O \
/etc/apt/trusted.gpg.d/platypush.asc \
https://apt.platypush.tech/pubkey.txt
```
1. The current Debian `stable`
2. Debian `oldstable`
2. Add the Platypush repository to your APT sources:
Ubuntu supported [to be added
soon](https://git.platypush.tech/platypush/platypush/issues/368).
```
# wget -q -O \
/etc/apt/sources.list.d/platypush.list \
https://apt.platypush.tech/lists/platypush-<deb_version>-<branch>.list
```
- Add the Platypush APT key to your trusted keyring:
Where:
```
# wget -q -O \
/etc/apt/trusted.gpg.d/platypush.asc \
https://apt.platypush.tech/pubkey.txt
```
- `deb_version` can be either:
- Add the Platypush repository to your APT sources:
- `stable`: current Debian stable
- `oldstable`: previous Debian stable
- `ubuntu`: latest Ubuntu release
```
# wget -q -O \
/etc/apt/sources.list.d/platypush.list \
https://apt.platypush.tech/lists/platypush-<deb_version>-<branch>.list
```
- `branch` can be either:
Where:
- `main`: latest stable release
- `dev`: a package always in sync with the latest git version
- `deb_version` can be either *stable* (for the current Debian stable version) or
*oldstable* (for the previous Debian stable version)
- `branch` can be either *main* (for the latest releases) or *dev* (for a package
that is always in sync with the git version)
For example, to install the latest stable tags on Debian stable:
For example, to install the latest stable tags on Debian stable:
```
# wget -q -O \
/etc/apt/sources.list.d/platypush.list \
https://apt.platypush.tech/lists/platypush-stable-main.list
```
```
# wget -q -O \
/etc/apt/sources.list.d/platypush.list \
https://apt.platypush.tech/lists/platypush-stable-main.list
```
3. Update your repos and install Platypush:
- Update your repos and install Platypush:
```
# apt update
# apt install platypush
```
```
# apt update
# apt install platypush
```
#### Fedora

View File

@ -152,7 +152,7 @@ const generateComponentsGrid = () => {
return
}
if (window.location.pathname === '/' || window.location.pathname.endsWith('/index.html')) {
if (window.location.pathname.endsWith('/index.html')) {
if (tocWrappers.length < 2) {
return
}

View File

@ -23,7 +23,7 @@ when = hook
__author__ = 'Fabio Manganiello <fabio@manganiello.tech>'
__version__ = '1.0.6'
__version__ = '0.99.0'
__all__ = [
'Application',
'Variable',

View File

@ -6,7 +6,6 @@ from flask import Blueprint, request, redirect, render_template, make_response
from platypush.backend.http.app import template_folder
from platypush.backend.http.utils import HttpUtils
from platypush.user import UserManager
from platypush.utils import utcnow
login = Blueprint('login', __name__, template_folder=template_folder)
@ -18,7 +17,7 @@ __routes__ = [
@login.route('/login', methods=['GET', 'POST'])
def login():
"""Login page"""
""" Login page """
user_manager = UserManager()
session_token = request.cookies.get('session_token')
@ -38,11 +37,11 @@ def login():
username = request.form.get('username')
password = request.form.get('password')
remember = request.form.get('remember')
expires = utcnow() + datetime.timedelta(days=365) if remember else None
expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) \
if remember else None
session = user_manager.create_user_session(
username=username, password=password, expires_at=expires
)
session = user_manager.create_user_session(username=username, password=password,
expires_at=expires)
if session:
redirect_target = redirect(redirect_page, 302) # lgtm [py/url-redirection]

View File

@ -6,7 +6,6 @@ from flask import Blueprint, request, redirect, render_template, make_response,
from platypush.backend.http.app import template_folder
from platypush.backend.http.utils import HttpUtils
from platypush.user import UserManager
from platypush.utils import utcnow
register = Blueprint('register', __name__, template_folder=template_folder)
@ -18,7 +17,7 @@ __routes__ = [
@register.route('/register', methods=['GET', 'POST'])
def register():
"""Registration page"""
""" Registration page """
user_manager = UserManager()
redirect_page = request.args.get('redirect')
if not redirect_page:
@ -35,9 +34,7 @@ def register():
return redirect(redirect_page, 302) # lgtm [py/url-redirection]
if user_manager.get_user_count() > 0:
return redirect(
'/login?redirect=' + redirect_page, 302
) # lgtm [py/url-redirection]
return redirect('/login?redirect=' + redirect_page, 302) # lgtm [py/url-redirection]
if request.form:
username = request.form.get('username')
@ -47,18 +44,12 @@ def register():
if password == confirm_password:
user_manager.create_user(username=username, password=password)
session = user_manager.create_user_session(
username=username,
password=password,
expires_at=(
utcnow() + datetime.timedelta(days=1) if not remember else None
),
)
session = user_manager.create_user_session(username=username, password=password,
expires_at=datetime.datetime.utcnow() + datetime.timedelta(days=1)
if not remember else None)
if session:
redirect_target = redirect(
redirect_page, 302
) # lgtm [py/url-redirection]
redirect_target = redirect(redirect_page, 302) # lgtm [py/url-redirection]
response = make_response(redirect_target)
response.set_cookie('session_token', session.session_token)
return response

Binary file not shown.

View File

@ -355,7 +355,7 @@ class Config:
prefix = modname + '.' if prefix is None else prefix
self.procedures.update(
**{
(getattr(obj, 'procedure_name', None) or f'{prefix}{name}'): obj
getattr(obj, 'procedure_name', f'{prefix}.{name}'): obj
for name, obj in inspect.getmembers(module)
if is_functional_procedure(obj)
}

View File

@ -1,9 +1,8 @@
from datetime import datetime, timedelta
import logging
from threading import Event
from typing import Collection, Optional
from platypush.utils import utcnow
from ._base import (
Entity,
EntityKey,
@ -46,8 +45,8 @@ def get_entities_engine(timeout: Optional[float] = None) -> EntitiesEngine:
:param timeout: Timeout in seconds (default: None).
"""
time_start = utcnow().timestamp()
while not timeout or (utcnow().timestamp() - time_start < timeout):
time_start = datetime.utcnow()
while not timeout or (datetime.utcnow() - time_start < timedelta(seconds=timeout)):
if _engine:
break

View File

@ -32,7 +32,6 @@ import platypush
from platypush.config import Config
from platypush.common.db import Base, is_defined
from platypush.message import JSONAble, Message
from platypush.utils import utcnow
EntityRegistryType = Dict[str, Type['Entity']]
entities_registry: EntityRegistryType = {}
@ -83,11 +82,13 @@ if not is_defined('entity'):
external_url = Column(String)
image_url = Column(String)
created_at = Column(DateTime(timezone=False), default=utcnow(), nullable=False)
created_at = Column(
DateTime(timezone=False), default=datetime.utcnow(), nullable=False
)
updated_at = Column(
DateTime(timezone=False),
default=utcnow(),
onupdate=utcnow(),
default=datetime.utcnow(),
onupdate=datetime.utcnow(),
)
parent = relationship(

View File

@ -1,11 +1,12 @@
import inspect
import json
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Any, Optional, Dict, Collection, Type
from platypush.config import Config
from platypush.entities._base import Entity, EntitySavedCallback
from platypush.utils import get_plugin_name_by_class, get_redis, utcnow
from platypush.utils import get_plugin_name_by_class, get_redis
_entity_registry_varname = '_platypush/plugin_entity_registry'
@ -76,7 +77,7 @@ class EntityManager(ABC):
entity.id = None # type: ignore
entity.plugin = get_plugin_name_by_class(self.__class__) # type: ignore
entity.updated_at = utcnow() # type: ignore
entity.updated_at = datetime.utcnow() # type: ignore
entity.children = self._normalize_entities(entity.children)
return entities

View File

@ -1,6 +1,5 @@
import copy
import json
import importlib
import logging
import threading
from functools import wraps
@ -47,7 +46,8 @@ class EventCondition:
kwargs -- Fields rules as a key-value (e.g. source_button=btn_id
or recognized_phrase='Your phrase')
"""
self.type = self._get_event_type(type)
self.type = type or Event.__class__ # type: ignore
self.args = {}
self.parsed_args = {}
self.priority = priority
@ -55,23 +55,6 @@ class EventCondition:
for key, value in kwargs.items():
self.args[key] = value
@staticmethod
def _get_event_type(type: Optional[Type[Event]] = None) -> Type[Event]:
if not type:
return Event
# The package alias `platypush.events` -> `platypush.message.event` is
# supported
if type.__module__.startswith('platypush.events'):
module = importlib.import_module(
'platypush.message.event' + type.__module__[len('platypush.events') :]
)
type = getattr(module, type.__name__)
assert type, f'Invalid event type: {type}'
return type
@classmethod
def build(cls, rule):
"""

View File

@ -19,12 +19,14 @@ class AssistantEvent(Event):
"""
assistant = assistant or kwargs.get('assistant')
if assistant:
kwargs['plugin'] = kwargs['_assistant'] = (
assistant = (
assistant
if isinstance(assistant, str)
else get_plugin_name_by_class(assistant.__class__)
)
kwargs['_assistant'] = assistant
super().__init__(*args, **kwargs)
@property

View File

@ -13,6 +13,7 @@ from platypush.plugins import Plugin, action
from platypush.utils import get_plugin_name_by_class
@dataclass
class AlertType(Enum):
"""
Enum representing the type of an alert.
@ -76,7 +77,7 @@ class AssistantPlugin(Plugin, AssistantEntityManager, ABC):
"""
super().__init__(*args, **kwargs)
self.tts_plugin = tts_plugin
self.tts_plugin_args = {'join': True, **(tts_plugin_args or {})}
self.tts_plugin_args = tts_plugin_args or {}
self.stop_conversation_on_speech_match = stop_conversation_on_speech_match
self._conversation_start_sound = None
if conversation_start_sound:

View File

@ -1,4 +1,4 @@
from datetime import timedelta, timezone
from datetime import datetime, timedelta
from logging import getLogger
from queue import Queue
from typing import Callable, Collection, Dict, Final, List, Optional, Type
@ -16,7 +16,6 @@ from platypush.message.event.bluetooth import (
BluetoothDeviceSignalUpdateEvent,
BluetoothDeviceEvent,
)
from platypush.utils import utcnow
from .._cache import EntityCache
from .._model import ServiceClass
@ -99,7 +98,7 @@ event_matchers: Dict[
)
and (
not (old and old.updated_at)
or utcnow() - old.updated_at.replace(tzinfo=timezone.utc)
or datetime.utcnow() - old.updated_at
>= timedelta(seconds=_rssi_update_interval)
)
),
@ -228,11 +227,9 @@ class EventHandler:
return True
mapped_uuids = [
(
int(str(srv.uuid).split('-', maxsplit=1)[0], 16) & 0xFFFF
if isinstance(srv.uuid, UUID)
else srv.uuid
)
int(str(srv.uuid).split('-', maxsplit=1)[0], 16) & 0xFFFF
if isinstance(srv.uuid, UUID)
else srv.uuid
for srv in device.services
]

View File

@ -4,7 +4,6 @@ from typing import Optional
from platypush.plugins import Plugin, action
from platypush.plugins.calendar import CalendarInterface
from platypush.utils import utcnow
class CalendarIcalPlugin(Plugin, CalendarInterface):
@ -26,7 +25,7 @@ class CalendarIcalPlugin(Plugin, CalendarInterface):
if not t:
return
if isinstance(t.dt, datetime.date):
if type(t.dt) == datetime.date:
return datetime.datetime(
t.dt.year, t.dt.month, t.dt.day, tzinfo=datetime.timezone.utc
).isoformat()
@ -43,23 +42,21 @@ class CalendarIcalPlugin(Plugin, CalendarInterface):
'id': str(event.get('uid')) if event.get('uid') else None,
'kind': 'calendar#event',
'summary': str(event.get('summary')) if event.get('summary') else None,
'description': (
str(event.get('description')) if event.get('description') else None
),
'description': str(event.get('description'))
if event.get('description')
else None,
'status': str(event.get('status')).lower() if event.get('status') else None,
'responseStatus': (
str(event.get('partstat')).lower() if event.get('partstat') else None
),
'responseStatus': str(event.get('partstat')).lower()
if event.get('partstat')
else None,
'location': str(event.get('location')) if event.get('location') else None,
'htmlLink': str(event.get('url')) if event.get('url') else None,
'organizer': (
{
'email': str(event.get('organizer')).replace('MAILTO:', ''),
'displayName': event.get('organizer').params.get('cn'),
}
if event.get('organizer')
else None
),
'organizer': {
'email': str(event.get('organizer')).replace('MAILTO:', ''),
'displayName': event.get('organizer').params.get('cn'),
}
if event.get('organizer')
else None,
'created': cls._convert_timestamp(event, 'created'),
'updated': cls._convert_timestamp(event, 'last-modified'),
'start': {
@ -97,7 +94,10 @@ class CalendarIcalPlugin(Plugin, CalendarInterface):
if (
event['status'] != 'cancelled'
and event['end'].get('dateTime')
and event['end']['dateTime'] >= utcnow().isoformat()
and event['end']['dateTime']
>= datetime.datetime.utcnow()
.replace(tzinfo=datetime.timezone.utc)
.isoformat()
and (
(
only_participating

View File

@ -1,7 +1,8 @@
import datetime
from platypush.plugins import action
from platypush.plugins.google import GooglePlugin
from platypush.plugins.calendar import CalendarInterface
from platypush.utils import utcnow
class GoogleCalendarPlugin(GooglePlugin, CalendarInterface):
@ -71,7 +72,7 @@ class GoogleCalendarPlugin(GooglePlugin, CalendarInterface):
:meth:`platypush.plugins.calendar.CalendarPlugin.get_upcoming_events`.
"""
now = utcnow().replace(tzinfo=None).isoformat() + 'Z'
now = datetime.datetime.utcnow().isoformat() + 'Z'
service = self.get_service('calendar', 'v3')
result = (
service.events()

View File

@ -16,7 +16,6 @@ from platypush.message.event.rss import NewFeedEntryEvent
from platypush.plugins import RunnablePlugin, action
from platypush.plugins.variable import VariablePlugin
from platypush.schemas.rss import RssFeedEntrySchema
from platypush.utils import utcnow
def _variable() -> VariablePlugin:
@ -290,7 +289,7 @@ class RssPlugin(RunnablePlugin):
title = ElementTree.Element('title')
title.text = 'Platypush feed subscriptions'
created = ElementTree.Element('dateCreated')
created.text = self._datetime_to_string(utcnow())
created.text = self._datetime_to_string(datetime.datetime.utcnow())
head.append(title)
head.append(created)

View File

@ -7,7 +7,6 @@ from dateutil.tz import gettz
from platypush.message.event.sun import SunriseEvent, SunsetEvent
from platypush.plugins import RunnablePlugin, action
from platypush.schemas.sun import SunEventsSchema
from platypush.utils import utcnow
class SunPlugin(RunnablePlugin):
@ -64,11 +63,11 @@ class SunPlugin(RunnablePlugin):
@staticmethod
def _convert_time(t: str) -> datetime.datetime:
now = utcnow().replace(microsecond=0)
now = datetime.datetime.now(datetime.UTC).replace(microsecond=0)
dt = datetime.datetime.strptime(
f'{now.year}-{now.month:02d}-{now.day:02d} {t}',
'%Y-%m-%d %I:%M:%S %p',
).replace(tzinfo=datetime.timezone.utc)
).replace(tzinfo=datetime.UTC)
if dt < now:
dt += datetime.timedelta(days=1)

View File

@ -178,7 +178,7 @@ class TtsPicovoicePlugin(TtsPlugin):
self._play_audio(
orca=orca,
pcm=np.array(
orca.synthesize(text, speech_rate=speech_rate)[0],
orca.synthesize(text, speech_rate=speech_rate),
dtype='int16',
),
)

View File

@ -558,9 +558,7 @@ class IfProcedure(Procedure):
return response
def procedure(name_or_func: Optional[str] = None, *upper_args, **upper_kwargs):
name = name_or_func if isinstance(name_or_func, str) else None
def procedure(name: Optional[str] = None):
def func_wrapper(f):
"""
Public decorator to mark a function as a procedure.
@ -571,15 +569,10 @@ def procedure(name_or_func: Optional[str] = None, *upper_args, **upper_kwargs):
@wraps(f)
def _execute_procedure(*args, **kwargs):
args = [*upper_args, *args]
kwargs = {**upper_kwargs, **kwargs}
return exec_wrapper(f, *args, **kwargs)
return _execute_procedure
if callable(name_or_func):
return func_wrapper(name_or_func)
return func_wrapper

View File

@ -18,7 +18,7 @@ from platypush.exceptions.user import (
InvalidJWTTokenException,
InvalidCredentialsException,
)
from platypush.utils import get_or_generate_jwt_rsa_key_pair, utcnow
from platypush.utils import get_or_generate_jwt_rsa_key_pair
class UserManager:
@ -78,7 +78,7 @@ class UserManager:
),
password_salt=password_salt.hex(),
hmac_iterations=hmac_iterations,
created_at=utcnow(),
created_at=datetime.datetime.utcnow(),
**kwargs,
)
@ -115,13 +115,10 @@ class UserManager:
.first()
)
expires_at = (
user_session.expires_at.replace(tzinfo=datetime.timezone.utc)
if user_session and user_session.expires_at
else None
)
if not user_session or (expires_at and expires_at < utcnow()):
if not user_session or (
user_session.expires_at
and user_session.expires_at < datetime.datetime.utcnow()
):
return None, None
user = session.query(User).filter_by(user_id=user_session.user_id).first()
@ -174,7 +171,7 @@ class UserManager:
user_id=user.user_id,
session_token=self.generate_session_token(),
csrf_token=self.generate_session_token(),
created_at=utcnow(),
created_at=datetime.datetime.utcnow(),
expires_at=expires_at,
)

View File

@ -814,12 +814,4 @@ def wait_for_either(*events, timeout: Optional[float] = None, cls: Type = Event)
return OrEvent(*events, cls=cls).wait(timeout=timeout)
def utcnow():
"""
utcnow() without tears. It always returns a datetime object in UTC
timezone.
"""
return datetime.datetime.now(datetime.timezone.utc)
# vim:sw=4:ts=4:et:

View File

@ -28,7 +28,6 @@ mock_imports = [
"dbus",
"deepspeech",
"defusedxml",
"dns",
"docutils",
"envirophat",
"feedparser",

View File

@ -1,5 +1,5 @@
[bumpversion]
current_version = 1.0.6
current_version = 0.99.0
commit = True
tag = True

View File

@ -34,7 +34,8 @@ def parse_deps(deps):
ret = []
for dep in deps:
if dep.startswith('git+'):
continue # Don't include git dependencies in the setup.py, or Twine will complain
repo_name = dep.split('/')[-1].split('.git')[0]
dep = f'{repo_name} @ {dep}'
ret.append(dep)
@ -66,7 +67,7 @@ backend = pkg_files('platypush/backend')
setup(
name="platypush",
version="1.0.6",
version="0.50.3",
author="Fabio Manganiello",
author_email="fabio@manganiello.tech",
description="Platypush service",