private synchronized void pushUpdated(GtasksInvoker invoker, SyncResultCallback callback) {
   TodorooCursor<Task> queued =
       taskService.query(
           Query.select(Task.PROPERTIES)
               .join(
                   Join.left(
                       Metadata.TABLE,
                       Criterion.and(
                           MetadataCriteria.withKey(GtasksMetadata.METADATA_KEY),
                           Task.ID.eq(Metadata.TASK))))
               .where(
                   Criterion.or(
                       Task.MODIFICATION_DATE.gt(GtasksMetadata.LAST_SYNC),
                       Criterion.and(
                           Task.USER_ID.neq(Task.USER_ID_SELF), GtasksMetadata.ID.isNotNull()),
                       Metadata.KEY.isNull())));
   callback.incrementMax(queued.getCount() * 10);
   try {
     Task task = new Task();
     for (queued.moveToFirst(); !queued.isAfterLast(); queued.moveToNext()) {
       task.readFromCursor(queued);
       try {
         gtasksSyncService.pushTaskOnSave(task, task.getMergedValues(), invoker, false);
       } catch (GoogleTasksException e) {
         handler.handleException("gtasks-sync-io", e, e.getType()); // $NON-NLS-1$
       } catch (IOException e) {
         handler.handleException("gtasks-sync-io", e, e.toString()); // $NON-NLS-1$
       } finally {
         callback.incrementProgress(10);
       }
     }
   } finally {
     queued.close();
   }
 }
Example #2
0
 /**
  * Build inbox filter
  *
  * @return
  */
 public static Filter buildInboxFilter(Resources r) {
   Filter inbox =
       new Filter(
           r.getString(R.string.BFE_Active),
           r.getString(R.string.BFE_Active),
           new QueryTemplate()
               .where(
                   Criterion.and(
                       TaskCriteria.activeVisibleMine(),
                       Criterion.not(
                           Task.ID.in(
                               Query.select(Metadata.TASK)
                                   .from(Metadata.TABLE)
                                   .where(
                                       Criterion.and(
                                           MetadataCriteria.withKey(TaskToTagMetadata.KEY),
                                           TaskToTagMetadata.TAG_NAME.like(
                                               "x_%", "x"))))))), // $NON-NLS-1$ //$NON-NLS-2$
           null);
   int themeFlags = ThemeService.getFilterThemeFlags();
   inbox.listingIcon =
       ((BitmapDrawable)
               r.getDrawable(ThemeService.getDrawable(R.drawable.filter_inbox, themeFlags)))
           .getBitmap();
   return inbox;
 }
