Ejemplo n.º 1
0
  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;
  }
Ejemplo n.º 2
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)))));
 }
Ejemplo n.º 3
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));
  }
Ejemplo n.º 4
0
 private FilterCategory filterFromTags(Tag[] tags, int name) {
   Filter[] filters = new Filter[tags.length];
   Context context = ContextManager.getContext();
   for (int i = 0; i < tags.length; i++)
     filters[i] = filterFromTag(context, tags[i], TaskCriteria.activeAndVisible());
   return new FilterCategory(context.getString(name), filters);
 }
Ejemplo n.º 5
0
 /** Create a filter from tag data object */
 public static Filter filterFromTagData(Context context, TagData tagData) {
   Tag tag =
       new Tag(
           tagData.getValue(TagData.NAME),
           tagData.getValue(TagData.TASK_COUNT),
           tagData.getValue(TagData.REMOTE_ID));
   return filterFromTag(context, tag, TaskCriteria.activeAndVisible());
 }
Ejemplo n.º 6
0
  private Filter[] buildSavedFilters(Context context, Resources r) {
    int themeFlags = ThemeService.getFilterThemeFlags();

    StoreObjectDao dao = PluginServices.getStoreObjectDao();
    TodorooCursor<StoreObject> cursor =
        dao.query(
            Query.select(StoreObject.PROPERTIES)
                .where(StoreObject.TYPE.eq(SavedFilter.TYPE))
                .orderBy(Order.asc(SavedFilter.NAME)));
    try {
      ArrayList<Filter> list = new ArrayList<>();

      // stock filters
      if (Preferences.getBoolean(R.string.p_show_recently_modified_filter, true)) {
        Filter recent =
            new Filter(
                r.getString(R.string.BFE_Recent),
                r.getString(R.string.BFE_Recent),
                new QueryTemplate()
                    .where(TaskCriteria.ownedByMe())
                    .orderBy(Order.desc(Task.MODIFICATION_DATE))
                    .limit(15),
                null);
        recent.listingIcon =
            ((BitmapDrawable)
                    r.getDrawable(ThemeService.getDrawable(R.drawable.filter_pencil, themeFlags)))
                .getBitmap();

        list.add(recent);
      }

      if (cursor != null) {
        StoreObject savedFilter = new StoreObject();
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
          savedFilter.readFromCursor(cursor);
          Filter f = SavedFilter.load(savedFilter);

          Intent deleteIntent = new Intent(context, DeleteActivity.class);
          deleteIntent.putExtra(TOKEN_FILTER_ID, savedFilter.getId());
          deleteIntent.putExtra(TOKEN_FILTER_NAME, f.title);
          f.contextMenuLabels = new String[] {context.getString(R.string.BFE_Saved_delete)};
          f.contextMenuIntents = new Intent[] {deleteIntent};
          f.listingIcon =
              ((BitmapDrawable)
                      r.getDrawable(
                          ThemeService.getDrawable(R.drawable.filter_sliders, themeFlags)))
                  .getBitmap();
          list.add(f);
        }
      }

      return list.toArray(new Filter[list.size()]);
    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
  }
Ejemplo n.º 7
0
  /** @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;
  }
Ejemplo n.º 8
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))));
 }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
0
  /** Recalculate all sizes */
  void updateList() {
    int max = 0, last = -1;

    StringBuilder sql =
        new StringBuilder(Query.select(new CountProperty()).from(Task.TABLE).toString())
            .append(" WHERE ");

    for (int i = 0; i < adapter.getCount(); i++) {
      CriterionInstance instance = adapter.getItem(i);
      String value = instance.getValueFromCriterion();
      if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) {
        value = "";
      }

      switch (instance.type) {
        case CriterionInstance.TYPE_ADD:
          sql.append("OR ");
          break;
        case CriterionInstance.TYPE_SUBTRACT:
          sql.append("AND NOT ");
          break;
        case CriterionInstance.TYPE_INTERSECT:
          sql.append("AND ");
          break;
        case CriterionInstance.TYPE_UNIVERSE:
      }

      // special code for all tasks universe
      if (instance.criterion.sql == null) {
        sql.append(TaskCriteria.activeAndVisible()).append(' ');
      } else {
        String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value));
        subSql = PermaSql.replacePlaceholders(subSql);
        sql.append(Task.ID).append(" IN (").append(subSql).append(") ");
      }

      Cursor cursor = database.rawQuery(sql.toString());
      try {
        cursor.moveToNext();
        instance.start = last == -1 ? cursor.getInt(0) : last;
        instance.end = cursor.getInt(0);
        last = instance.end;
        max = Math.max(max, last);
      } finally {
        cursor.close();
      }
    }

    for (int i = 0; i < adapter.getCount(); i++) {
      CriterionInstance instance = adapter.getItem(i);
      instance.max = max;
    }

    adapter.notifyDataSetInvalidated();
  }
