/**
   * Create a task container for the given remote task
   *
   * @throws JSONException
   */
  private GtasksTaskContainer parseRemoteTask(
      com.google.api.services.tasks.model.Task remoteTask, String listId) {
    Task task = new Task();

    ArrayList<Metadata> metadata = new ArrayList<Metadata>();

    task.setValue(Task.TITLE, remoteTask.getTitle());
    task.setValue(Task.CREATION_DATE, DateUtilities.now());
    task.setValue(
        Task.COMPLETION_DATE,
        GtasksApiUtilities.gtasksCompletedTimeToUnixTime(remoteTask.getCompleted(), 0));
    if (remoteTask.getDeleted() == null || !remoteTask.getDeleted().booleanValue())
      task.setValue(Task.DELETION_DATE, 0L);
    else if (remoteTask.getDeleted().booleanValue())
      task.setValue(Task.DELETION_DATE, DateUtilities.now());
    if (remoteTask.getHidden() != null && remoteTask.getHidden().booleanValue())
      task.setValue(Task.DELETION_DATE, DateUtilities.now());

    long dueDate = GtasksApiUtilities.gtasksDueTimeToUnixTime(remoteTask.getDue(), 0);
    long createdDate = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate);
    task.setValue(Task.DUE_DATE, createdDate);
    task.setValue(Task.NOTES, remoteTask.getNotes());

    Metadata gtasksMetadata = GtasksMetadata.createEmptyMetadata(AbstractModel.NO_ID);
    gtasksMetadata.setValue(GtasksMetadata.ID, remoteTask.getId());
    gtasksMetadata.setValue(GtasksMetadata.LIST_ID, listId);

    GtasksTaskContainer container = new GtasksTaskContainer(task, metadata, gtasksMetadata);
    return container;
  }