Example #3
0
  public boolean memberOfTagData(String email, String tagId, String memberId) {
    Criterion criterion;
    if (!RemoteModel.isUuidEmpty(memberId) && !TextUtils.isEmpty(email)) {
      criterion =
          Criterion.or(
              TagMemberMetadata.USER_UUID.eq(email), TagMemberMetadata.USER_UUID.eq(memberId));
    } else if (!RemoteModel.isUuidEmpty(memberId)) {
      criterion = TagMemberMetadata.USER_UUID.eq(memberId);
    } else if (!TextUtils.isEmpty(email)) {
      criterion = TagMemberMetadata.USER_UUID.eq(email);
    } else {
      return false;
    }

    TodorooCursor<TagMetadata> count =
        query(
            Query.select(TagMetadata.ID)
                .where(
                    Criterion.and(
                        TagMetadataCriteria.withKey(TagMemberMetadata.KEY),
                        TagMetadata.TAG_UUID.eq(tagId),
                        criterion)));
    try {
      return count.getCount() > 0;
    } finally {
      //
    }
  }
 public static Filter getAssignedByMeFilter(Resources r) {
   int themeFlags = ThemeService.getFilterThemeFlags();
   Filter f =
       new Filter(
           r.getString(R.string.BFE_Assigned),
           r.getString(R.string.BFE_Assigned),
           new QueryTemplate()
               .join(
                   Join.left(
                       Metadata.TABLE,
                       Criterion.and(
                           Metadata.KEY.eq(TaskRabbitMetadata.METADATA_KEY),
                           Task.ID.eq(Metadata.TASK))))
               .where(
                   Criterion.and(
                       TaskCriteria.isActive(),
                       Criterion.or(
                           Task.CREATOR_ID.eq(0),
                           Task.CREATOR_ID.eq(ActFmPreferenceService.userId())),
                       Criterion.or(Task.USER_ID.neq(0), TaskRabbitMetadata.ID.gt(0)))),
           null);
   f.listingIcon =
       ((BitmapDrawable)
               r.getDrawable(ThemeService.getDrawable(R.drawable.filter_assigned, themeFlags)))
           .getBitmap();
   return f;
 }
  private Filter filterUserAssignedByOthers(
      Context context, ProducteevUser user, long currentUserId) {
    String title = context.getString(R.string.producteev_FEx_responsible_title, user.toString());
    ContentValues values = new ContentValues();
    values.put(Metadata.KEY.name, ProducteevTask.METADATA_KEY);
    values.put(ProducteevTask.ID.name, 0);
    values.put(ProducteevTask.CREATOR_ID.name, 0);
    values.put(ProducteevTask.RESPONSIBLE_ID.name, user.getId());
    Filter filter =
        new Filter(
            user.toString(),
            title,
            new QueryTemplate()
                .join(ProducteevDataService.METADATA_JOIN)
                .where(
                    Criterion.and(
                        MetadataCriteria.withKey(ProducteevTask.METADATA_KEY),
                        TaskCriteria.isActive(),
                        TaskCriteria.isVisible(),
                        Criterion.not(ProducteevTask.CREATOR_ID.eq(currentUserId)),
                        ProducteevTask.RESPONSIBLE_ID.eq(user.getId()))),
            values);

    return filter;
  }
  private synchronized void synchronizeListHelper(
      StoreObject list,
      GtasksInvoker invoker,
      boolean manual,
      SyncExceptionHandler errorHandler,
      SyncResultCallback callback) {
    String listId = list.getValue(GtasksList.REMOTE_ID);
    long lastSyncDate;
    if (!manual && list.containsNonNullValue(GtasksList.LAST_SYNC)) {
      lastSyncDate = list.getValue(GtasksList.LAST_SYNC);
    } else {
      lastSyncDate = 0;
    }
    boolean includeDeletedAndHidden = lastSyncDate != 0;
    try {
      Tasks taskList =
          invoker.getAllGtasksFromListId(
              listId, includeDeletedAndHidden, includeDeletedAndHidden, lastSyncDate);
      List<com.google.api.services.tasks.model.Task> tasks = taskList.getItems();
      if (tasks != null) {
        callback.incrementMax(tasks.size() * 10);
        HashSet<Long> localIds = new HashSet<Long>(tasks.size());
        for (com.google.api.services.tasks.model.Task t : tasks) {
          GtasksTaskContainer container = parseRemoteTask(t, listId);
          gtasksMetadataService.findLocalMatch(container);
          container.gtaskMetadata.setValue(
              GtasksMetadata.GTASKS_ORDER, Long.parseLong(t.getPosition()));
          container.gtaskMetadata.setValue(
              GtasksMetadata.PARENT_TASK, gtasksMetadataService.localIdForGtasksId(t.getParent()));
          container.gtaskMetadata.setValue(GtasksMetadata.LAST_SYNC, DateUtilities.now() + 1000L);
          write(container);
          localIds.add(container.task.getId());
          callback.incrementProgress(10);
        }
        list.setValue(GtasksList.LAST_SYNC, DateUtilities.now());
        storeObjectDao.persist(list);

        if (lastSyncDate == 0) {
          Long[] localIdArray = localIds.toArray(new Long[localIds.size()]);
          Criterion delete =
              Criterion.and(
                  Metadata.KEY.eq(GtasksMetadata.METADATA_KEY),
                  GtasksMetadata.LIST_ID.eq(listId),
                  Criterion.not(Metadata.TASK.in(localIdArray)));
          taskService.deleteWhere(
              Task.ID.in(Query.select(Metadata.TASK).from(Metadata.TABLE).where(delete)));
          metadataService.deleteWhere(delete);
        }

        gtasksTaskListUpdater.correctOrderAndIndentForList(listId);
      }
    } catch (GoogleTasksException e) {
      if (errorHandler != null)
        errorHandler.handleException("gtasks-sync-io", e, e.getType()); // $NON-NLS-1$
    } catch (IOException e) {
      if (errorHandler != null)
        errorHandler.handleException("gtasks-sync-io", e, e.toString()); // $NON-NLS-1$
    }
  }
  @SuppressWarnings("nls")
  private TodorooCursor<Task> constructCursor() {
    String tagName = null;
    if (getActiveTagData() != null) tagName = getActiveTagData().getValue(TagData.NAME);

    String[] emergentTags = TagService.getInstance().getEmergentTags();
    StringProperty tagProperty =
        new StringProperty(null, TAGS_METADATA_JOIN + "." + TagService.TAG.name);

    Criterion tagsJoinCriterion =
        Criterion.and(
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name)
                .eq(TagService.KEY), // $NON-NLS-1$
            Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name)),
            Criterion.not(tagProperty.in(emergentTags)));
    if (tagName != null)
      tagsJoinCriterion =
          Criterion.and(
              tagsJoinCriterion,
              Field.field(TAGS_METADATA_JOIN + "." + TagService.TAG.name).neq(tagName));

    // TODO: For now, we'll modify the query to join and include the task rabbit and tag data here.
    // Eventually, we might consider restructuring things so that this query is constructed
    // elsewhere.
    String joinedQuery =
        Join.left(
                    Metadata.TABLE.as(TR_METADATA_JOIN),
                    Criterion.and(
                        Field.field(TR_METADATA_JOIN + "." + Metadata.KEY.name)
                            .eq(TaskRabbitMetadata.METADATA_KEY), // $NON-NLS-1$
                        Task.ID.eq(Field.field(TR_METADATA_JOIN + "." + Metadata.TASK.name))))
                .toString() //$NON-NLS-1$
            + Join.left(Metadata.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion)
                .toString() //$NON-NLS-1$
            + filter.getSqlQuery();

    sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort));

    String groupedQuery;
    if (sqlQueryTemplate.get().contains("GROUP BY")) groupedQuery = sqlQueryTemplate.get();
    else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$
    groupedQuery =
          sqlQueryTemplate
              .get()
              .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$
    else groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID;
    sqlQueryTemplate.set(groupedQuery);

    // Peform query
    try {
      return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    } catch (SQLiteException e) {
      // We don't show this error anymore--seems like this can get triggered
      // by a strange bug, but there seems to not be any negative side effect.
      // For now, we'll suppress the error
      // See http://astrid.com/home#tags-7tsoi/task-1119pk
      return null;
    }
  }
