Esempio n. 1
0
 private static void populateUser() {
   try {
     user.put("name", Preferences.getStringValue(PREF_NAME));
     user.put("first_name", Preferences.getStringValue(PREF_FIRST_NAME));
     user.put("last_name", Preferences.getStringValue(PREF_LAST_NAME));
     user.put("premium", isPremiumUser());
     user.put("email", Preferences.getStringValue(PREF_EMAIL));
     user.put("picture", Preferences.getStringValue(PREF_PICTURE));
     user.put("id", ActFmPreferenceService.userId());
   } catch (JSONException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 2
0
  @SuppressWarnings("nls")
  private void refreshMembersPage() {
    tagName.setText(tagData.getValue(TagData.NAME));
    picture.setUrl(tagData.getValue(TagData.PICTURE));

    TextView ownerLabel = (TextView) findViewById(R.id.tag_owner);
    try {
      if (tagData.getFlag(TagData.FLAGS, TagData.FLAG_EMERGENT)) {
        ownerLabel.setText(String.format("<%s>", getString(R.string.actfm_TVA_tag_owner_none)));
      } else if (tagData.getValue(TagData.USER_ID) == 0) {
        ownerLabel.setText(Preferences.getStringValue(ActFmPreferenceService.PREF_NAME));
      } else {
        JSONObject owner = new JSONObject(tagData.getValue(TagData.USER));
        ownerLabel.setText(owner.getString("name"));
      }
    } catch (JSONException e) {
      Log.e("tag-view-activity", "json error refresh owner", e);
      ownerLabel.setText("<error>");
      System.err.println(tagData.getValue(TagData.USER));
    }

    tagMembers.removeAllViews();
    String peopleJson = tagData.getValue(TagData.MEMBERS);
    if (!TextUtils.isEmpty(peopleJson)) {
      try {
        JSONArray people = new JSONArray(peopleJson);
        for (int i = 0; i < people.length(); i++) {
          JSONObject person = people.getJSONObject(i);
          TextView textView = null;

          if (person.has("id") && person.getLong("id") == ActFmPreferenceService.userId())
            textView =
                tagMembers.addPerson(Preferences.getStringValue(ActFmPreferenceService.PREF_NAME));
          else if (!TextUtils.isEmpty(person.optString("name")))
            textView = tagMembers.addPerson(person.getString("name"));
          else if (!TextUtils.isEmpty(person.optString("email")))
            textView = tagMembers.addPerson(person.getString("email"));

          if (textView != null) {
            textView.setTag(person);
            textView.setEnabled(false);
          }
        }
      } catch (JSONException e) {
        System.err.println(peopleJson);
        Log.e("tag-view-activity", "json error refresh members", e);
      }
    }

    tagMembers.addPerson(""); // $NON-NLS-1$
  }
Esempio n. 3
0
    private Filter getFilter(int widgetId) {
      // base our filter off the inbox filter, replace stuff if we have it
      Filter filter = CoreFilterExposer.buildInboxFilter(getResources());
      String sql = Preferences.getStringValue(WidgetConfigActivity.PREF_SQL + widgetId);
      if (sql != null) filter.sqlQuery = sql;
      String title = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId);
      if (title != null) filter.title = title;
      String contentValues =
          Preferences.getStringValue(WidgetConfigActivity.PREF_VALUES + widgetId);
      if (contentValues != null)
        filter.valuesForNewTasks =
            AndroidUtilities.contentValuesFromSerializedString(contentValues);

      return filter;
    }
 @SuppressWarnings("nls")
 private static synchronized JSONObject thisUser() {
   if (user == null) {
     user = new JSONObject();
     try {
       user.put("name", Preferences.getStringValue(PREF_NAME));
       user.put("email", Preferences.getStringValue(PREF_EMAIL));
       user.put("picture", Preferences.getStringValue(PREF_PICTURE));
       user.put("id", Preferences.getLong(PREF_USER_ID, 0));
       System.err.println(user);
     } catch (JSONException e) {
       throw new RuntimeException(e);
     }
   }
   return user;
 }
Esempio n. 5
0
  /**
   * Invalidates and then revalidates the auth token for the currently logged in user Shouldn't be
   * called from the main thread--will block on network calls
   *
   * @return valid token on success, null on failure
   */
  public static synchronized String validateAuthToken(Context c, String token)
      throws GoogleTasksException {
    GoogleAccountManager accountManager = new GoogleAccountManager(ContextManager.getContext());

    if (testToken(token)) {
      return token;
    }

    // If fail, token may have expired -- get a new one and return that
    String accountName = Preferences.getStringValue(GtasksPreferenceService.PREF_USER_NAME);
    Account a = accountManager.getAccountByName(accountName);
    if (a == null) {
      throw new GoogleTasksException(
          c.getString(R.string.gtasks_error_accountNotFound, accountName), "account-not-found");
    }

    for (int i = 0; i < REVALIDATION_TRIES; i++) {
      accountManager.invalidateAuthToken(token);

      // try with notify-auth-failure = false
      AccountManagerFuture<Bundle> future =
          accountManager.manager.getAuthToken(a, GtasksInvoker.AUTH_TOKEN_TYPE, false, null, null);
      token = getTokenFromFuture(c, future);

      if (TOKEN_INTENT_RECEIVED.equals(token)) {
        return null;
      } else if (token != null && testToken(token)) {
        return token;
      }
    }

    throw new GoogleTasksException(
        c.getString(R.string.gtasks_error_authRefresh), "auth-token-refresh");
  }
Esempio n. 6
0
  /**
   * Migration for existing users to assert that the "hide always" section divider exists in the
   * preferences. Knowing that this section will always be in the constructed list of controls
   * simplifies the logic a bit.
   *
   * @param c
   */
  public static void assertHideUntilSectionExists(Context c, long latestSetVersion) {
    if (latestSetVersion == 0) Preferences.setBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, true);

    if (Preferences.getBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, false)) return;

    String order = Preferences.getStringValue(BEAST_MODE_ORDER_PREF);
    String hideSectionPref = c.getString(R.string.TEA_ctrl_hide_section_pref);
    if (TextUtils.isEmpty(order)) {
      // create preference and stick hide always at the end of it
      String[] items = c.getResources().getStringArray(R.array.TEA_control_sets_prefs);
      StringBuilder builder = new StringBuilder();
      for (String item : items) {
        if (item.equals(hideSectionPref)) continue;
        builder.append(item);
        builder.append(BEAST_MODE_PREF_ITEM_SEPARATOR);
      }

      builder.append(hideSectionPref);
      builder.append(BEAST_MODE_PREF_ITEM_SEPARATOR);
      order = builder.toString();
    } else if (!order.contains(hideSectionPref)) {
      order += (hideSectionPref + BEAST_MODE_PREF_ITEM_SEPARATOR);
    }
    Preferences.setString(BEAST_MODE_ORDER_PREF, order);

    Preferences.setBoolean(BEAST_MODE_ASSERTED_HIDE_ALWAYS, true);
  }