Exemple #2
0
  /** Synchronize with server when data changes */
  public void pushTaskOnSave(Task task, ContentValues values, GtasksInvoker invoker, boolean sleep)
      throws IOException {
    if (sleep) AndroidUtilities.sleepDeep(1000L); // Wait for metadata to be saved

    Metadata gtasksMetadata = gtasksMetadataService.getTaskMetadata(task.getId());
    com.google.api.services.tasks.model.Task remoteModel = null;
    boolean newlyCreated = false;

    String remoteId = null;
    String listId = Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST);
    if (listId == null) {
      com.google.api.services.tasks.model.TaskList defaultList = invoker.getGtaskList(DEFAULT_LIST);
      if (defaultList != null) {
        listId = defaultList.getId();
        Preferences.setString(GtasksPreferenceService.PREF_DEFAULT_LIST, listId);
      } else {
        listId = DEFAULT_LIST;
      }
    }

    if (gtasksMetadata == null
        || !gtasksMetadata.containsNonNullValue(GtasksMetadata.ID)
        || TextUtils.isEmpty(gtasksMetadata.getValue(GtasksMetadata.ID))) { // Create case
      if (gtasksMetadata == null) {
        gtasksMetadata = GtasksMetadata.createEmptyMetadata(task.getId());
      }
      if (gtasksMetadata.containsNonNullValue(GtasksMetadata.LIST_ID)) {
        listId = gtasksMetadata.getValue(GtasksMetadata.LIST_ID);
      }

      remoteModel = new com.google.api.services.tasks.model.Task();
      newlyCreated = true;
    } else { // update case
      remoteId = gtasksMetadata.getValue(GtasksMetadata.ID);
      listId = gtasksMetadata.getValue(GtasksMetadata.LIST_ID);
      remoteModel = new com.google.api.services.tasks.model.Task();
      remoteModel.setId(remoteId);
    }

    // If task was newly created but without a title, don't sync--we're in the middle of
    // creating a task which may end up being cancelled
    if (newlyCreated
        && (!values.containsKey(Task.TITLE.name) || TextUtils.isEmpty(task.getValue(Task.TITLE)))) {
      return;
    }

    // Update the remote model's changed properties
    if (values.containsKey(Task.DELETION_DATE.name) && task.isDeleted()) {
      remoteModel.setDeleted(true);
    }

    if (values.containsKey(Task.TITLE.name)) {
      remoteModel.setTitle(task.getValue(Task.TITLE));
    }
    if (values.containsKey(Task.NOTES.name)) {
      remoteModel.setNotes(task.getValue(Task.NOTES));
    }
    if (values.containsKey(Task.DUE_DATE.name) && task.hasDueDate()) {
      remoteModel.setDue(GtasksApiUtilities.unixTimeToGtasksDueDate(task.getValue(Task.DUE_DATE)));
    }
    if (values.containsKey(Task.COMPLETION_DATE.name)) {
      if (task.isCompleted()) {
        remoteModel.setCompleted(
            GtasksApiUtilities.unixTimeToGtasksCompletionTime(task.getValue(Task.COMPLETION_DATE)));
        remoteModel.setStatus("completed"); // $NON-NLS-1$
      } else {
        remoteModel.setCompleted(null);
        remoteModel.setStatus("needsAction"); // $NON-NLS-1$
      }
    }

    if (!newlyCreated) {
      invoker.updateGtask(listId, remoteModel);
    } else {
      String parent = gtasksMetadataService.getRemoteParentId(gtasksMetadata);
      String priorSibling = gtasksMetadataService.getRemoteSiblingId(listId, gtasksMetadata);

      CreateRequest create = new CreateRequest(invoker, listId, remoteModel, parent, priorSibling);
      com.google.api.services.tasks.model.Task created = create.executePush();

      if (created != null) {
        // Update the metadata for the newly created task
        gtasksMetadata.setValue(GtasksMetadata.ID, created.getId());
        gtasksMetadata.setValue(GtasksMetadata.LIST_ID, listId);
      } else return;
    }

    task.setValue(Task.MODIFICATION_DATE, DateUtilities.now());
    gtasksMetadata.setValue(GtasksMetadata.LAST_SYNC, DateUtilities.now() + 1000L);
    metadataService.save(gtasksMetadata);
    task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
    taskDao.saveExistingWithSqlConstraintCheck(task);
  }
  public void checkAndMigrateLegacy() throws IOException {
    if (!gtasksPreferenceService.migrationHasOccurred()) {

      // Fetch all tasks that have associated gtask metadata
      String defaultListTitle =
          gtasksListService.getListName(
              Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST));
      String defaultListId = null;

      TodorooCursor<Task> allTasksWithGtaskData =
          taskService.query(
              Query.select(Task.PROPERTIES)
                  .where(
                      Task.ID.in(
                          Query.select(Metadata.TASK)
                              .from(Metadata.TABLE)
                              .where(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY)))));

      try {
        if (allTasksWithGtaskData.getCount() > 0) {
          // Fetch all remote tasks from all remote lists (this may be an expensive operation)
          // and map their titles to their real remote ids
          HashMap<String, String> taskAndListTitlesToRemoteTaskIds = new HashMap<String, String>();

          List<TaskList> items = allLists.getItems();
          for (TaskList list : items) {
            if (list.getTitle().equals(defaultListTitle)) {
              defaultListId = list.getId();
            }

            Tasks allTasks = gtasksService.getAllGtasksFromListId(list.getId(), false, false, 0);

            List<com.google.api.services.tasks.model.Task> tasksItems = allTasks.getItems();
            if (tasksItems != null) {
              for (com.google.api.services.tasks.model.Task t : tasksItems) {
                String key = constructKeyFromTitles(t.getTitle(), list.getTitle());
                taskAndListTitlesToRemoteTaskIds.put(key, t.getId());
              }
            }
          }

          if (defaultListId == null) {
            com.google.api.services.tasks.model.TaskList defaultList =
                gtasksService.getGtaskList("@default"); // $NON-NLS-1$
            defaultListId = defaultList.getId();
          }
          Preferences.setString(GtasksPreferenceService.PREF_DEFAULT_LIST, defaultListId);

          // For each local task, check to see if its title paired with any list title has a match
          // in the map
          for (allTasksWithGtaskData.moveToFirst();
              !allTasksWithGtaskData.isAfterLast();
              allTasksWithGtaskData.moveToNext()) {
            GtasksTaskContainer container =
                gtasksMetadataService.readTaskAndMetadata(allTasksWithGtaskData);
            // memorize the original listname for the case that the task is not matched,
            // then it should at least be recreated in the correct list
            String originalListName =
                gtasksListService.getListName(
                    container.gtaskMetadata.getValue(GtasksMetadata.LIST_ID));
            String originalListId = null;

            // Search through lists to see if one of them has match
            String taskTitle = container.task.getValue(Task.TITLE);
            boolean foundMatch = false;
            items = allLists.getItems();
            for (TaskList list : items) {
              String expectedKey = constructKeyFromTitles(taskTitle, list.getTitle());

              // save the new id of the current list
              // if it matches the listname of the current task
              if (list.getTitle() != null && list.getTitle().equals(originalListName)) {
                originalListId = list.getId();
              }

              if (taskAndListTitlesToRemoteTaskIds.containsKey(expectedKey)) {
                foundMatch = true;
                String newRemoteTaskId = taskAndListTitlesToRemoteTaskIds.get(expectedKey);
                String newRemoteListId = list.getId();

                container.gtaskMetadata.setValue(GtasksMetadata.ID, newRemoteTaskId);
                container.gtaskMetadata.setValue(GtasksMetadata.LIST_ID, newRemoteListId);
                gtasksMetadataService.saveTaskAndMetadata(container);
                break;
              }
            }

            if (!foundMatch) {
              // For non-matches, make the task look newly created
              container.gtaskMetadata = GtasksMetadata.createEmptyMetadata(container.task.getId());
              container.gtaskMetadata.setValue(GtasksMetadata.ID, ""); // $NON-NLS-1$
              if (originalListId != null) {
                // set the list-id based on the original listname, saved above during for-loop
                container.gtaskMetadata.setValue(GtasksMetadata.LIST_ID, originalListId);
              } else {
                // remote list or local list was renamed, so put this unmatched task in the default
                // list
                container.gtaskMetadata.setValue(GtasksMetadata.LIST_ID, defaultListId);
              }
              gtasksMetadataService.saveTaskAndMetadata(container);
              break;
            }
          }
        }

        // migrate the list-id's afterwards, so that we can put the non-matched tasks in their
        // original lists
        // if the listnames didnt change before migration (defaultlist otherwise)
        listService.migrateListIds(allLists);

      } finally {
        allTasksWithGtaskData.close();
      }
      Preferences.setBoolean(
          GtasksPreferenceService.PREF_MIGRATION_HAS_OCCURRED, true); // Record successful migration
    }
  }