Example #8
0
  private TodorooCursor<Task> constructCursor() {
    String tagName = null;
    if (getActiveTagData() != null) {
      tagName = getActiveTagData().getName();
    }

    Criterion tagsJoinCriterion =
        Criterion.and(
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name)
                .eq(TaskToTagMetadata.KEY), // $NON-NLS-1$
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.DELETION_DATE.name).eq(0),
            Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name)));
    if (tagName != null) {
      tagsJoinCriterion =
          Criterion.and(
              tagsJoinCriterion,
              Field.field(TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name).neq(tagName));
    }

    // TODO: For now, we'll modify the query to join and include the things like tag data here.
    // Eventually, we might consider restructuring things so that this query is constructed
    // elsewhere.
    String joinedQuery =
        Join.left(Metadata.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion)
                .toString() //$NON-NLS-1$
            + Join.left(
                TaskAttachment.TABLE.as(FILE_METADATA_JOIN),
                Task.UUID.eq(Field.field(FILE_METADATA_JOIN + "." + TaskAttachment.TASK_UUID.name)))
            + filter.getSqlQuery();

    sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort));

    String groupedQuery;
    if (sqlQueryTemplate.get().contains("GROUP BY")) {
      groupedQuery = sqlQueryTemplate.get();
    } else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$
    {
      groupedQuery =
          sqlQueryTemplate
              .get()
              .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$
    } else {
      groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID;
    }
    sqlQueryTemplate.set(groupedQuery);

    // Peform query
    try {
      return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    } catch (SQLiteException e) {
      // We don't show this error anymore--seems like this can get triggered
      // by a strange bug, but there seems to not be any negative side effect.
      // For now, we'll suppress the error
      // See http://astrid.com/home#tags-7tsoi/task-1119pk
      log.error(e.getMessage(), e);
      return null;
    }
  }