Esempio n. 7
0
 /** @return get user id */
 public static String userId() {
   try {
     String value = Preferences.getStringValue(PREF_USER_ID);
     if (value == null) {
       return Long.toString(Preferences.getLong(PREF_USER_ID, -2L));
     }
     return value;
   } catch (Exception e) {
     return Long.toString(Preferences.getLong(PREF_USER_ID, -2L));
   }
 }
Esempio n. 8
0
  @Override
  public String getLoggedInUserName() {
    String name = Preferences.getStringValue(PREF_NAME);
    if (TextUtils.isEmpty(name)) {
      String firstName = Preferences.getStringValue(PREF_FIRST_NAME);
      if (!TextUtils.isEmpty(firstName)) {
        name = firstName;
      }

      String lastName = Preferences.getStringValue(PREF_FIRST_NAME);
      if (!TextUtils.isEmpty(lastName)) {
        if (!TextUtils.isEmpty(name)) {
          name += " "; // $NON-NLS-1$
        }
        name += lastName;
      }

      if (name == null) {
        name = ""; // $NON-NLS-1$
      }
    }
    return name;
  }
Esempio n. 9
0
  public static ArrayList<String> constructOrderedControlList(Context context) {
    String order = Preferences.getStringValue(BEAST_MODE_ORDER_PREF);
    ArrayList<String> list = new ArrayList<String>();
    String[] itemsArray;
    if (order == null) {
      itemsArray = context.getResources().getStringArray(R.array.TEA_control_sets_prefs);
    } else {
      itemsArray = order.split(BEAST_MODE_PREF_ITEM_SEPARATOR);
    }

    for (String s : itemsArray) {
      if (!s.equals(context.getResources().getString(R.string.TEA_ctrl_title_pref))) {
        list.add(s);
      }
    }

    if (order == null) return list;

    itemsArray = context.getResources().getStringArray(R.array.TEA_control_sets_prefs);
    for (int i = 0; i < itemsArray.length; i++) {
      if (!list.contains(itemsArray[i])) list.add(i, itemsArray[i]);
    }
    return list;
  }
