Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-message

Source of release 0.5.0

0.5.0 / src / mail_sync / engine.lucb

#==============================================================================================
#
#   mail_sync/engine - The engine: its loop, commands, paths and waiting
#
#==============================================================================================

pub struct Engine:
    var room: Mailroom*
    ## The mail database the window shares; it outlives the engine.
    var store: prism.Store*
    var text: TextPool
    var account: Account
    var session: imap.Session
    var online: bool
    var folders: List[Folder]
    var folder_text: TextPool
    var selected: Buffer
    var last_full_sync: u64
    var wants_full_sync: bool
    var retry_at: u64

    ## An engine for the account in `room`'s configuration line.
    pub static func create(room: Mailroom*) -> Engine!:
        let store = room.store else error(prism.closed, "the mail engine has no store")
        var engine = Engine(room = room, store = store, account = Account(id = "", imap_host = "", imap_port = 993, imap_security = imap.Security.tls, user = "", password = "", smtp_host = "", smtp_port = 587, smtp_security = smtp.Security.starttls, smtp_user = "", smtp_password = ""), wants_full_sync = true)
        errdefer engine.close()
        let fields = Fields.split(room.config.view())
        var scratch: Buffer
        defer scratch.destroy()
        engine.account.id = try engine.config_field(&fields, 0, &scratch)
        engine.account.imap_host = try engine.config_field(&fields, 1, &scratch)
        engine.account.imap_port = (u16)fields.number(2)
        engine.account.imap_security = imap_security(fields.raw(3))
        engine.account.user = try engine.config_field(&fields, 4, &scratch)
        engine.account.password = try engine.config_field(&fields, 5, &scratch)
        engine.account.smtp_host = try engine.config_field(&fields, 6, &scratch)
        engine.account.smtp_port = (u16)fields.number(7)
        engine.account.smtp_security = smtp_security(fields.raw(8))
        engine.account.smtp_user = try engine.config_field(&fields, 9, &scratch)
        engine.account.smtp_password = try engine.config_field(&fields, 10, &scratch)
        return engine

    func config_field(fields: const Fields*, at: usize, scratch: Buffer*) -> str!:
        scratch.clear()
        try fields.unescape(at, scratch)
        return try self.text.keep_text(scratch.view())

    # mark: events ===============================================================================

    ## Post an event of `kind` with up to three fields.
    func post(kind: str, first: const u8[] = b"", second: const u8[] = b"", third: const u8[] = b""):
        var line: Buffer
        defer line.destroy()
        line.put_text(kind) catch failure:
            return
        for field in [first, second, third]:
            if field.length == 0:
                continue
            line.put_byte('\t') catch failure:
                return
            put_field(&line, field) catch failure:
                return
        self.room.post(line.view())

    # mark: the loop =============================================================================

    ## Serve the account until the window stops the engine.
    pub func run():
        while not self.room.stopped():
            self.step() catch failure:
                if self.room.stopped():
                    return
                self.go_offline(failure.message)
                recover ()

    ## One turn: connect if needed, run a waiting command, sync when due, else wait.
    func step() -> !:
        if not self.online:
            if time.now() < self.retry_at:
                self.pause()
                return
            try self.connect()
        var command: Buffer
        defer command.destroy()
        if try self.room.take(&command):
            try self.handle(command.view())
            return
        if self.wants_full_sync or time.now() - self.last_full_sync > full_sync_interval:
            try self.sync_all()
            return
        try self.watch()

    ## Wait a moment for a command or the end, while offline.
    func pause():
        var waited: u64 = 0
        while waited < 1000 and not self.room.stopped() and not self.room.has_command():
            thread.sleep(50)
            waited += 50

    ## Close the session and say why; reconnect after a while.
    func go_offline(reason: str):
        if self.online:
            self.session.close()
        self.online = false
        self.selected.clear()
        self.retry_at = time.now() + retry_delay
        self.post("offline", reason.bytes)

    ## Connect and log in.
    func connect() -> !:
        self.post("status", b"Connecting")
        self.session = try imap.Session.open(self.account.imap_host, self.account.imap_port, self.account.imap_security, cancellation = &self.room.quit)
        self.online = true
        try self.session.login(self.account.user, self.account.password)
        self.wants_full_sync = true
        self.post("online")

    # mark: commands =============================================================================

    ## Run one command line from the window.
    func handle(line: const u8[]) -> !:
        let fields = Fields.split(line)
        let name = fields.raw(0)
        var path: Buffer
        defer path.destroy()
        try fields.unescape(1, &path)
        if name == b"sync":
            self.wants_full_sync = true
        elif name == b"body":
            try self.fetch_body(path.view(), (u32)fields.number(2))
        elif name == b"flags":
            var uids: Buffer
            defer uids.destroy()
            try fields.unescape(2, &uids)
            try self.set_flags(path.view(), uids.view(), fields.number(3) != 0, (u16)fields.number(4))
        elif name == b"move":
            var uids: Buffer
            defer uids.destroy()
            try fields.unescape(2, &uids)
            var target: Buffer
            defer target.destroy()
            try fields.unescape(3, &target)
            try self.move(path.view(), uids.view(), target.view())
        elif name == b"send":
            var sender: Buffer
            defer sender.destroy()
            try fields.unescape(2, &sender)
            var recipients: Buffer
            defer recipients.destroy()
            try fields.unescape(3, &recipients)
            self.send(path.view(), sender.view(), recipients.view())
        elif name == b"draft":
            self.save_draft(path.view())
        elif name == b"search":
            var query: Buffer
            defer query.destroy()
            try fields.unescape(2, &query)
            try self.search(path.view(), query.view())

    # mark: paths ================================================================================

    ## The prism identity of folder `path` onto `out`.
    func folder_identity_of(path: const u8[], out: Buffer*) -> !:
        var key: Buffer
        defer key.destroy()
        try put_key(path, &key)
        try mail_db.folder_identity(self.account.id, key.view(), out)

    # mark: selecting ============================================================================

    ## Select folder `path` unless it is already.
    func select(path: const u8[]) -> imap.Selected!:
        if self.selected.view() == path and self.session.is_selected():
            return self.session.selected
        self.selected.clear()
        let state = try self.session.select((str)path)
        try self.selected.put(path)
        return state

    # mark: waiting ==============================================================================

    ## Wait in IDLE on INBOX until it has news, the window has a command, or a full sync
    ## is due; then bring INBOX up to date if it changed.
    func watch() -> !:
        var inbox: usize? = none
        for at in 0..<self.folders.length():
            if imap.same(self.folders.at(at).path.bytes, b"INBOX"):
                inbox = at
        if inbox == none:
            self.pause()
            return
        let at = inbox else return
        _ = try self.select(b"INBOX")
        self.session.take_events()
        let started = time.now()
        if try self.session.idle_start():
            while not self.room.has_command() and not self.room.stopped() and time.now() - started < full_sync_interval:
                if try self.session.idle_wait(idle_slice):
                    break
            try self.session.idle_done()
        else:
            try self.session.noop()
            if not self.session.has_events():
                self.pause()
        if self.session.has_events():
            self.session.take_events()
            try self.sync_folder(at)
            try self.save_folders()
            self.post("folders")

    pub func close():
        if self.online:
            self.session.logout()
        self.online = false
        self.text.destroy()
        self.folders.destroy()
        self.folder_text.destroy()
        self.selected.destroy()