Example #9
0
 /**
  * Gets a listing of all tasks that are active &
  *
  * @param properties
  * @return todoroo cursor. PLEASE CLOSE THIS CURSOR!
  */
 private TodorooCursor<Task> getTasksWithReminders(Property<?>... properties) {
   return taskDao.query(
       Query.select(properties)
           .where(
               Criterion.and(
                   TaskCriteria.isActive(),
                   TaskCriteria.ownedByMe(),
                   Criterion.or(Task.REMINDER_FLAGS.gt(0), Task.REMINDER_PERIOD.gt(0)))));
 }
  private void addTags(ArrayList<FilterListItem> list) {
    HashSet<String> tagNames = new HashSet<String>();

    // active tags
    Tag[] myTags =
        tagService.getGroupedTags(
            TagService.GROUPED_TAGS_BY_SIZE,
            Criterion.and(TaskCriteria.ownedByMe(), TaskCriteria.activeAndVisible()));
    for (Tag tag : myTags) tagNames.add(tag.tag);
    if (myTags.length > 0) list.add(filterFromTags(myTags, R.string.tag_FEx_category_mine));

    // find all tag data not in active tag list
    TodorooCursor<TagData> cursor =
        tagDataService.query(
            Query.select(TagData.NAME, TagData.TASK_COUNT, TagData.REMOTE_ID)
                .where(TagData.DELETION_DATE.eq(0)));
    ArrayList<Tag> notListed = new ArrayList<Tag>();
    try {
      ArrayList<Tag> sharedTags = new ArrayList<Tag>();
      for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        String tagName = cursor.get(TagData.NAME);
        if (tagNames.contains(tagName)) continue;
        Tag tag = new Tag(tagName, cursor.get(TagData.TASK_COUNT), cursor.get(TagData.REMOTE_ID));
        if (tag.count > 0) sharedTags.add(tag);
        else notListed.add(tag);
        tagNames.add(tagName);
      }
      if (sharedTags.size() > 0)
        list.add(
            filterFromTags(
                sharedTags.toArray(new Tag[sharedTags.size()]), R.string.tag_FEx_category_shared));
    } finally {
      cursor.close();
    }

    // find inactive tags, intersect tag list
    Tag[] inactiveTags =
        tagService.getGroupedTags(
            TagService.GROUPED_TAGS_BY_ALPHA,
            Criterion.and(
                TaskCriteria.notDeleted(), Criterion.not(TaskCriteria.activeAndVisible())));
    for (Tag tag : inactiveTags) {
      if (!tagNames.contains(tag.tag) && !TextUtils.isEmpty(tag.tag)) {
        notListed.add(tag);
        tag.count = 0;
      }
    }
    if (notListed.size() > 0)
      list.add(
          filterFromTags(
              notListed.toArray(new Tag[notListed.size()]), R.string.tag_FEx_category_inactive));
  }
Example #11
0
 public void tagDataOrderedByName(Callback<TagData> callback) {
   query(
       callback,
       Query.select(TagData.PROPERTIES)
           .where(Criterion.and(TagData.DELETION_DATE.eq(0), TagData.NAME.isNotNull()))
           .orderBy(Order.asc(Functions.upper(TagData.NAME))));
 }
Example #12
0
 public void createMemberLink(
     long tagId,
     String tagUuid,
     String memberId,
     boolean removedMember,
     boolean suppressOutstanding) {
   TagMetadata newMetadata = TagMemberMetadata.newMemberMetadata(tagId, tagUuid, memberId);
   if (removedMember) {
     newMetadata.setValue(TagMetadata.DELETION_DATE, DateUtilities.now());
   }
   if (suppressOutstanding) {
     newMetadata.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
   }
   if (update(
           Criterion.and(
               TagMetadataCriteria.byTagAndWithKey(tagUuid, TagMemberMetadata.KEY),
               TagMemberMetadata.USER_UUID.eq(memberId)),
           newMetadata)
       <= 0) {
     if (suppressOutstanding) {
       newMetadata.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
     }
     createNew(newMetadata);
   }
 }
Example #13
0
 public void removeMemberLinks(
     long tagId, String tagUuid, String[] memberIds, boolean suppressOutstanding) {
   TagMetadata deleteTemplate = new TagMetadata();
   deleteTemplate.setValue(
       TagMetadata.TAG_ID, tagId); // Need this for recording changes in outstanding table
   deleteTemplate.setValue(TagMetadata.DELETION_DATE, DateUtilities.now());
   if (memberIds != null) {
     for (String uuid : memberIds) {
       // TODO: Right now this is in a loop because each deleteTemplate needs the individual
       // tagUuid in order to record
       // the outstanding entry correctly. If possible, this should be improved to a single query
       deleteTemplate.setValue(
           TagMemberMetadata.USER_UUID,
           uuid); // Need this for recording changes in outstanding table
       if (suppressOutstanding) {
         deleteTemplate.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
       }
       update(
           Criterion.and(
               TagMetadataCriteria.withKey(TagMemberMetadata.KEY),
               TagMetadata.DELETION_DATE.eq(0),
               TagMetadata.TAG_UUID.eq(tagUuid),
               TagMemberMetadata.USER_UUID.eq(uuid)),
           deleteTemplate);
     }
   }
 }
