forked from Qwinpin/erobot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcore.py
194 lines (170 loc) · 5.43 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# built-in
import os
import os.path
import pickle
import random
import time
from collections import namedtuple
from contextlib import contextmanager
# project
import config
from crontab import CronTab
from settings import bot
State = namedtuple('State', ['queue', 'sended', 'failed'])
class Channel:
def __init__(self, rule, state=None):
self.rule = rule
self.state = state
def get_all_files(self):
# make dir if not exists
if not self.rule.path.is_dir():
self.rule.path.mkdir()
# read files from dir
return list(self.rule.path.iterdir())
def flush(self):
# read
files = self.get_all_files()
# shuffle
random.shuffle(files)
# flush state
self.state = State(
queue=files,
sended=[],
failed=[],
)
# return new state
return self.state
def update(self):
files = self.get_all_files()
# find diff (deleted and added files)
diff_files = list((set(files) ^ set(self.state.queue)) - set(self.state.sended))
# get new queue
queue = list(set(files) - set(self.state.sended))
# shuffle queue
random.shuffle(queue)
# update queue in state
self.state = self.state._replace(queue=queue)
return diff_files
def create_cron_task(self):
cron = CronTab()
job = cron.new(command='python3 {} "{}"'.format(
config.PROJECT_PATH / 'send.py',
self.rule.alias,
))
job.setall('0 08,13,19,23 * * *')
return cron.write()
def _send_file(self, file_descriptor, ext, caption):
if ext in ('.jpg', '.png'):
return bot.send_photo(
chat_id=self.rule.chat_id,
photo=file_descriptor,
caption=caption,
)
elif ext == '.txt':
return bot.send_message(
chat_id=self.rule.chat_id,
text=file_descriptor.read().decode(),
)
elif ext == '.md':
return bot.send_message(
chat_id=self.rule.chat_id,
text=file_descriptor.read().decode(),
parse_mode='Markdown',
)
elif ext == '.html':
return bot.send_message(
chat_id=self.rule.chat_id,
text=file_descriptor.read().decode(),
parse_mode='HTML',
)
elif ext == '.mp3':
return bot.send_message(
chat_id=self.rule.chat_id,
audio=file_descriptor,
caption=caption,
)
elif ext == '.ogg':
return bot.send_voice(
chat_id=self.rule.chat_id,
voice=file_descriptor,
caption=caption,
)
else:
return bot.send_document(
chat_id=self.rule.chat_id,
data=file_descriptor,
caption=caption,
)
def send(self, count=1):
for _i in range(count):
if not self.state.queue:
return
fpath = self.state.queue.pop()
self.state.failed.append(fpath)
date = fpath.stat().st_mtime
with fpath.open('rb') as file_descriptor:
self._send_file(
file_descriptor=file_descriptor,
ext=os.path.splitext(str(fpath))[-1],
caption=time.strftime('%d.%m.%Y', time.gmtime(date)),
)
self.state.sended.append(fpath)
self.state.failed.pop()
class ChannelsManager:
channels = None
def __init__(self, rules=config.RULES, storage_file=config.STORAGE_FILE):
self.rules = rules
self.storage_file = storage_file
def flush(self):
# flush channels list
self.channels = []
for rule in self.rules:
# init channel
channel = Channel(rule)
# flush channel state
channel.flush()
# add channel to channels list
self.channels.append(channel)
return self.channels
def read(self):
# init channels by flush method if storage doesn't exist
if not os.path.isfile(self.storage_file):
return self.flush()
# read states from storage
with open(config.STORAGE_FILE, 'rb') as f:
states = pickle.load(f)
# init all channels
self.channels = []
for rule, state in zip(self.rules, states):
channel = Channel(rule, state)
self.channels.append(channel)
return self.channels
def write(self):
states = [channel.state for channel in self.channels]
with open(config.STORAGE_FILE, 'wb') as f:
pickle.dump(states, f)
def update(self):
if not self.channels:
self.read()
updated = []
for channel in self.channels:
updated.extend(channel.update())
return updated
def create_cron_tasks(self):
if not self.channels:
self.read()
for channel in self.channels:
channel.create_cron_task()
def send(self):
if not self.channels:
self.read()
for channel in self.channels:
channel.send()
@contextmanager
def context():
manager = ChannelsManager()
manager.read()
try:
yield manager
finally:
manager.write()