Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MailCore imapsessions will be started from here.
- func loadAccoutWithUserName(_ userName: String, password: String?, hostname: String, oauth2Token: String?) {
- //Setup imap session
- imapSession = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
- imapSession2 = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
- imapSession3 = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
- imapSession4 = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
- #if DEBUG
- var enableLogger = false
- enableLogger = true
- if enableLogger {
- let lockQueue = DispatchQueue(label: "com.test.LockQueue")
- imapSession?.connectionLogger = {(UnsafeMutableRawPointer, type:MCOConnectionLogType, Data) in
- lockQueue.sync() {
- if (type != MCOConnectionLogType.sentPrivate) {
- //TODO: better memory management
- if let data = Data {
- //let errorString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
- if let errorString = NSString(data: data, encoding: String.Encoding.utf8.rawValue){
- print("Error (errorString)")
- print("event logged (String(describing: UnsafeMutableRawPointer!)) withData: (errorString)" as Any)
- }
- }
- }
- }
- }
- var _ : NSError?
- #if DEBUG
- print("going to check op1")
- #endif
- imapCheckOp = imapSession?.checkAccountOperation()
- self.imapCheckOp?.start({ (error) -> Void in
- if let error = error{
- print("(String(describing: error._userInfo))")
- let dict = error._userInfo! as! NSDictionary
- let alertString = dict["NSLocalizedDescription"] as? String
- if alertString != nil {
- self.displayDebugAlert("(alertString!)")
- self.imapSession?.disconnectOperation().start({ (error) -> Void in
- if let error = error {
- print("(error._userInfo!)")
- } else {
- print("disconnect successfully")
- }
- })
- self.imapSession2?.disconnectOperation().start({ (error) -> Void in
- if let error = error {
- print("(error._userInfo!)")
- } else {
- print("disconnect successfully")
- }
- })
- self.imapSession3?.disconnectOperation().start({ (error) -> Void in
- if let error = error {
- print("(error._userInfo!)")
- } else {
- print("disconnect successfully")
- }
- })
- self.imapSession4?.disconnectOperation().start({ (error) -> Void in
- if let error = error {
- print("(error._userInfo!)")
- } else {
- print("disconnect successfully")
- }
- })
- }
- self.currentAccount = nil
- } else {
- self.updateLoggedInDateForAccount()
- }
- })
- }
- func createNewIMAPSessionWith(_ userName: String, hostname: String, oauth2Token: String) -> MCOIMAPSession {
- let retSession = MCOIMAPSession()
- retSession.hostname = hostname
- retSession.port = 993
- retSession.username = userName
- retSession.oAuth2Token = oauth2Token
- retSession.authType = MCOAuthType.xoAuth2
- retSession.connectionType = MCOConnectionType.TLS
- retSession.maximumConnections = 1
- retSession.timeout = TimeInterval(60)
- retSession.allowsFolderConcurrentAccessEnabled = true
- return retSession
- }
- var startingIndex = 1
- var counter = 0
- var sessionForOp : MCOIMAPSession!
- while startingIndex <= Int(totalMessageCount!) {
- strongSelf.numFetchBatches += 1
- if counter % 4 == 0 {
- sessionForOp = strongSelf.imapSession
- } else if counter % 4 == 1{
- sessionForOp = strongSelf.imapSession2
- } else if counter % 4 == 2{
- sessionForOp = strongSelf.imapSession3
- } else {
- sessionForOp = strongSelf.imapSession4
- }
- strongSelf.fetchEmailForFolder(imapFolder.path, expectedMessageCount: Int(totalMessageCount!), startingInt: UInt64(startingIndex), length: UInt64(strongSelf.batchSize), sessionForOp: sessionForOp, queueNo: counter%4)
- startingIndex += 1 + strongSelf.batchSize
- counter += 1
- }
- } else {
- strongSelf.fetchEmailForFolder(imapFolder.path, expectedMessageCount: Int(totalMessageCount!), sessionForOp: strongSelf.imapSession!)
- }
- }
- })
- }
- }
- }
- func fetchEmailForFolder(_ path: String, expectedMessageCount: Int, startingInt: UInt64 = 1, length : UInt64 = UINT64_MAX, sessionForOp: MCOIMAPSession, queueNo: Int = 1) {
- let requestKind = ( MCOIMAPMessagesRequestKind.headers)
- let indexSet = MCOIndexSet(range: MCORangeMake(startingInt, length))
- let currentFetchMsgOp = sessionForOp.fetchMessagesByNumberOperation(withFolder: path, requestKind: requestKind, numbers: indexSet)
- DispatchQueue.main.async { [weak self] in
- if let strongSelf = self {
- unowned let unownedSelf = strongSelf
- currentFetchMsgOp?.progress = {
- progress in
- var progressPercentage = Float(progress) / Float(expectedMessageCount)
- if path == "INBOX" {
- // assuming that if it's not sent mail, it's in the inbox
- unownedSelf.inboundMailFetched += 1
- progressPercentage = Float(unownedSelf.inboundMailFetched) / Float(unownedSelf.inboundMailExpected)
- if unownedSelf.inboundMailFetched % 10 == 0 || Int(progress) == unownedSelf.batchSize {
- unownedSelf.countLabel.text = "(unownedSelf.inboundMailFetched) scanned"
- unownedSelf.percentLabel.text = NSString(format: "%.0f%%", progressPercentage * 100) as String
- }
- if unownedSelf.inboundMailFetched < 2 {
- unownedSelf.statusLabel.text = "Scanning Inbox"
- unownedSelf.setUpProgressPie(2)
- }
- }
- else if path == unownedSelf.outBoxId {
- unownedSelf.countLabel.text = "(progress) scanned"
- unownedSelf.percentLabel.text = NSString(format: "%.0f%%", progressPercentage * 100) as String
- if progress < 2{
- unownedSelf.statusLabel.text = "Scanning Sent Mails"
- unownedSelf.setUpProgressPie(1)
- }
- if Int(progress) == expectedMessageCount {
- }
- } else {
- #if DEBUG
- print("what path have you gone to little one?")
- #endif
- }
- unownedSelf.progressViewRing!.setProgress(CGFloat(progressPercentage), animated: false)
- }
- #if DEBUG
- print("starting (unownedSelf.batchNum), queue: (queueNo), startingIndex : (startingInt)")
- #endif
- currentFetchMsgOp?.start({ (error, messages, vanishedMessages) -> Void in
- //strongSelf.batchNum++
- //MARK: completionOperation of fetchOp
- if let error = error {
- #if DEBUG
- print("(String(describing: error._userInfo))")
- #endif
- } else {
- let messagesArr = messages as! [MCOIMAPMessage]
- if let existingArr = strongSelf.messageDict![path] as? [MCOIMAPMessage] {
- let newArr = existingArr + messagesArr
- unownedSelf.messageDict![path] = newArr as NSArray
- } else {
- unownedSelf.messageDict![path] = messagesArr as NSArray
- }
- if unownedSelf.numIncompleteProcess == 2 {
- unownedSelf.numFetchBatches -= 1
- if unownedSelf.inboundMailFetched >= unownedSelf.inboundMailExpected || unownedSelf.isFetchedCompleted || unownedSelf.numFetchBatches == 0 {
- unownedSelf.numIncompleteProcess -= 1
- let inboundContactCreation = DispatchQueue(label: "inboundContactCreation", attributes: DispatchQueue.Attributes.concurrent)
- inboundContactCreation.async {[weak unownedSelf] in
- unownedSelf!.populateInboundContacts()
- }
- } else {
- if unownedSelf.inboundMailFetched == strongSelf.lastFetchCount {
- if abs(unownedSelf.inboundMailFetched - expectedMessageCount) < unownedSelf.batchSize {
- unownedSelf.isFetchedCompleted = true
- }
- } else {
- unownedSelf.lastFetchCount = unownedSelf.inboundMailFetched
- }
- }
- }
- if unownedSelf.numIncompleteProcess == 1 {
- unownedSelf.playChime()
- unownedSelf.finishedFetchingInbox()
- } else if unownedSelf.numIncompleteProcess == 0 {
- unownedSelf.playChime()
- unownedSelf.setUpDisplayForFinalSequence()
- }
- }
- })
- }
- }
- }
Add Comment
Please, Sign In to add comment