Example #14
0
 public TaskListMetadata fetchByTagId(String tagUuid, Property<?>... properties) {
   return getFirst(
       Query.select(properties)
           .where(
               Criterion.or(
                   TaskListMetadata.TAG_UUID.eq(tagUuid), TaskListMetadata.FILTER.eq(tagUuid))));
 }
  /** @param context */
  public static Filter filterFromList(
      Context context, ProducteevDashboard dashboard, long currentUserId) {
    String dashboardTitle = dashboard.getName();
    String title = dashboard.getName();
    ContentValues values = new ContentValues();
    values.put(Metadata.KEY.name, ProducteevTask.METADATA_KEY);
    values.put(ProducteevTask.DASHBOARD_ID.name, dashboard.getId());
    values.put(ProducteevTask.ID.name, 0);
    values.put(ProducteevTask.CREATOR_ID.name, 0);
    values.put(ProducteevTask.RESPONSIBLE_ID.name, 0);
    Filter filter;
    if (currentUserId != -1)
      filter =
          new Filter(
              dashboardTitle,
              title,
              new QueryTemplate()
                  .join(ProducteevDataService.METADATA_JOIN)
                  .where(
                      Criterion.and(
                          MetadataCriteria.withKey(ProducteevTask.METADATA_KEY),
                          TaskCriteria.isActive(),
                          TaskCriteria.isVisible(),
                          Criterion.or(
                              ProducteevTask.CREATOR_ID.eq(currentUserId),
                              ProducteevTask.RESPONSIBLE_ID.eq(currentUserId)),
                          ProducteevTask.DASHBOARD_ID.eq(dashboard.getId()))),
              values);
    else
      filter =
          new Filter(
              dashboardTitle,
              title,
              new QueryTemplate()
                  .join(ProducteevDataService.METADATA_JOIN)
                  .where(
                      Criterion.and(
                          MetadataCriteria.withKey(ProducteevTask.METADATA_KEY),
                          TaskCriteria.isActive(),
                          TaskCriteria.isVisible(),
                          ProducteevTask.DASHBOARD_ID.eq(dashboard.getId()))),
              values);

    return filter;
  }
Example #16
0
  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    synchronized (this) {
      if (dataLoaded) return;
      dataLoaded = true;
    }

    String tag = getIntent().getStringExtra(EXTRA_TAG_NAME);
    long remoteId = getIntent().getLongExtra(EXTRA_TAG_REMOTE_ID, 0);

    if (tag == null && remoteId == 0) return;

    TodorooCursor<TagData> cursor =
        tagDataService.query(
            Query.select(TagData.PROPERTIES)
                .where(
                    Criterion.or(
                        TagData.NAME.eq(tag),
                        Criterion.and(TagData.REMOTE_ID.gt(0), TagData.REMOTE_ID.eq(remoteId)))));
    try {
      tagData = new TagData();
      if (cursor.getCount() == 0) {
        tagData.setValue(TagData.NAME, tag);
        tagData.setValue(TagData.REMOTE_ID, remoteId);
        tagDataService.save(tagData);
      } else {
        cursor.moveToFirst();
        tagData.readFromCursor(cursor);
      }
    } finally {
      cursor.close();
    }

    String fetchKey = LAST_FETCH_KEY + tagData.getId();
    long lastFetchDate = Preferences.getLong(fetchKey, 0);
    if (DateUtilities.now() > lastFetchDate + 300000L) {
      refreshData(false, false);
      Preferences.setLong(fetchKey, DateUtilities.now());
    }

    setUpUpdateList();
    setUpMemberPage();
  }
Example #17
0
 /**
  * Gets a listing of all alarms that are active
  *
  * @param properties
  * @return todoroo cursor. PLEASE CLOSE THIS CURSOR!
  */
 private TodorooCursor<Metadata> getActiveAlarms() {
   return PluginServices.getMetadataService()
       .query(
           Query.select(AlarmFields.TIME)
               .join(Join.inner(Task.TABLE, Metadata.TASK.eq(Task.ID)))
               .where(
                   Criterion.and(
                       TaskCriteria.isActive(),
                       MetadataCriteria.withKey(AlarmFields.METADATA_KEY))));
 }