Esempio n. 10
0
  private String getQuery(Context context) {
    if (SubtasksHelper.isTagFilter(filter)) {
      ((FilterWithCustomIntent) filter).customTaskList =
          new ComponentName(
              context,
              TagViewFragment.class); // In case legacy widget was created with subtasks fragment
    }

    SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context);
    int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
    flags |= SortHelper.FLAG_SHOW_RECENTLY_COMPLETED;
    int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
    if (sort == 0) {
      sort = SortHelper.SORT_WIDGET;
    }

    String query =
        SortHelper.adjustQueryForFlagsAndSort(filter.getSqlQuery(), flags, sort)
            .replaceAll("LIMIT \\d+", "");

    String tagName = Preferences.getStringValue(WidgetConfigActivity.PREF_TITLE + widgetId);

    return SubtasksHelper.applySubtasksToWidgetFilter(filter, query, tagName, 0);
  }
  @Override
  public void onReceive(final Context context, Intent intent) {
    if (!Preferences.getBoolean(R.string.p_field_missed_calls, false)) {
      Preferences.clear(PREF_LAST_INCOMING_NUMBER);
      return;
    }

    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
      String number = digitsOnly(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
      if (TextUtils.isEmpty(number)) return;

      Preferences.setString(PREF_LAST_INCOMING_NUMBER, number);
    } else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
      final String lastNumber = Preferences.getStringValue(PREF_LAST_INCOMING_NUMBER);
      if (TextUtils.isEmpty(lastNumber)) {
        return;
      }

      Preferences.clear(PREF_LAST_INCOMING_NUMBER);

      new Thread() {
        @Override
        public void run() {
          AndroidUtilities.sleepDeep(WAIT_BEFORE_READ_LOG);
          Cursor calls =
              context
                  .getContentResolver()
                  .query(
                      Calls.CONTENT_URI,
                      new String[] {Calls.NUMBER, Calls.DATE, Calls.CACHED_NAME},
                      Calls.TYPE + " = ? AND " + Calls.NEW + " = ?",
                      new String[] {Integer.toString(Calls.MISSED_TYPE), "1"},
                      Calls.DATE + " DESC");
          try {
            if (calls == null) return;
            if (calls.moveToFirst()) {
              int numberIndex = calls.getColumnIndex(Calls.NUMBER);
              String number = calls.getString(numberIndex);

              // Sanity check for phone number match
              // in case the phone logs haven't updated for some reaosn
              if (!lastNumber.equals(digitsOnly(number))) {
                return;
              }

              // If a lot of time has passed since the most recent missed call, ignore
              // It could be the same person calling you back before you call them back,
              // but if you answer this time, the missed call will still be in the database
              // and will be processed again.
              int dateIndex = calls.getColumnIndex(Calls.DATE);
              long date = calls.getLong(dateIndex);
              if (DateUtilities.now() - date > 2 * DateUtilities.ONE_MINUTE) {
                return;
              }

              int nameIndex = calls.getColumnIndex(Calls.CACHED_NAME);
              String name = calls.getString(nameIndex);

              String timeString = DateUtilities.getTimeString(context, new Date(date));

              long contactId = getContactIdFromNumber(context, number);

              Intent missedCallIntent = new Intent(context, MissedCallActivity.class);
              missedCallIntent.putExtra(MissedCallActivity.EXTRA_NUMBER, number);
              missedCallIntent.putExtra(MissedCallActivity.EXTRA_NAME, name);
              missedCallIntent.putExtra(MissedCallActivity.EXTRA_TIME, timeString);
              missedCallIntent.putExtra(MissedCallActivity.EXTRA_CONTACT_ID, contactId);
              missedCallIntent.setFlags(
                  Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
              context.startActivity(missedCallIntent);
            }
          } finally {
            if (calls != null) calls.close();
          }
        }
      }.start();
    }
  }
