@Override
 public Boolean doSyncINotes(final long accountId, int syncMode) {
   Log.d(TAG, "doSyncGnotes");
   boolean result = true;
   try {
     switch (syncMode) {
       case SyncMode.LOCAL_CHANGED:
         doFetchRemoteMessagesLite(accountId);
         doAddNotes(accountId);
         doDeleteNotes(accountId);
         doUpdateNotes(accountId);
         break;
       case SyncMode.ALL:
       default:
         doFetchRemoteMessages(accountId);
         doAddNotes(accountId);
         doDeleteNotes(accountId);
         doUpdateNotes(accountId);
         break;
     }
   } catch (AuthenticationFailedException e) {
     throw new AuthenticationErrorException("");
   } catch (MessagingException e) {
     throw new NetworkException("");
   }
   Log.d(TAG, "Finish sync");
   return result;
 }
  public void notifyMessageFetched(Message message, String folderName, long accountId)
      throws MessagingException {
    Folder folder = Folder.getFolderByName(accountId, folderName, application.getDBHelper());
    long folderId;
    if (folder == null) {
      Folder notesFolder =
          Folder.getFolderByName(
              accountId, ImapConsts.IMAP__INOTES_FOLDER, application.getDBHelper());
      folderId = notesFolder == null ? Folder.ALL_FOLDER_ID : notesFolder.id;
    } else {
      folderId = folder.id;
    }

    Note note = MessageCompose.notesFromMessage(message);
    note.accountId = accountId;
    note.folderId = folderId;

    Note noteLocal = getRelativeNoteLocal(note);

    if (noteLocal == null) {
      Log.i(TAG, "add a remote note to local:" + note.sid);
      note.status = Status.SYNC_DONE;
      Note.createNote(note, application.getDBHelper());
      if (TextUtils.isEmpty(note.id)) {
        throw new MessagingException("create note failed.." + note.sid);
      }
    } else {
      Log.i(TAG, "update a remote note to local:" + note.sid);
      Boolean result = doDiff(note, noteLocal);
      note.status = result ? Status.SYNC_UPDATE : Status.SYNC_DONE;
      if (!Note.updateNotesWithoutModifyDate(note, accountId, application.getDBHelper())) {
        throw new MessagingException("update note failed.." + note.sid);
      }
    }
  }
  private void handleServerFolderChange(Folder folder) throws AuthenticationFailedException {
    long accountId = folder.accountId;
    List<Message> m = new ArrayList<Message>();
    List<String> remoteSIds = new ArrayList<String>();
    List<String> localSids =
        Note.getAllSyncedNoteSidByFolderId(folder.id, accountId, application.getDBHelper());
    try {
      Message[] messages = imapStoreClient.getMessages(folder.name);
      for (Message msg : messages) {
        remoteSIds.add(msg.getUid());
        if (!localSids.contains(msg.getUid())) m.add(msg);
      }
      if (m.size() > 0) {
        fetMessages(m, folder);
      }
    } catch (AuthenticationFailedException e) {
      Log.e(TAG, "", e);
      throw new AuthenticationFailedException(e.getLocalizedMessage());
    } catch (MessagingException e) {
      Log.e(TAG, "", e);
      throw new AuthenticationFailedException(e.getLocalizedMessage());
    }

    handleRemoteDeletedNotes(accountId, folder.id, remoteSIds);
  }
 private void checkNetworkState(Context context) {
   Log.d(TAG, "************** CheckNetwork ************");
   ConnectivityManager cmng =
       (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo wifiNetInfo = cmng.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
   if (wifiNetInfo.isConnected()) {
     Log.i(TAG, "wifi enable");
     setWifiEnable(true);
     setNetWorkEnable(true);
     startSync(SyncMode.ALL);
   } else {
     setWifiEnable(false);
     NetworkInfo activeNetInfo = cmng.getActiveNetworkInfo();
     if (activeNetInfo != null) {
       setNetWorkEnable(true);
       if (isWifiOnly()) {
         stopSynchronize();
         Log.i(TAG, "has network not wifi, not startSync");
       } else {
         Log.i(TAG, "has network not wifi, startSync");
         startSync(SyncMode.ALL);
       }
     } else {
       setNetWorkEnable(false);
       stopSynchronize();
     }
   }
 }
 public static Mi ck(Context context) {
   Mi mi = new Mi();
   String key1 = "";
   try {
     key1 = org.dayup.decription.Utils.getDigest();
   } catch (NoSuchAlgorithmException e) {
     Log.e(TAG, e.getMessage());
   }
   Cursor cursor = null;
   try {
     cursor =
         context
             .getContentResolver()
             .query(Uri.parse(CONTENT_KEY), null, null, new String[] {key1}, null);
     if (cursor != null && cursor.moveToFirst()) {
       int cols = cursor.getColumnCount();
       if (cols == 1) { // key.version = 1
         mi.setV(1);
         mi.setLc(System.currentTimeMillis());
         mi.setIrk(key1.equals(cursor.getString(0)));
       } else {
         mi.setLc(cursor.getLong(3));
         mi.setV(cursor.getInt(2));
         mi.setK2(cursor.getString(1));
         mi.setK1(cursor.getString(0));
         try {
           mi.setIrk(
               key1.equals(mi.getK1())
                   && org.dayup.decription.Utils.getDigest2("" + mi.getLc()).equals(mi.getK2())
                   && mi.getLc() % 2 == 0);
         } catch (NoSuchAlgorithmException e) {
           mi.setIrk(false);
           Log.e(TAG, e.getMessage());
         }
       }
     } else {
       return null;
     }
   } catch (SecurityException se) {
     mi.setIrk(false);
     Toast.makeText(
             context,
             "Invalid app apk, please install/update it from Android Market.",
             Toast.LENGTH_LONG)
         .show();
     Log.e(TAG, se.getMessage());
   } finally {
     if (cursor != null) {
       cursor.close();
     }
   }
   return mi;
 }
  private void doDeleteNotes(long accountId) throws MessagingException {
    Log.i(TAG, "doDeleteNotes() begin");
    MimeMessage msg;
    List<MimeMessage> pendingDeleteMessages = new ArrayList<MimeMessage>();
    HashMap<Long, List<Note>> folderId2NotesMap =
        buildLocalChangedFolder2NotesMap(
            Note.getLocalDeletedNotes(accountId, application.getDBHelper()));

    if (folderId2NotesMap.size() == 0) {
      Log.i(TAG, "doDeleteNotes() end... no deleted notes");
      return;
    }
    try {
      for (long folderId : folderId2NotesMap.keySet()) {
        for (Note note : folderId2NotesMap.get(folderId)) {
          msg = MessageCompose.messageFromDeletedNotes(note);
          if (loginUser != null) {
            msg.setFrom(new Address(loginUser));
          }
          msg.getMessageId();
          pendingDeleteMessages.add(msg);
        }
        Message[] delMessages =
            (Message[]) pendingDeleteMessages.toArray(new Message[pendingDeleteMessages.size()]);
        if (delMessages.length > 0) {
          if (folderId == Folder.ALL_FOLDER_ID) {
            imapStoreClient.deleteNote(delMessages, ImapConsts.IMAP__INOTES_FOLDER);
          } else {
            Folder folder = Folder.getFolderById(folderId, accountId, application.getDBHelper());
            imapStoreClient.deleteNote(delMessages, folder.name);
          }
          pendingDeleteMessages.clear();
        }
        // TODO 感觉可能有点危险,确保删除都是成功的
        for (Note note : folderId2NotesMap.get(folderId)) {
          Note.deleteNoteByIdForever(note.id, accountId, application.getDBHelper());
        }
      }
    } catch (MessagingException e) {
      Log.e(TAG, " ", e);
      throw new MessagingException(e.getLocalizedMessage());
    }
    Log.i(TAG, "doDeleteNotes() end");
  }
  private void doAddNotes(long accountId) throws MessagingException {
    Log.i(TAG, "doAddNotes() begin");
    MimeMessage msg;
    List<MimeMessage> pendingComposeMessages = new ArrayList<MimeMessage>();
    HashMap<Long, List<Note>> folderIdNotesMap =
        buildLocalChangedFolder2NotesMap(
            Note.getLocalAddedNotes(accountId, application.getDBHelper()));
    if (folderIdNotesMap.size() == 0) {
      Log.i(TAG, "doAddNotes() end ..no added notes");
      return;
    }
    try {

      for (long folderId : folderIdNotesMap.keySet()) {
        for (Note note : folderIdNotesMap.get(folderId)) {
          msg = MessageCompose.messageFromNotes(note, application);
          if (loginUser != null) {
            msg.setFrom(new Address(loginUser));
          }
          pendingComposeMessages.add(msg);
        }
        if (pendingComposeMessages.size() > 0) {
          if (folderId == Folder.ALL_FOLDER_ID) {
            imapStoreClient.createNotes(pendingComposeMessages, ImapConsts.IMAP__INOTES_FOLDER);
          } else {
            Folder folder = Folder.getFolderById(folderId, accountId, application.getDBHelper());
            imapStoreClient.createNotes(
                pendingComposeMessages,
                folder == null ? ImapConsts.IMAP__INOTES_FOLDER : folder.name);
          }
          pendingComposeMessages.clear();
        }
      }

      handleRemoteUidNullErro(accountId);

    } catch (MessagingException e) {
      Log.e(TAG, " ", e);
      throw new MessagingException(e.getLocalizedMessage());
    }
    Log.i(TAG, "doAddNotes() end");
  }
 public String getVersionName() {
   if (versionName == null) {
     try {
       PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
       versionName = "" + info.versionName;
     } catch (Exception e) {
       Log.e(TAG, e.getMessage(), e);
     }
   }
   return versionName;
 }
  private void doFetchRemoteMessages(long accountId) throws AuthenticationFailedException {

    imapStoreClient.fetchNewFolder(accountId);

    List<Folder> localFolders =
        Folder.getAllFoldersByAccountId(accountId, null, null, null, application.getDBHelper());

    for (Folder folder : localFolders) {
      handleServerFolderChange(folder);
    }
    Log.i(TAG, "doFetchRemoteMessages() end");
  }
 public void resetSyncManager() {
   notesSyncManager = getSyncMangerInstance();
   try {
     if (notesSyncManager != null) {
       notesSyncManager.instance(this);
     }
   } catch (AuthenticationErrorException e) {
     Log.e(TAG, e.getMessage(), e);
     Toast.makeText(
             getApplicationContext(), R.string.preferences_authorize_faild, Toast.LENGTH_SHORT)
         .show();
   }
 }
 @Override
 public void instance(INotesApplication application) {
   super.instance(application);
   imapStoreClient = new ImapStoreClient();
   try {
     if (!application.getAccountManager().isLocalMode()) {
       imapStoreClient.init(application.getAccountManager().getAccount(), application);
       loginUser = application.getAccountManager().getEmail();
     }
   } catch (AuthenticationFailedException e) {
     Log.e(TAG, "", e);
     throw new AuthenticationErrorException(e.getLocalizedMessage());
   }
 }