Example #18
0
 private void titleMatchWithActFm(Task task) {
   String title = task.getValue(Task.TITLE);
   TodorooCursor<Task> match =
       taskService.query(
           Query.select(Task.ID)
               .join(
                   Join.left(
                       Metadata.TABLE,
                       Criterion.and(
                           Metadata.KEY.eq(GtasksMetadata.METADATA_KEY),
                           Metadata.TASK.eq(Task.ID))))
               .where(Criterion.and(Task.TITLE.eq(title), GtasksMetadata.ID.isNull())));
   try {
     if (match.getCount() > 0) {
       match.moveToFirst();
       task.setId(match.get(Task.ID));
     }
   } finally {
     match.close();
   }
 }
Example #19
0
 public boolean tagHasMembers(String uuid) {
   TodorooCursor<TagMetadata> metadata =
       query(
           Query.select(TagMetadata.ID)
               .where(
                   Criterion.and(
                       TagMetadataCriteria.byTagAndWithKey(uuid, TagMemberMetadata.KEY),
                       TagMetadata.DELETION_DATE.eq(0))));
   try {
     return metadata.getCount() > 0;
   } finally {
     metadata.close();
   }
 }
Example #20
0
  /**
   * Cursor with the following columns
   *
   * <ol>
   *   <li>task title, string
   *   <li>task importance color, int android RGB color
   *   <li>task due date (was: preferred due date), long millis since epoch
   *   <li>task due date (was: absolute due date), long millis since epoch
   *   <li>task importance, integer from 0 to 3 (0 => most important)
   *   <li>task id, long
   *   <li>task tags, string tags separated by |
   * </ol>
   *
   * @return cursor as described above
   */
  public Cursor getTasks() {

    MatrixCursor ret = new MatrixCursor(TASK_FIELD_LIST);

    TodorooCursor<Task> cursor =
        taskService.query(
            Query.select(Task.ID, Task.TITLE, Task.IMPORTANCE, Task.DUE_DATE)
                .where(Criterion.and(TaskCriteria.isActive(), TaskCriteria.isVisible()))
                .orderBy(SortHelper.defaultTaskOrder())
                .limit(MAX_NUMBER_OF_TASKS));
    try {
      int[] importanceColors = Task.getImportanceColors(ctx.getResources());
      Task task = new Task();
      for (int i = 0; i < cursor.getCount(); i++) {
        cursor.moveToNext();
        task.readFromCursor(cursor);

        StringBuilder taskTags = new StringBuilder();
        TodorooCursor<Metadata> tagCursor = TagService.getInstance().getTags(task.getId());
        try {
          for (tagCursor.moveToFirst(); !tagCursor.isAfterLast(); tagCursor.moveToNext())
            taskTags.append(tagCursor.get(TagService.TAG)).append(TAG_SEPARATOR);
        } finally {
          tagCursor.close();
        }

        Object[] values = new Object[7];
        values[0] = task.getValue(Task.TITLE);
        values[1] = importanceColors[task.getValue(Task.IMPORTANCE)];
        values[2] = task.getValue(Task.DUE_DATE);
        values[3] = task.getValue(Task.DUE_DATE);
        values[4] = task.getValue(Task.IMPORTANCE);
        values[5] = task.getId();
        values[6] = taskTags.toString();

        ret.addRow(values);
      }
    } finally {
      cursor.close();
    }

    return ret;
  }
Example #21
0
  /**
   * Synchronize metadata for given task id. Deletes rows in database that are not identical to
   * those in the metadata list, creates rows that have no match.
   *
   * @param taskId id of task to perform synchronization on
   * @param metadata list of new metadata items to save
   * @param metadataCriteria criteria to load data for comparison from metadata
   */
  public void synchronizeMetadata(
      long taskId, ArrayList<Metadata> metadata, Criterion metadataCriteria) {
    HashSet<ContentValues> newMetadataValues = new HashSet<ContentValues>();
    for (Metadata metadatum : metadata) {
      metadatum.setValue(Metadata.TASK, taskId);
      metadatum.clearValue(Metadata.ID);
      newMetadataValues.add(metadatum.getMergedValues());
    }

    Metadata item = new Metadata();
    TodorooCursor<Metadata> cursor =
        query(
            Query.select(Metadata.PROPERTIES)
                .where(Criterion.and(MetadataCriteria.byTask(taskId), metadataCriteria)));
    try {
      // try to find matches within our metadata list
      for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        item.readFromCursor(cursor);
        long id = item.getId();

        // clear item id when matching with incoming values
        item.clearValue(Metadata.ID);
        ContentValues itemMergedValues = item.getMergedValues();
        if (newMetadataValues.contains(itemMergedValues)) {
          newMetadataValues.remove(itemMergedValues);
          continue;
        }

        // not matched. cut it
        delete(id);
      }
    } finally {
      cursor.close();
    }

    // everything that remains shall be written
    for (ContentValues values : newMetadataValues) {
      item.clear();
      item.mergeWith(values);
      persist(item);
    }
  }
