Guest User

Untitled

a guest
Feb 3rd, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.14 KB | None | 0 0
  1. // MailCore imapsessions will be started from here.
  2. func loadAccoutWithUserName(_ userName: String, password: String?, hostname: String, oauth2Token: String?) {
  3. //Setup imap session
  4. imapSession = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
  5. imapSession2 = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
  6. imapSession3 = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
  7. imapSession4 = createNewIMAPSessionWith(userName, hostname: hostname, oauth2Token: oauth2Token!)
  8.  
  9. #if DEBUG
  10. var enableLogger = false
  11. enableLogger = true
  12. if enableLogger {
  13. let lockQueue = DispatchQueue(label: "com.test.LockQueue")
  14. imapSession?.connectionLogger = {(UnsafeMutableRawPointer, type:MCOConnectionLogType, Data) in
  15. lockQueue.sync() {
  16. if (type != MCOConnectionLogType.sentPrivate) {
  17.  
  18. //TODO: better memory management
  19. if let data = Data {
  20. //let errorString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
  21. if let errorString = NSString(data: data, encoding: String.Encoding.utf8.rawValue){
  22. print("Error (errorString)")
  23. print("event logged (String(describing: UnsafeMutableRawPointer!)) withData: (errorString)" as Any)
  24. }
  25. }
  26. }
  27. }
  28. }
  29.  
  30. var _ : NSError?
  31. #if DEBUG
  32. print("going to check op1")
  33. #endif
  34. imapCheckOp = imapSession?.checkAccountOperation()
  35. self.imapCheckOp?.start({ (error) -> Void in
  36. if let error = error{
  37. print("(String(describing: error._userInfo))")
  38. let dict = error._userInfo! as! NSDictionary
  39. let alertString = dict["NSLocalizedDescription"] as? String
  40. if alertString != nil {
  41. self.displayDebugAlert("(alertString!)")
  42. self.imapSession?.disconnectOperation().start({ (error) -> Void in
  43. if let error = error {
  44. print("(error._userInfo!)")
  45. } else {
  46. print("disconnect successfully")
  47. }
  48. })
  49. self.imapSession2?.disconnectOperation().start({ (error) -> Void in
  50. if let error = error {
  51. print("(error._userInfo!)")
  52. } else {
  53. print("disconnect successfully")
  54. }
  55. })
  56. self.imapSession3?.disconnectOperation().start({ (error) -> Void in
  57. if let error = error {
  58. print("(error._userInfo!)")
  59. } else {
  60. print("disconnect successfully")
  61. }
  62. })
  63. self.imapSession4?.disconnectOperation().start({ (error) -> Void in
  64. if let error = error {
  65. print("(error._userInfo!)")
  66. } else {
  67. print("disconnect successfully")
  68. }
  69. })
  70.  
  71. }
  72. self.currentAccount = nil
  73. } else {
  74. self.updateLoggedInDateForAccount()
  75. }
  76. })
  77. }
  78.  
  79. func createNewIMAPSessionWith(_ userName: String, hostname: String, oauth2Token: String) -> MCOIMAPSession {
  80. let retSession = MCOIMAPSession()
  81. retSession.hostname = hostname
  82. retSession.port = 993
  83. retSession.username = userName
  84. retSession.oAuth2Token = oauth2Token
  85. retSession.authType = MCOAuthType.xoAuth2
  86. retSession.connectionType = MCOConnectionType.TLS
  87. retSession.maximumConnections = 1
  88. retSession.timeout = TimeInterval(60)
  89. retSession.allowsFolderConcurrentAccessEnabled = true
  90. return retSession
  91. }
  92.  
  93. var startingIndex = 1
  94. var counter = 0
  95. var sessionForOp : MCOIMAPSession!
  96. while startingIndex <= Int(totalMessageCount!) {
  97. strongSelf.numFetchBatches += 1
  98. if counter % 4 == 0 {
  99. sessionForOp = strongSelf.imapSession
  100. } else if counter % 4 == 1{
  101. sessionForOp = strongSelf.imapSession2
  102. } else if counter % 4 == 2{
  103. sessionForOp = strongSelf.imapSession3
  104. } else {
  105. sessionForOp = strongSelf.imapSession4
  106. }
  107. strongSelf.fetchEmailForFolder(imapFolder.path, expectedMessageCount: Int(totalMessageCount!), startingInt: UInt64(startingIndex), length: UInt64(strongSelf.batchSize), sessionForOp: sessionForOp, queueNo: counter%4)
  108. startingIndex += 1 + strongSelf.batchSize
  109. counter += 1
  110. }
  111. } else {
  112. strongSelf.fetchEmailForFolder(imapFolder.path, expectedMessageCount: Int(totalMessageCount!), sessionForOp: strongSelf.imapSession!)
  113. }
  114. }
  115. })
  116. }
  117. }
  118. }
  119.  
  120. func fetchEmailForFolder(_ path: String, expectedMessageCount: Int, startingInt: UInt64 = 1, length : UInt64 = UINT64_MAX, sessionForOp: MCOIMAPSession, queueNo: Int = 1) {
  121. let requestKind = ( MCOIMAPMessagesRequestKind.headers)
  122. let indexSet = MCOIndexSet(range: MCORangeMake(startingInt, length))
  123.  
  124. let currentFetchMsgOp = sessionForOp.fetchMessagesByNumberOperation(withFolder: path, requestKind: requestKind, numbers: indexSet)
  125. DispatchQueue.main.async { [weak self] in
  126. if let strongSelf = self {
  127. unowned let unownedSelf = strongSelf
  128. currentFetchMsgOp?.progress = {
  129. progress in
  130. var progressPercentage = Float(progress) / Float(expectedMessageCount)
  131. if path == "INBOX" {
  132. // assuming that if it's not sent mail, it's in the inbox
  133. unownedSelf.inboundMailFetched += 1
  134. progressPercentage = Float(unownedSelf.inboundMailFetched) / Float(unownedSelf.inboundMailExpected)
  135. if unownedSelf.inboundMailFetched % 10 == 0 || Int(progress) == unownedSelf.batchSize {
  136. unownedSelf.countLabel.text = "(unownedSelf.inboundMailFetched) scanned"
  137. unownedSelf.percentLabel.text = NSString(format: "%.0f%%", progressPercentage * 100) as String
  138. }
  139. if unownedSelf.inboundMailFetched < 2 {
  140. unownedSelf.statusLabel.text = "Scanning Inbox"
  141. unownedSelf.setUpProgressPie(2)
  142. }
  143. }
  144.  
  145. else if path == unownedSelf.outBoxId {
  146.  
  147. unownedSelf.countLabel.text = "(progress) scanned"
  148. unownedSelf.percentLabel.text = NSString(format: "%.0f%%", progressPercentage * 100) as String
  149. if progress < 2{
  150. unownedSelf.statusLabel.text = "Scanning Sent Mails"
  151. unownedSelf.setUpProgressPie(1)
  152. }
  153. if Int(progress) == expectedMessageCount {
  154. }
  155. } else {
  156. #if DEBUG
  157. print("what path have you gone to little one?")
  158. #endif
  159. }
  160. unownedSelf.progressViewRing!.setProgress(CGFloat(progressPercentage), animated: false)
  161. }
  162. #if DEBUG
  163. print("starting (unownedSelf.batchNum), queue: (queueNo), startingIndex : (startingInt)")
  164. #endif
  165. currentFetchMsgOp?.start({ (error, messages, vanishedMessages) -> Void in
  166. //strongSelf.batchNum++
  167. //MARK: completionOperation of fetchOp
  168.  
  169. if let error = error {
  170. #if DEBUG
  171. print("(String(describing: error._userInfo))")
  172. #endif
  173. } else {
  174. let messagesArr = messages as! [MCOIMAPMessage]
  175. if let existingArr = strongSelf.messageDict![path] as? [MCOIMAPMessage] {
  176. let newArr = existingArr + messagesArr
  177. unownedSelf.messageDict![path] = newArr as NSArray
  178. } else {
  179. unownedSelf.messageDict![path] = messagesArr as NSArray
  180. }
  181. if unownedSelf.numIncompleteProcess == 2 {
  182. unownedSelf.numFetchBatches -= 1
  183. if unownedSelf.inboundMailFetched >= unownedSelf.inboundMailExpected || unownedSelf.isFetchedCompleted || unownedSelf.numFetchBatches == 0 {
  184. unownedSelf.numIncompleteProcess -= 1
  185. let inboundContactCreation = DispatchQueue(label: "inboundContactCreation", attributes: DispatchQueue.Attributes.concurrent)
  186. inboundContactCreation.async {[weak unownedSelf] in
  187. unownedSelf!.populateInboundContacts()
  188. }
  189. } else {
  190. if unownedSelf.inboundMailFetched == strongSelf.lastFetchCount {
  191. if abs(unownedSelf.inboundMailFetched - expectedMessageCount) < unownedSelf.batchSize {
  192. unownedSelf.isFetchedCompleted = true
  193. }
  194. } else {
  195. unownedSelf.lastFetchCount = unownedSelf.inboundMailFetched
  196. }
  197. }
  198. }
  199.  
  200. if unownedSelf.numIncompleteProcess == 1 {
  201. unownedSelf.playChime()
  202. unownedSelf.finishedFetchingInbox()
  203. } else if unownedSelf.numIncompleteProcess == 0 {
  204. unownedSelf.playChime()
  205. unownedSelf.setUpDisplayForFinalSequence()
  206. }
  207. }
  208. })
  209.  
  210. }
  211. }
  212. }
Add Comment
Please, Sign In to add comment