Make Syncer asynchronous (lol)

This commit is contained in:
Dan 2018-06-18 21:11:28 +02:00
parent 8049c9129b
commit e3a667a8fe

View file

@ -16,13 +16,13 @@
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import base64 import base64
import json import json
import logging import logging
import os import os
import shutil import shutil
import time import time
from threading import Thread, Event, Lock
from . import utils from . import utils
@ -33,13 +33,12 @@ class Syncer:
INTERVAL = 20 INTERVAL = 20
clients = {} clients = {}
thread = None event = asyncio.Event()
event = Event() lock = asyncio.Lock()
lock = Lock()
@classmethod @classmethod
def add(cls, client): async def add(cls, client):
with cls.lock: with await cls.lock:
cls.sync(client) cls.sync(client)
cls.clients[id(client)] = client cls.clients[id(client)] = client
@ -48,8 +47,8 @@ class Syncer:
cls.start() cls.start()
@classmethod @classmethod
def remove(cls, client): async def remove(cls, client):
with cls.lock: with await cls.lock:
cls.sync(client) cls.sync(client)
del cls.clients[id(client)] del cls.clients[id(client)]
@ -60,25 +59,24 @@ class Syncer:
@classmethod @classmethod
def start(cls): def start(cls):
cls.event.clear() cls.event.clear()
cls.thread = Thread(target=cls.worker, name=cls.__name__) asyncio.ensure_future(cls.worker())
cls.thread.start()
@classmethod @classmethod
def stop(cls): def stop(cls):
cls.event.set() cls.event.set()
@classmethod @classmethod
def worker(cls): async def worker(cls):
while True: while True:
cls.event.wait(cls.INTERVAL) try:
await asyncio.wait_for(cls.event.wait(), cls.INTERVAL)
if cls.event.is_set(): except asyncio.TimeoutError:
with await cls.lock:
for client in cls.clients.values():
cls.sync(client)
else:
break break
with cls.lock:
for client in cls.clients.values():
cls.sync(client)
@classmethod @classmethod
def sync(cls, client): def sync(cls, client):
temporary = os.path.join(client.workdir, "{}.sync".format(client.session_name)) temporary = os.path.join(client.workdir, "{}.sync".format(client.session_name))