Example #22
0
  public void removeMemberLink(
      long tagId, String tagUuid, String memberId, boolean suppressOutstanding) {
    TagMetadata deleteTemplate = new TagMetadata();
    deleteTemplate.setValue(
        TagMetadata.TAG_ID, tagId); // Need this for recording changes in outstanding table
    deleteTemplate.setValue(TagMetadata.DELETION_DATE, DateUtilities.now());
    deleteTemplate.setValue(
        TagMemberMetadata.USER_UUID,
        memberId); // Need this for recording changes in outstanding table

    if (suppressOutstanding) {
      deleteTemplate.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
    }
    update(
        Criterion.and(
            TagMetadataCriteria.withKey(TagMemberMetadata.KEY),
            TagMetadata.DELETION_DATE.eq(0),
            TagMetadata.TAG_UUID.eq(tagUuid),
            TagMemberMetadata.USER_UUID.eq(memberId)),
        deleteTemplate);
  }
 public static Filter getTodayFilter(Resources r) {
   int themeFlags = ThemeService.getFilterThemeFlags();
   String todayTitle = AndroidUtilities.capitalize(r.getString(R.string.today));
   ContentValues todayValues = new ContentValues();
   todayValues.put(Task.DUE_DATE.name, PermaSql.VALUE_NOON);
   Filter todayFilter =
       new Filter(
           todayTitle,
           todayTitle,
           new QueryTemplate()
               .where(
                   Criterion.and(
                       TaskCriteria.activeVisibleMine(),
                       Task.DUE_DATE.gt(0),
                       Task.DUE_DATE.lte(PermaSql.VALUE_EOD))),
           todayValues);
   todayFilter.listingIcon =
       ((BitmapDrawable)
               r.getDrawable(ThemeService.getDrawable(R.drawable.filter_calendar, themeFlags)))
           .getBitmap();
   return todayFilter;
 }
Example #24
0
  /**
   * Fill in the Task List with current items
   *
   * @param withCustomId force task with given custom id to be part of list
   */
  protected void setUpTaskList() {
    if (filter == null) return;

    // TODO: For now, we'll modify the query to join and include the task rabbit data here.
    // Eventually, we might consider restructuring things so that this query is constructed
    // elsewhere.
    String joinedTaskRabbitQuery =
        Join.left(
                Metadata.TABLE.as(TR_METADATA_JOIN),
                Criterion.and(
                    Field.field(TR_METADATA_JOIN + "." + Metadata.KEY.name)
                        .eq(TaskRabbitMetadata.METADATA_KEY), // $NON-NLS-1$
                    Task.ID.eq(
                        Field.field(TR_METADATA_JOIN) + "." + Metadata.TASK.name))) // $NON-NLS-1$
            + filter.getSqlQuery();

    sqlQueryTemplate.set(
        SortHelper.adjustQueryForFlagsAndSort(joinedTaskRabbitQuery, sortFlags, sortSort));

    // perform query
    TodorooCursor<Task> currentCursor;
    try {
      currentCursor = taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    } catch (SQLiteException e) {
      StartupService.handleSQLiteColumnMissing(getActivity(), e);
      return;
    }

    // set up list adapters
    taskAdapter = createTaskAdapter(currentCursor);

    setListAdapter(taskAdapter);
    getListView().setOnScrollListener(this);
    registerForContextMenu(getListView());

    loadTaskListContent(true);
  }
Example #25
0
 public void refreshMetadata() {
   if (model != null) {
     TodorooCursor<Metadata> cursor =
         metadataService.query(
             Query.select(Metadata.PROPERTIES)
                 .where(
                     Criterion.and(
                         MetadataCriteria.byTaskAndwithKey(
                             model.getId(), FileMetadata.METADATA_KEY),
                         FileMetadata.DELETION_DATE.eq(0))));
     try {
       files.clear();
       for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
         Metadata metadata = new Metadata();
         metadata.readFromCursor(cursor);
         files.add(metadata);
       }
     } finally {
       cursor.close();
     }
     validateFiles();
     if (initialized) afterInflate();
   }
 }