Ejemplo n.º 11
0
  void saveAndView() {
    String title = filterName.getText().toString().trim();

    if (isEmpty(title)) {
      return;
    }

    StringBuilder sql = new StringBuilder(" WHERE ");
    ContentValues values = new ContentValues();
    for (int i = 0; i < adapter.getCount(); i++) {
      CriterionInstance instance = adapter.getItem(i);
      String value = instance.getValueFromCriterion();
      if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) {
        value = "";
      }

      switch (instance.type) {
        case CriterionInstance.TYPE_ADD:
          sql.append("OR ");
          break;
        case CriterionInstance.TYPE_SUBTRACT:
          sql.append("AND NOT ");
          break;
        case CriterionInstance.TYPE_INTERSECT:
          sql.append("AND ");
          break;
        case CriterionInstance.TYPE_UNIVERSE:
      }

      // special code for all tasks universe
      if (instance.criterion.sql == null) {
        sql.append(TaskCriteria.activeAndVisible()).append(' ');
      } else {
        String subSql = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value));
        sql.append(Task.ID).append(" IN (").append(subSql).append(") ");
      }

      if (instance.criterion.valuesForNewTasks != null
          && instance.type == CriterionInstance.TYPE_INTERSECT) {
        for (Entry<String, Object> entry : instance.criterion.valuesForNewTasks.valueSet()) {
          values.put(
              entry.getKey().replace("?", value), entry.getValue().toString().replace("?", value));
        }
      }
    }

    StoreObject storeObject =
        SavedFilter.persist(storeObjectDao, adapter, title, sql.toString(), values);
    Filter filter = new CustomFilter(title, sql.toString(), values, storeObject.getId());
    setResult(RESULT_OK, new Intent().putExtra(TagSettingsActivity.TOKEN_NEW_FILTER, filter));
    finish();
  }
Ejemplo n.º 12
0
  /**
   * Select a custom task id in the list. If it doesn't exist, create a new custom filter
   *
   * @param withCustomId
   */
  @SuppressWarnings("nls")
  public void selectCustomId(long withCustomId) {
    // if already in the list, select it
    TodorooCursor<Task> currentCursor = (TodorooCursor<Task>) taskAdapter.getCursor();
    for (int i = 0; i < currentCursor.getCount(); i++) {
      currentCursor.moveToPosition(i);
      if (currentCursor.get(Task.ID) == withCustomId) {
        getListView().setSelection(i);
        return;
      }
    }

    // create a custom cursor
    if (!sqlQueryTemplate.get().contains("WHERE"))
      sqlQueryTemplate.set(sqlQueryTemplate.get() + " WHERE " + TaskCriteria.byId(withCustomId));
    else
      sqlQueryTemplate.set(
          sqlQueryTemplate
              .get()
              .replace("WHERE ", "WHERE " + TaskCriteria.byId(withCustomId) + " OR "));

    currentCursor = taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    getListView().setFilterText("");

    taskAdapter.changeCursor(currentCursor);

    // update title
    if (getActivity() instanceof TaskListActivity)
      ((TaskListActivity) getActivity()).setListsTitle(getString(R.string.TLA_custom));

    // try selecting again
    for (int i = 0; i < currentCursor.getCount(); i++) {
      currentCursor.moveToPosition(i);
      if (currentCursor.get(Task.ID) == withCustomId) {
        getListView().setSelection(i);
        break;
      }
    }
  }