Esempio n. 12
0
  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
    }
  }
Esempio n. 13
0
    @SuppressWarnings("nls")
    public RemoteViews buildUpdate(Context context, int widgetId) {
      DependencyInjectionService.getInstance().inject(this);

      RemoteViews views = null;

      views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized);

      int[] textIDs = TEXT_IDS;
      int[] separatorIDs = SEPARATOR_IDS;
      int numberOfTasks = 5;

      for (int i = 0; i < textIDs.length; i++) views.setTextViewText(textIDs[i], "");

      TodorooCursor<Task> cursor = null;
      Filter filter = null;
      try {
        filter = getFilter(widgetId);
        views.setTextViewText(R.id.widget_title, filter.title);

        SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
        int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
        int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
        String query =
            SortHelper.adjustQueryForFlagsAndSort(filter.sqlQuery, flags, sort)
                    .replaceAll("LIMIT \\d+", "")
                + " LIMIT "
                + numberOfTasks;

        database.openForReading();
        cursor =
            taskService.fetchFiltered(
                query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
        Task task = new Task();
        for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
          cursor.moveToPosition(i);
          task.readFromCursor(cursor);

          String textContent = "";
          int textColor = Color.WHITE;

          textContent = task.getValue(Task.TITLE);

          if (task.isCompleted())
            textColor = context.getResources().getColor(R.color.task_list_done);
          else if (task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
            textColor = context.getResources().getColor(R.color.task_list_overdue);

          if (i > 0) views.setViewVisibility(separatorIDs[i - 1], View.VISIBLE);
          views.setTextViewText(textIDs[i], textContent);
          views.setTextColor(textIDs[i], textColor);
        }

        for (int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
          if (i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
        }
      } catch (Exception e) {
        // can happen if database is not ready
        Log.e("WIDGET-UPDATE", "Error updating widget", e);
      } finally {
        if (cursor != null) cursor.close();
      }

      updateForScreenSize(views);

      Intent listIntent = new Intent(context, TaskListActivity.class);
      String customIntent =
          Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_INTENT + widgetId);
      if (customIntent != null) {
        listIntent.setComponent(ComponentName.unflattenFromString(customIntent));
        String serializedExtras =
            Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_EXTRAS + widgetId);
        Bundle extras = AndroidUtilities.bundleFromSerializedString(serializedExtras);
        listIntent.putExtras(extras);
      }
      listIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_WIDGET);
      listIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
      if (filter != null) {
        listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
        listIntent.setAction("L" + widgetId + filter.sqlQuery);
      }
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              context, widgetId, listIntent, PendingIntent.FLAG_CANCEL_CURRENT);
      views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);

      Intent editIntent = new Intent(context, TaskEditActivity.class);
      editIntent.setFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      if (filter != null && filter.valuesForNewTasks != null) {
        String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
        editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
        editIntent.setType(values);
      }
      pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0);
      views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);

      return views;
    }