Example #26
0
 /** Returns all metadata associated with a given key */
 public static Criterion byTaskAndwithKey(long taskId, String key) {
   return Criterion.and(withKey(key), byTask(taskId));
 }
Example #27
0
 /**
  * Update all matching a clause to have the values set on template object.
  *
  * <p>Example (updates "joe" => "bob" in metadata value1): {code} Metadata item = new Metadata();
  * item.setValue(Metadata.VALUE1, "bob"); update(item, Metadata.VALUE1.eq("joe")); {code}
  *
  * @param where sql criteria
  * @param template set fields on this object in order to set them in the db.
  * @return # of updated items
  */
 public int update(Criterion where, TYPE template) {
   return database.update(table.name, template.getSetValues(), where.toString(), null);
 }
Example #28
0
 /** Returns all metadata associated with a given key */
 public static Criterion byTagAndWithKey(String tagUuid, String key) {
   return Criterion.and(withKey(key), byTag(tagUuid));
 }
Example #29
0
 /**
  * Updates multiple rows of the database based on model set values
  *
  * @param item item model
  * @param criterion
  * @return returns true on success.
  */
 public int updateMultiple(ContentValues values, Criterion criterion) {
   if (values.size() == 0) // nothing changed
   return 0;
   return database.update(table.name, values, criterion.toString(), null);
 }
Example #30
0
  /** Fixes task filter missing tasks bug, migrate PDV/RTM notes */
  @SuppressWarnings("nls")
  private void upgrade3To3_7() {
    TodorooCursor<Task> t =
        taskService.query(Query.select(Task.ID, Task.DUE_DATE).where(Task.DUE_DATE.gt(0)));
    Task task = new Task();
    for (t.moveToFirst(); !t.isAfterLast(); t.moveToNext()) {
      task.readFromCursor(t);
      if (task.hasDueDate()) {
        task.setValue(Task.DUE_DATE, task.getValue(Task.DUE_DATE) / 1000L * 1000L);
        taskService.save(task);
      }
    }
    t.close();

    TodorooCursor<Metadata> m =
        metadataService.query(
            Query.select(Metadata.PROPERTIES)
                .where(
                    Criterion.or(
                        Metadata.KEY.eq("producteev-note"), Metadata.KEY.eq("rmilk-note"))));

    StringProperty PDV_NOTE_ID = Metadata.VALUE1;
    StringProperty PDV_NOTE_MESSAGE = Metadata.VALUE2;
    LongProperty PDV_NOTE_CREATED = new LongProperty(Metadata.TABLE, Metadata.VALUE3.name);

    StringProperty RTM_NOTE_ID = Metadata.VALUE1;
    StringProperty RTM_NOTE_TITLE = Metadata.VALUE2;
    StringProperty RTM_NOTE_TEXT = Metadata.VALUE3;
    LongProperty RTM_NOTE_CREATED = new LongProperty(Metadata.TABLE, Metadata.VALUE4.name);

    Metadata metadata = new Metadata();
    for (m.moveToFirst(); !m.isAfterLast(); m.moveToNext()) {
      metadata.readFromCursor(m);

      String id, body, title, provider;
      long created;
      if ("rmilk-note".equals(metadata.getValue(Metadata.KEY))) {
        id = metadata.getValue(RTM_NOTE_ID);
        body = metadata.getValue(RTM_NOTE_TEXT);
        title = metadata.getValue(RTM_NOTE_TITLE);
        created = metadata.getValue(RTM_NOTE_CREATED);
        provider = MilkNoteHelper.PROVIDER;
      } else {
        id = metadata.getValue(PDV_NOTE_ID);
        body = metadata.getValue(PDV_NOTE_MESSAGE);
        created = metadata.getValue(PDV_NOTE_CREATED);
        title =
            DateUtilities.getDateStringWithWeekday(ContextManager.getContext(), new Date(created));
        provider = ProducteevDataService.NOTE_PROVIDER;
      }

      metadata.setValue(Metadata.KEY, NoteMetadata.METADATA_KEY);
      metadata.setValue(Metadata.CREATION_DATE, created);
      metadata.setValue(NoteMetadata.BODY, body);
      metadata.setValue(NoteMetadata.TITLE, title);
      metadata.setValue(NoteMetadata.THUMBNAIL, null);
      metadata.setValue(NoteMetadata.EXT_PROVIDER, provider);
      metadata.setValue(NoteMetadata.EXT_ID, id);

      metadata.clearValue(Metadata.ID);
      metadataService.save(metadata);
    }
    m.close();
  }