| 177 | |
| 178 | |
| 179 | class IdleManager: |
| 180 | def __init__(self, direct_imap) -> None: |
| 181 | self.direct_imap = direct_imap |
| 182 | self.log = direct_imap.account.log |
| 183 | # fetch latest messages before starting idle so that it only |
| 184 | # returns messages that arrive anew |
| 185 | self.direct_imap.conn.fetch("1:*") |
| 186 | self.direct_imap.conn.idle.start() |
| 187 | |
| 188 | def check(self, timeout=None) -> List[bytes]: |
| 189 | """(blocking) wait for next idle message from server.""" |
| 190 | self.log("imap-direct: calling idle_check") |
| 191 | res = self.direct_imap.conn.idle.poll(timeout=timeout) |
| 192 | self.log(f"imap-direct: idle_check returned {res!r}") |
| 193 | return res |
| 194 | |
| 195 | def wait_for_new_message(self, timeout=None) -> bytes: |
| 196 | while True: |
| 197 | for item in self.check(timeout=timeout): |
| 198 | if b"EXISTS" in item or b"RECENT" in item: |
| 199 | return item |
| 200 | |
| 201 | def wait_for_seen(self, timeout=None) -> int: |
| 202 | """Return first message with SEEN flag from a running idle-stream.""" |
| 203 | while True: |
| 204 | for item in self.check(timeout=timeout): |
| 205 | if FETCH in item: |
| 206 | self.log(str(item)) |
| 207 | if FLAGS in item and rb"\Seen" in item: |
| 208 | return int(item.split(b" ")[1]) |
| 209 | |
| 210 | def done(self): |
| 211 | """send idle-done to server if we are currently in idle mode.""" |
| 212 | return self.direct_imap.conn.idle.stop() |