Esempio n. 14
0
  private static void setNormalPreferenceDefaults() {
    Context context = ContextManager.getContext();
    SharedPreferences prefs = Preferences.getPrefs(context);
    Editor editor = prefs.edit();
    Resources r = context.getResources();

    Preferences.setIfUnset(prefs, editor, r, R.string.p_default_urgency_key, 0);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_default_importance_key, 2);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_default_hideUntil_key, 0);
    Preferences.setIfUnset(
        prefs,
        editor,
        r,
        R.string.p_default_reminders_key,
        Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_rmd_default_random_hours, 0);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_fontSize, 16);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_showNotes, false);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_use_contact_picker, true);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_field_missed_calls, true);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_third_party_addons, false);
    Preferences.setIfUnset(prefs, editor, r, R.string.p_end_at_deadline, true);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_rmd_persistent, true);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_ideas_tab_enabled, true);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_show_featured_lists, true);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_taskRowStyle, false);

    Preferences.setIfUnset(prefs, editor, r, R.string.p_calendar_reminders, true);

    String dragDropTestInitialized = "android_drag_drop_initialized"; // $NON-NLS-1$
    if (!Preferences.getBoolean(dragDropTestInitialized, false)) {
      SharedPreferences publicPrefs = getPublicPrefs(context);
      if (publicPrefs != null) {
        Editor edit = publicPrefs.edit();
        if (edit != null) {
          edit.putInt(SortHelper.PREF_SORT_FLAGS, SortHelper.FLAG_DRAG_DROP);
          edit.putInt(SortHelper.PREF_SORT_SORT, SortHelper.SORT_AUTO);
          edit.commit();
          Preferences.setInt(P_SUBTASKS_HELP, 1);
        }
      }
      Preferences.setBoolean(dragDropTestInitialized, true);
    }

    if ("white-blue"
        .equals(
            Preferences.getStringValue(
                R.string.p_theme))) { // $NON-NLS-1$ migrate from when white-blue wasn't the default
      Preferences.setString(R.string.p_theme, ThemeService.THEME_WHITE);
    }

    if (Constants.MARKET_STRATEGY.defaultPhoneLayout()) {
      Preferences.setIfUnset(prefs, editor, r, R.string.p_force_phone_layout, true);
    }

    setShowFriendsView();

    setShowFeaturedLists();

    editor.commit();
  }
Esempio n. 15
0
 /** The name (e.g. 4.0.1) of the currently installed version of astrid */
 public static String getCurrentVersionName() {
   String versionName = Preferences.getStringValue(P_CURRENT_VERSION_NAME);
   if (versionName == null) versionName = "0"; // $NON-NLS-1$
   return versionName;
 }
Esempio n. 16
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);
  }
Esempio n. 17
0
 private static void readPreferenceToUser(User u, StringProperty prop, String prefKey) {
   String val = Preferences.getStringValue(prefKey);
   if (val == null) val = ""; // $NON-NLS-1$
   u.setValue(prop, val);
 }
