2020-01-28 04:55:10 +01:00
//
// F e t c h A l l U n r e a d C o u n t s O p e r a t i o n . s w i f t
// A r t i c l e s D a t a b a s e
//
// C r e a t e d b y B r e n t S i m m o n s o n 1 / 2 6 / 2 0 .
// C o p y r i g h t © 2 0 2 0 R a n c h e r o S o f t w a r e . A l l r i g h t s r e s e r v e d .
//
import Foundation
import RSCore
import RSDatabase
2020-01-28 08:00:48 +01:00
public final class FetchAllUnreadCountsOperation : MainThreadOperation {
2020-01-28 04:55:10 +01:00
2020-02-06 06:18:29 +01:00
public var result : UnreadCountDictionaryCompletionResult = . failure ( . isSuspended )
2020-01-28 04:55:10 +01:00
// M a i n T h r e a d O p e r a t i o n
2020-01-28 08:00:48 +01:00
public var isCanceled = false
public var id : Int ?
public weak var operationDelegate : MainThreadOperationDelegate ?
2020-02-06 06:18:29 +01:00
public var name : String ? = " FetchAllUnreadCountsOperation "
2020-01-28 08:00:48 +01:00
public var completionBlock : MainThreadOperation . MainThreadOperationCompletionBlock ?
2020-01-28 04:55:10 +01:00
private let queue : DatabaseQueue
private let cutoffDate : Date
init ( databaseQueue : DatabaseQueue , cutoffDate : Date ) {
self . queue = databaseQueue
self . cutoffDate = cutoffDate
}
2020-01-28 08:00:48 +01:00
public func run ( ) {
2020-01-28 04:55:10 +01:00
queue . runInDatabase { databaseResult in
if self . isCanceled {
self . informOperationDelegateOfCompletion ( )
return
}
switch databaseResult {
case . success ( let database ) :
self . fetchUnreadCounts ( database )
case . failure :
self . informOperationDelegateOfCompletion ( )
}
}
}
}
private extension FetchAllUnreadCountsOperation {
func fetchUnreadCounts ( _ database : FMDatabase ) {
let sql = " select distinct feedID, count(*) from articles natural join statuses where read=0 and userDeleted=0 and (starred=1 or dateArrived>?) group by feedID; "
guard let resultSet = database . executeQuery ( sql , withArgumentsIn : [ cutoffDate ] ) else {
informOperationDelegateOfCompletion ( )
return
}
2020-02-06 06:18:29 +01:00
var unreadCountDictionary = UnreadCountDictionary ( )
2020-01-28 04:55:10 +01:00
while resultSet . next ( ) {
if isCanceled {
2020-01-30 07:45:55 +01:00
resultSet . close ( )
2020-01-28 04:55:10 +01:00
informOperationDelegateOfCompletion ( )
return
}
let unreadCount = resultSet . long ( forColumnIndex : 1 )
if let webFeedID = resultSet . string ( forColumnIndex : 0 ) {
2020-02-06 06:18:29 +01:00
unreadCountDictionary [ webFeedID ] = unreadCount
2020-01-28 04:55:10 +01:00
}
}
2020-01-30 07:45:55 +01:00
resultSet . close ( )
2020-01-28 04:55:10 +01:00
2020-02-06 06:18:29 +01:00
result = . success ( unreadCountDictionary )
2020-01-28 04:55:10 +01:00
informOperationDelegateOfCompletion ( )
}
}