Ejemplo n.º 13
0
  @Override
  public void applyToFilter(Filter filter) {
    String query = filter.getSqlQuery();

    query = query.replaceAll("ORDER BY .*", "");
    query =
        query
            + String.format(
                " ORDER BY %s, %s, %s, %s",
                Task.DELETION_DATE, Task.COMPLETION_DATE, getOrderString(), Task.CREATION_DATE);
    query = query.replace(TaskCriteria.isVisible().toString(), Criterion.all.toString());

    filter.setFilterQueryOverride(query);
  }
Ejemplo n.º 14
0
  @Override
  public void onReceive(Context context, Intent intent) {
    if (!Preferences.getBoolean(R.string.p_rmd_enabled, true)) return;

    DependencyInjectionService.getInstance().inject(this);

    int reengagementReminders = Preferences.getInt(ReengagementService.PREF_REENGAGEMENT_COUNT, 1);
    Preferences.setInt(ReengagementService.PREF_REENGAGEMENT_COUNT, reengagementReminders + 1);

    Intent notifIntent = new Intent(context, TaskListActivity.class);

    QueryTemplate template = new QueryTemplate().where(TaskCriteria.activeVisibleMine());
    String sql =
        SortHelper.adjustQueryForFlagsAndSort(template.toString(), 0, SortHelper.SORT_AUTO)
            + " LIMIT "
            + TASK_LIMIT; //$NON-NLS-1$

    boolean hasTasks = false;
    TodorooCursor<Task> tasks =
        taskService.query(
            Query.select(Task.ID).where(TaskCriteria.activeVisibleMine()).limit(TASK_LIMIT));
    try {
      hasTasks = tasks.getCount() > 0;
    } finally {
      tasks.close();
    }

    String title =
        Notifications.getRandomReminder(
            context.getResources().getStringArray(R.array.rmd_reengage_notif_titles));
    if (title.contains("%s")) { // $NON-NLS-1$
      String name = ""; // $NON-NLS-1$
      if (actFmPreferenceService.isLoggedIn()) {
        JSONObject thisUser = ActFmPreferenceService.thisUser();
        name = thisUser.optString("first_name"); // $NON-NLS-1$
        if (TextUtils.isEmpty(name)) name = thisUser.optString("name"); // $NON-NLS-1$
        if (TextUtils.isEmpty(name)) name = context.getString(R.string.rmd_reengage_name_default);
      }
      title = String.format(title, name);
    }

    String text =
        Notifications.getRandomReminder(
            context
                .getResources()
                .getStringArray(
                    hasTasks
                        ? R.array.rmd_reengage_dialog_options
                        : R.array.rmd_reengage_dialog_empty_options));

    FilterWithCustomIntent filter =
        new FilterWithCustomIntent(
            context.getString(R.string.rmd_NoA_filter),
            context.getString(R.string.rmd_NoA_filter),
            sql,
            null);
    filter.customTaskList = new ComponentName(context, ReengagementFragment.class);
    filter.customExtras = new Bundle();
    filter.customExtras.putString(ReengagementFragment.EXTRA_TEXT, text);

    notifIntent.setAction("NOTIFY_reengagement"); // $NON-NLS-1$
    notifIntent.putExtra(TaskListFragment.TOKEN_FILTER, filter);
    notifIntent.putExtra(ReengagementFragment.EXTRA_TEXT, text);
    notifIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    notifIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_REENGAGEMENT);

    NotificationManager manager = new AndroidNotificationManager(context);
    Notification notification =
        new Notification(R.drawable.notif_astrid, text, System.currentTimeMillis());

    PendingIntent pendingIntent =
        PendingIntent.getActivity(context, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(context, title, text, pendingIntent);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    if (Preferences.getBoolean(R.string.p_rmd_persistent, true)) {
      notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_SHOW_LIGHTS;
      notification.ledOffMS = 5000;
      notification.ledOnMS = 700;
      notification.ledARGB = Color.YELLOW;
    } else {
      notification.defaults = Notification.DEFAULT_LIGHTS;
    }

    manager.notify(0, notification);
    Flags.set(Flags.REFRESH); // Forces a reload when app launches

    ReengagementService.scheduleReengagementAlarm(context);
  }