Esempio n. 18
0
  /**
   * Shows an Astrid notification. Pulls in ring tone and quiet hour settings from preferences. You
   * can make it say anything you like.
   *
   * @param ringTimes number of times to ring (-1 = nonstop)
   */
  public static void showNotification(
      int notificationId, Intent intent, int type, String title, String text, int ringTimes) {
    Context context = ContextManager.getContext();
    if (notificationManager == null) notificationManager = new AndroidNotificationManager(context);

    // quiet hours? unless alarm clock
    boolean quietHours = false;
    int quietHoursStart = Preferences.getIntegerFromString(R.string.p_rmd_quietStart, -1);
    int quietHoursEnd = Preferences.getIntegerFromString(R.string.p_rmd_quietEnd, -1);
    if (quietHoursStart != -1 && quietHoursEnd != -1 && ringTimes >= 0) {
      int hour = new Date().getHours();
      if (quietHoursStart <= quietHoursEnd) {
        if (hour >= quietHoursStart && hour < quietHoursEnd) quietHours = true;
      } else { // wrap across 24/hour boundary
        if (hour >= quietHoursStart || hour < quietHoursEnd) quietHours = true;
      }
    }

    PendingIntent pendingIntent =
        PendingIntent.getActivity(
            context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // set up properties (name and icon) for the notification
    int icon;
    switch (Preferences.getIntegerFromString(R.string.p_rmd_icon, ICON_SET_ASTRID)) {
      case ICON_SET_PINK:
        icon = R.drawable.notif_pink_alarm;
        break;
      case ICON_SET_BORING:
        icon = R.drawable.notif_boring_alarm;
        break;
      default:
        icon = R.drawable.notif_astrid;
    }

    // create notification object
    Notification notification = new Notification(icon, text, System.currentTimeMillis());
    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;

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    // detect call state
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    int callState = tm.getCallState();

    boolean voiceReminder = Preferences.getBoolean(R.string.p_voiceRemindersEnabled, false);

    // if multi-ring is activated, set up the flags for insistent
    // notification, and increase the volume to full volume, so the user
    // will actually pay attention to the alarm
    if (ringTimes != 1 && (type != ReminderService.TYPE_RANDOM)) {
      notification.audioStreamType = AudioManager.STREAM_ALARM;
      audioManager.setStreamVolume(
          AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);

      // insistent rings until notification is disabled
      if (ringTimes < 0) {
        notification.flags |= Notification.FLAG_INSISTENT;
        voiceReminder = false;
      }

    } else {
      notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;
    }

    // quiet hours = no sound
    if (quietHours || callState != TelephonyManager.CALL_STATE_IDLE) {
      notification.sound = null;
      voiceReminder = false;
    } else {
      String notificationPreference = Preferences.getStringValue(R.string.p_rmd_ringtone);
      if (audioManager.getStreamVolume(AudioManager.STREAM_RING) == 0) {
        notification.sound = null;
        voiceReminder = false;
      } else if (notificationPreference != null) {
        if (notificationPreference.length() > 0) {
          Uri notificationSound = Uri.parse(notificationPreference);
          notification.sound = notificationSound;
        } else {
          notification.sound = null;
        }
      } else {
        notification.defaults |= Notification.DEFAULT_SOUND;
      }
    }

    // quiet hours && ! due date or snooze = no vibrate
    if (quietHours && !(type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_SNOOZE)) {
      notification.vibrate = null;
    } else if (callState != TelephonyManager.CALL_STATE_IDLE) {
      notification.vibrate = null;
    } else {
      if (Preferences.getBoolean(R.string.p_rmd_vibrate, true)
          && audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_NOTIFICATION)) {
        notification.vibrate = new long[] {0, 1000, 500, 1000, 500, 1000};
      } else {
        notification.vibrate = null;
      }
    }

    if (Constants.DEBUG)
      Log.w("Astrid", "Logging notification: " + text); // $NON-NLS-1$ //$NON-NLS-2$

    for (int i = 0; i < Math.max(ringTimes, 1); i++) {
      notificationManager.notify(notificationId, notification);
      AndroidUtilities.sleepDeep(500);
    }

    if (voiceReminder) {
      AndroidUtilities.sleepDeep(2000);
      for (int i = 0; i < 50; i++) {
        AndroidUtilities.sleepDeep(500);
        if (audioManager.getMode() != AudioManager.MODE_RINGTONE) break;
      }
      try {
        VoiceOutputService.getVoiceOutputInstance().queueSpeak(text);
      } catch (VerifyError e) {
        // unavailable
      }
    }
  }