fetchPrevious method

Future<List<BaseMessage>> fetchPrevious({
  1. MessageFetchListener? listener,
  2. dynamic onSuccess(
    1. List<BaseMessage> message
    )?,
  3. dynamic onError(
    1. CometChatException excep
    )?,
})

Returns a list of BaseMessage object fetched after putting the filters.

Android Reference: MessagesRequest.fetchPrevious() Migration Note: Migrated from platform channels to native Dart. Uses MessageRepository for backend communication. Fetches older messages (prepend direction). Offline (opt-in, additive): pass listener for the two-phase read — onCachedMessages (instant local page, may be empty) → onServerMessages (authoritative) / onError.

Backward compatibility: the cache phase is listener-only. A legacy caller (no listener) gets exactly today's behavior — server result via onSuccess, and a failure via onError — whether offline is enabled or not. Nothing is ever served from the cache to a legacy caller.

Implementation

Future<List<BaseMessage>> fetchPrevious({
  MessageFetchListener? listener,
  Function(List<BaseMessage> message)? onSuccess,
  Function(CometChatException excep)? onError,
}) async {
  // Phase 1 — cache. Listener-only. Uses the self-advancing scroll-back
  // anchor so repeated offline calls walk older windows instead of re-serving
  // the newest page. Never touches the server cursor or the in-progress guard.
  var cacheDelivered = false;
  // The timeline cache page delivered, kept for the cache-edge resume.
  List<BaseMessage>? timelineCachePage;
  if (listener != null) {
    try {
      if (_isPinnedList || _isSavedList) {
        // A feature list is served from its own store, in the server's page
        // order, and never from the message table (BEH-PIN-02 / SAVE-02).
        // A null page means no offline store is open: no cache phase. A list
        // with no store of its own gets an empty page (BEH-READ-03).
        final page = await _featureCachePage();
        if (page != null) {
          _storeCursor = page.nextCursor;
          if (page.isEmpty) _storeExhausted = true;
          cacheDelivered = true;
          listener.onCachedMessages(page.messages);
        }
      } else {
        final page = await _timelineCachePage(forward: false);
        if (page != null) {
          cacheDelivered = true;
          timelineCachePage = page.messages;
          listener.onCachedMessages(page.messages);
        }
      }
    } catch (_) {
      // A cache-phase failure is non-fatal; the server phase still runs.
    }
  }
  try {
    // 1. Validate request parameters
    // **Android Reference:** MessagesRequest.fetchPrevious() → validateMessageRequest()
    final validationError = _validateMessageRequest();
    if (validationError != null) {
      if (onError != null) onError(validationError);
      return [];
    }

    // 2. Check updatesOnly without updatedAfter
    // **Android Reference:** if (updatesOnly && updatedAfter == -1)
    final int? updatedAfterLong = updatedAfter != null
        ? updatedAfter!.millisecondsSinceEpoch ~/ 1000
        : null;
    if ((updatesOnly ?? false) && updatedAfterLong == null) {
      final error = CometChatException(
        'ERR_UPDATESONLY_WITHOUT_UPDATEDAFTER',
        'updatedAfter must be set when updatesOnly is true',
        'updatedAfter must be set when updatesOnly is true',
      );
      if (onError != null) onError(error);
      return [];
    }

    // 3. Check hasPrevious flag — return empty list if no more messages
    // **Android Reference:** MessagesRequest.fetchPrevious() hasPrevious check
    // With offline on, a two-phase read past the end still asks the server
    // (BEH-READ-05, R105): see [_readsPastTheEnd].
    if (!_hasPrevious && !_readsPastTheEnd(listener)) {
      if (onSuccess != null) onSuccess([]);
      return [];
    }

    // 4. Check limit does not exceed MAX_LIMIT
    // **Android Reference:** Each fetch method checks limit <= MAX_LIMIT
    if ((limit ?? 0) > (maxLimit ?? 100)) {
      final error = CometChatException(
        'ERR_LIMIT_EXCEEDED',
        'Limit cannot exceed $maxLimit',
        'Limit cannot exceed $maxLimit',
      );
      if (onError != null) onError(error);
      return [];
    }

    // 5. Check inProgress flag — return error if already fetching
    // **Android Reference:** returns ERROR_REQUEST_IN_PROGRESS to onError
    if (_inProgress) {
      final error = CometChatException(
        'ERR_REQUEST_IN_PROGRESS',
        'A fetch request is already in progress',
        'A fetch request is already in progress',
      );
      if (onError != null) onError(error);
      return [];
    }

    // Set inProgress flag before fetch
    // **Android Reference:** MessagesRequest.fetchPrevious() line: inProgress = true
    _inProgress = true;

    // 1. Get SDK instance
    final sdk = SdkRegistry.getInstance();

    // 2. Get updatedAfter as Unix timestamp (already computed above)
    int? updateAfterLong = updatedAfterLong;

    // The feature-list cursor for the NEXT page of a pinned or saved list,
    // from the server's own `meta.cursor` (BEH-PIN-02 / BEH-SAVE-02). Null for
    // every ordinary read, which keeps using the timestamp/messageId cursor.
    final isFeatureList = _isPinnedList || _isSavedList;
    final int? featurePinnedAtCursor = isFeatureList
        ? _featurePinnedAtCursor
        : null;
    final String? featureIdCursor = isFeatureList ? _featureIdCursor : null;
    // Captured as the request goes out: a page answered after this session
    // ended is never written (BEH-SYNC-06).
    final issuedIn = OfflineRuntime.instance.readSession;
    // Captured BEFORE the request goes out: a store row written locally while
    // this page is in the air carries a higher sequence and survives the
    // reconcile (BEH-THR-04 (f)).
    if (isFeatureList) {
      _storeSeqAtDispatch =
          await OfflineRuntime.instance.store?.currentStoreSeq() ?? 0;
    }

    // 3. Call repository based on parentMessageId/uid/guid
    // **Android Reference:** MessagesRequest.fetchPrevious() routing:
    //   parentMessageId first, then uid+guid, then uid, then guid, then fallback
    late final MessagesResult result;

    if (_isSavedList) {
      // A SAVED list is per-viewer and spans every conversation, so it always
      // goes to `GET /messages?saved=1` — uid, guid and parentMessageId are
      // ignored, exactly as the server ignores them (BEH-SAVE-02). Routing it
      // to `/users/{uid}/messages` asked for "this user's saved messages",
      // which is a different list and silently a subset.
      result = await sdk.messages.getMessages(
        limit: limit ?? 30,
        timestamp: _timestamp,
        messageId: _messageId?.toString(),
        affix: 'prepend',
        unread: unread,
        hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
        searchKeyword: searchKeyword,
        updatedAfter: updateAfterLong,
        updatesOnly: updatesOnly,
        categories: categories,
        types: types,
        hideReplies: hideReplies,
        hideDeleted: hideDeleted,
        tags: tags,
        withTags: withTags,
        interactionGoalCompleted: interactionGoalCompletedOnly,
        mentionsWithTagInfo: _mentionsWithTagInfo,
        mentionsWithBlockedInfo: _mentionsWithBlockedInfo,
        hasAttachments: hasAttachments,
        hasLinks: hasLinks,
        hasMentions: hasMentions,
        hasReactions: hasReactions,
        mentionedUids: mentionedUids,
        attachmentTypes: attachmentTypes,
        hideQuotedMessages: hideQuotedMessages,
        pinned: pinned,
        saved: saved,
        // A saved page is ranked by `sentAt`, so it pages on the id of the
        // page's first (oldest) row alone — there is no `pinnedAt` to send.
        featureIdCursor: featureIdCursor,
      );
    } else if (parentMessageId != null && parentMessageId != 0) {
      // Threaded messages — checked FIRST per Android SDK
      result = await sdk.messages.getThreadedMessages(
        parentMessageId.toString(),
        limit: limit ?? 30,
        affix: 'prepend', // fetchPrevious = prepend (older messages)
        timestamp: _timestamp,
        messageId: _messageId?.toString(),
        unread: unread,
        hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
        searchKeyword: searchKeyword,
        updatedAfter: updateAfterLong,
        updatesOnly: updatesOnly,
        categories: categories,
        types: types,
        hideDeleted: hideDeleted,
        tags: tags,
        withTags: withTags,
        interactionGoalCompleted: interactionGoalCompletedOnly,
        mentionsWithTagInfo: _mentionsWithTagInfo,
        mentionsWithBlockedInfo: _mentionsWithBlockedInfo,
        hasAttachments: hasAttachments,
        hasLinks: hasLinks,
        hasMentions: hasMentions,
        hasReactions: hasReactions,
        mentionedUids: mentionedUids,
        attachmentTypes: attachmentTypes,
        withParent: withParent,
        hideQuotedMessages: hideQuotedMessages,
        pinned: pinned,
        saved: saved,
        pinnedAtCursor: featurePinnedAtCursor,
        featureIdCursor: featureIdCursor,
      );
    } else if (uid != null &&
        uid!.isNotEmpty &&
        guid != null &&
        guid!.isNotEmpty) {
      // User messages in a specific group
      // **Android Reference:** fetchMessagesForUserInGroup()
      result = await sdk.messages.getUserMessages(
        uid!,
        limit: limit ?? 30,
        affix: 'prepend',
        timestamp: _timestamp,
        messageId: _messageId?.toString(),
        unread: unread,
        hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
        searchKeyword: searchKeyword,
        updatedAfter: updateAfterLong,
        updatesOnly: updatesOnly,
        categories: categories,
        types: types,
        hideReplies: hideReplies,
        hideDeleted: hideDeleted,
        tags: tags,
        withTags: withTags,
        interactionGoalCompleted: interactionGoalCompletedOnly,
        mentionsWithTagInfo: _mentionsWithTagInfo,
        mentionsWithBlockedInfo: _mentionsWithBlockedInfo,
        hasAttachments: hasAttachments,
        hasLinks: hasLinks,
        hasMentions: hasMentions,
        hasReactions: hasReactions,
        mentionedUids: mentionedUids,
        attachmentTypes: attachmentTypes,
        hideQuotedMessages: hideQuotedMessages,
        pinned: pinned,
        saved: saved,
        pinnedAtCursor: featurePinnedAtCursor,
        featureIdCursor: featureIdCursor,
      );
    } else if (uid != null && uid!.isNotEmpty) {
      // User messages
      result = await sdk.messages.getUserMessages(
        uid!,
        limit: limit ?? 30,
        affix: 'prepend', // fetchPrevious = prepend (older messages)
        timestamp: _timestamp,
        messageId: _messageId?.toString(),
        unread: unread,
        hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
        searchKeyword: searchKeyword,
        updatedAfter: updateAfterLong,
        updatesOnly: updatesOnly,
        categories: categories,
        types: types,
        hideReplies: hideReplies,
        hideDeleted: hideDeleted,
        tags: tags,
        withTags: withTags,
        interactionGoalCompleted: interactionGoalCompletedOnly,
        mentionsWithTagInfo: _mentionsWithTagInfo,
        mentionsWithBlockedInfo: _mentionsWithBlockedInfo,
        hasAttachments: hasAttachments,
        hasLinks: hasLinks,
        hasMentions: hasMentions,
        hasReactions: hasReactions,
        mentionedUids: mentionedUids,
        attachmentTypes: attachmentTypes,
        hideQuotedMessages: hideQuotedMessages,
        pinned: pinned,
        saved: saved,
        pinnedAtCursor: featurePinnedAtCursor,
        featureIdCursor: featureIdCursor,
      );
    } else if (guid != null && guid!.isNotEmpty) {
      // Group messages
      result = await sdk.messages.getGroupMessages(
        guid!,
        limit: limit ?? 30,
        affix: 'prepend', // fetchPrevious = prepend (older messages)
        timestamp: _timestamp,
        messageId: _messageId?.toString(),
        unread: unread,
        hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
        searchKeyword: searchKeyword,
        updatedAfter: updateAfterLong,
        updatesOnly: updatesOnly,
        categories: categories,
        types: types,
        hideReplies: hideReplies,
        hideDeleted: hideDeleted,
        tags: tags,
        withTags: withTags,
        interactionGoalCompleted: interactionGoalCompletedOnly,
        mentionsWithTagInfo: _mentionsWithTagInfo,
        mentionsWithBlockedInfo: _mentionsWithBlockedInfo,
        hasAttachments: hasAttachments,
        hasLinks: hasLinks,
        hasMentions: hasMentions,
        hasReactions: hasReactions,
        mentionedUids: mentionedUids,
        attachmentTypes: attachmentTypes,
        hideQuotedMessages: hideQuotedMessages,
        pinned: pinned,
        saved: saved,
        pinnedAtCursor: featurePinnedAtCursor,
        featureIdCursor: featureIdCursor,
      );
    } else {
      // All messages
      result = await sdk.messages.getMessages(
        limit: limit ?? 30,
        timestamp: _timestamp,
        messageId: _messageId?.toString(),
        affix: 'prepend', // fetchPrevious = prepend (older messages)
        unread: unread,
        hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers,
        searchKeyword: searchKeyword,
        updatedAfter: updateAfterLong,
        updatesOnly: updatesOnly,
        categories: categories,
        types: types,
        hideReplies: hideReplies,
        hideDeleted: hideDeleted,
        tags: tags,
        withTags: withTags,
        interactionGoalCompleted: interactionGoalCompletedOnly,
        mentionsWithTagInfo: _mentionsWithTagInfo,
        mentionsWithBlockedInfo: _mentionsWithBlockedInfo,
        hasAttachments: hasAttachments,
        hasLinks: hasLinks,
        hasMentions: hasMentions,
        hasReactions: hasReactions,
        mentionedUids: mentionedUids,
        attachmentTypes: attachmentTypes,
        hideQuotedMessages: hideQuotedMessages,
        pinned: pinned,
        saved: saved,
        pinnedAtCursor: featurePinnedAtCursor,
        featureIdCursor: featureIdCursor,
      );
    }

    // 4. Update pagination cursor for next fetch
    // For prepend (fetchPrevious), we update to the MIN messageId/timestamp
    // Reference: Android SDK updateMessageIdAndTimestamp() method
    _updatePaginationCursor(result.messages, isAppend: false);

    // 5. Update pagination state from response
    // **Android Reference:** MessagesRequest.fetchPrevious() pagination state update
    _updatePaginationState(result);

    // 6. Update hasNext/hasPrevious flags based on page comparison
    // **Android Reference:** if (affix==PREPEND && currentPage==totalPages) { hasPrevious=false; hasNext=true; }
    if (_currentPage != -1 &&
        _totalPages != -1 &&
        _currentPage == _totalPages) {
      _hasPrevious = false;
      _hasNext = true;
    }
    // Also set hasPrevious=false if no messages returned (safety net)
    if (result.messages.isEmpty) {
      _hasPrevious = false;
    }

    // 7. Reset inProgress flag after successful fetch
    // **Android Reference:** MessagesRequest.fetchPrevious() line: inProgress = false
    _inProgress = false;

    // A feature list walks the server's own order here, so its page IS
    // authoritative: it writes through to the store and reconciles the flag
    // (BEH-THR-04 / BEH-FLAG-07), in place of the message-cache persist and
    // the omission heal, which would both answer the wrong question for it.
    if (_isPinnedList || _isSavedList) {
      // Write BEFORE advancing: the write-through needs to know whether this
      // was the chain's FIRST page, which is what may create the store and
      // what makes a non-overlapping page a replacement rather than a
      // continuation (BEH-THR-04 (d)). Advancing first made every page look
      // like a continuation of one that never happened.
      await _writeFeaturePage(
        result.messages,
        inServerOrder: true,
        issuedIn: issuedIn,
      );
      _advanceFeatureCursor(result);
    }

    // Offline: warm the cache with this server page (no-op when disabled).
    await _persistToCache(result.messages, issuedIn);
    // Then heal read-time forceDelete ghosts by omission (no-op when disabled
    // or under a content filter). Runs only here, on a genuine parsed 200.
    await _healOmittedGhosts(result.messages, issuedIn);

    // 8. Call callbacks (listener wins — never both).
    if (listener != null) {
      listener.onServerMessages(result.messages);
    } else if (onSuccess != null) {
      onSuccess(result.messages);
    }
    return result.messages;
  } on sdk_errors.SdkException catch (sdkEx) {
    // Reset inProgress flag on error
    _inProgress = false;
    // Convert SdkException to CometChatException
    final cometChatEx = CometChatException(
      sdkEx.code,
      sdkEx.details ?? sdkEx.message,
      sdkEx.message,
    );
    _resumeServerAtCacheEdge(timelineCachePage, isAppend: false);
    _deliverFetchError(cometChatEx, listener, onError, cacheDelivered);
  } catch (e) {
    // Reset inProgress flag on error
    _inProgress = false;
    debugPrint("Error: ${e.toString()}");
    // Handle unexpected errors
    final cometChatEx = CometChatException(
      ErrorCode.errorUnhandledException,
      e.toString(),
      e.toString(),
    );
    _resumeServerAtCacheEdge(timelineCachePage, isAppend: false);
    _deliverFetchError(cometChatEx, listener, onError, cacheDelivered);
  }
  return [];
}