Esempio n. 1
0
  @Override
  public String writeToModel(Task task) {
    Metadata metadata = ProducteevDataService.getInstance().getTaskMetadata(task.getId());
    try {
      if (metadata == null) {
        metadata = new Metadata();
        metadata.setValue(Metadata.KEY, ProducteevTask.METADATA_KEY);
        metadata.setValue(Metadata.TASK, task.getId());
        metadata.setValue(ProducteevTask.ID, 0L);
      }

      ProducteevDashboard dashboard = (ProducteevDashboard) dashboardSelector.getSelectedItem();
      metadata.setValue(ProducteevTask.DASHBOARD_ID, dashboard.getId());

      ProducteevUser responsibleUser = (ProducteevUser) responsibleSelector.getSelectedItem();

      if (responsibleUser == null) metadata.setValue(ProducteevTask.RESPONSIBLE_ID, 0L);
      else metadata.setValue(ProducteevTask.RESPONSIBLE_ID, responsibleUser.getId());

      // Erase PDTV-repeating-info if task itself is repeating with Astrid-repeat
      if (task.containsNonNullValue(Task.RECURRENCE)
          && task.getValue(Task.RECURRENCE).length() > 0) {
        metadata.setValue(ProducteevTask.REPEATING_SETTING, "");
      }

      if (metadata.getSetValues().size() > 0) {
        metadataService.save(metadata);
        task.setValue(Task.MODIFICATION_DATE, DateUtilities.now());
      }
    } catch (Exception e) {
      Log.e("error-saving-pdv", "Error Saving Metadata", e); // $NON-NLS-1$ //$NON-NLS-2$
    }
    return null;
  }
Esempio n. 2
0
  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$
    }
  }
Esempio n. 3
0
  /**
   * Save the given array of alarms into the database
   *
   * @param taskId
   * @param tags
   * @return true if data was changed
   */
  public boolean synchronizeAlarms(long taskId, LinkedHashSet<Long> alarms) {
    MetadataService service = PluginServices.getMetadataService();

    ArrayList<Metadata> metadata = new ArrayList<Metadata>();
    for (Long alarm : alarms) {
      Metadata item = new Metadata();
      item.setValue(Metadata.KEY, AlarmFields.METADATA_KEY);
      item.setValue(AlarmFields.TIME, alarm);
      item.setValue(AlarmFields.TYPE, AlarmFields.TYPE_SINGLE);
      metadata.add(item);
    }

    boolean changed =
        service.synchronizeMetadata(taskId, metadata, Metadata.KEY.eq(AlarmFields.METADATA_KEY))
            > 0;
    if (changed) scheduleAlarms(taskId);
    return changed;
  }
Esempio n. 4
0
  private void showFile(final Metadata m) {
    final String fileType =
        m.containsNonNullValue(FileMetadata.FILE_TYPE)
            ? m.getValue(FileMetadata.FILE_TYPE)
            : FileMetadata.FILE_TYPE_OTHER;
    final String filePath = m.getValue(FileMetadata.FILE_PATH);

    if (fileType.startsWith(FileMetadata.FILE_TYPE_AUDIO)) {
      RecognizerApi.play(
          activity,
          m.getValue(FileMetadata.FILE_PATH),
          new PlaybackExceptionHandler() {
            @Override
            public void playbackFailed(String file) {
              showFromIntent(filePath, fileType);
            }
          });
    } else if (fileType.startsWith(FileMetadata.FILE_TYPE_IMAGE)) {
      AlertDialog image = new AlertDialog.Builder(activity).create();
      ImageView imageView = new ImageView(activity);
      imageView.setLayoutParams(
          new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
      Bitmap bitmap = AndroidUtilities.readScaledBitmap(filePath);

      if (bitmap == null) {
        Toast.makeText(activity, R.string.file_err_memory, Toast.LENGTH_LONG).show();
        return;
      }

      imageView.setImageBitmap(bitmap);
      image.setView(imageView);

      image.setButton(
          activity.getString(R.string.DLG_close),
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface d, int which) {
              return;
            }
          });
      image.show();
    } else {
      String useType = fileType;
      if (fileType.equals(FileMetadata.FILE_TYPE_OTHER)) {
        String extension = AndroidUtilities.getFileExtension(filePath);

        MimeTypeMap map = MimeTypeMap.getSingleton();
        String guessedType = map.getMimeTypeFromExtension(extension);
        if (!TextUtils.isEmpty(guessedType)) useType = guessedType;
        if (useType != guessedType) {
          m.setValue(FileMetadata.FILE_TYPE, useType);
          metadataService.save(m);
        }
      }
      showFromIntent(filePath, useType);
    }
  }
Esempio n. 5
0
 private void validateFiles() {
   for (int i = 0; i < files.size(); i++) {
     Metadata m = files.get(i);
     if (m.containsNonNullValue(FileMetadata.FILE_PATH)) {
       File f = new File(m.getValue(FileMetadata.FILE_PATH));
       if (!f.exists()) {
         m.setValue(FileMetadata.FILE_PATH, ""); // $NON-NLS-1$
         if (m.containsNonNullValue(
             FileMetadata.URL)) { // We're ok, just the local file was deleted
           metadataService.save(m);
         } else { // No local file and no url -- delete the metadata
           metadataService.delete(m);
           files.remove(i);
           i--;
         }
       }
     }
   }
 }
Esempio n. 6
0
  private synchronized void serializeMetadata(Task task) throws IOException {
    TodorooCursor<Metadata> cursor =
        metadataService.query(
            Query.select(Metadata.PROPERTIES).where(MetadataCriteria.byTask(task.getId())));
    try {
      Metadata metadata = new Metadata();
      for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        metadata.readFromCursor(cursor);

        xml.startTag(null, BackupConstants.METADATA_TAG);
        serializeModel(metadata, Metadata.PROPERTIES, Metadata.ID, Metadata.TASK);
        xml.endTag(null, BackupConstants.METADATA_TAG);
      }
    } finally {
      cursor.close();
    }
  }
Esempio n. 7
0
  @SuppressWarnings("nls")
  private void readTagData(JSONArray tags) throws JSONException {
    ArrayList<Metadata> metadata = new ArrayList<Metadata>();
    for (int i = 0; i < tags.length(); i++) {
      JSONObject tagObject = tags.getJSONObject(i);
      TagData tagData = tagDataService.getTag(tagObject.getString("name"), TagData.ID);
      if (tagData == null) tagData = new TagData();
      ActFmSyncService.JsonHelper.tagFromJson(tagObject, tagData);
      tagDataService.save(tagData);

      Metadata tagMeta = new Metadata();
      tagMeta.setValue(Metadata.KEY, TagService.KEY);
      tagMeta.setValue(TagService.TAG, tagData.getValue(TagData.NAME));
      tagMeta.setValue(TagService.REMOTE_ID, tagData.getValue(TagData.REMOTE_ID));
      metadata.add(tagMeta);
    }

    metadataService.synchronizeMetadata(
        task.getId(), metadata, MetadataCriteria.withKey(TagService.KEY));
  }
Esempio n. 8
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();
   }
 }
Esempio n. 9
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. 10
0
  private void setUpListAdapter() {
    items.clear();
    this.removeAllViews();
    historyCount = 0;
    TodorooCursor<Metadata> notes =
        metadataService.query(
            Query.select(Metadata.PROPERTIES)
                .where(MetadataCriteria.byTaskAndwithKey(task.getId(), NoteMetadata.METADATA_KEY)));
    try {
      Metadata metadata = new Metadata();
      for (notes.moveToFirst(); !notes.isAfterLast(); notes.moveToNext()) {
        metadata.readFromCursor(notes);
        items.add(NoteOrUpdate.fromMetadata(metadata));
      }
    } finally {
      notes.close();
    }

    User self = UpdateAdapter.getSelfUser();

    TodorooCursor<UserActivity> updates = taskService.getActivityAndHistoryForTask(task);
    try {
      UserActivity update = new UserActivity();
      History history = new History();
      User user = new User();
      for (updates.moveToFirst(); !updates.isAfterLast(); updates.moveToNext()) {
        update.clear();
        user.clear();

        String type = updates.getString(UpdateAdapter.TYPE_PROPERTY_INDEX);
        NoteOrUpdate noa;
        boolean isSelf;
        if (NameMaps.TABLE_ID_USER_ACTIVITY.equals(type)) {
          UpdateAdapter.readUserActivityProperties(updates, update);
          isSelf = Task.USER_ID_SELF.equals(update.getValue(UserActivity.USER_UUID));
          UpdateAdapter.readUserProperties(updates, user, self, isSelf);
          noa = NoteOrUpdate.fromUpdateOrHistory(activity, update, null, user, linkColor);
        } else {
          UpdateAdapter.readHistoryProperties(updates, history);
          isSelf = Task.USER_ID_SELF.equals(history.getValue(History.USER_UUID));
          UpdateAdapter.readUserProperties(updates, user, self, isSelf);
          noa = NoteOrUpdate.fromUpdateOrHistory(activity, null, history, user, linkColor);
          historyCount++;
        }
        if (noa != null) items.add(noa);
      }
    } finally {
      updates.close();
    }

    Collections.sort(
        items,
        new Comparator<NoteOrUpdate>() {
          @Override
          public int compare(NoteOrUpdate a, NoteOrUpdate b) {
            if (a.createdAt < b.createdAt) return 1;
            else if (a.createdAt == b.createdAt) return 0;
            else return -1;
          }
        });

    for (int i = 0; i < Math.min(items.size(), commentItems); i++) {
      View notesView = this.getUpdateNotes(items.get(i), this);
      this.addView(notesView);
    }

    if (items.size() > commentItems || task.getValue(Task.HISTORY_HAS_MORE) > 0) {
      Button loadMore = new Button(getContext());
      loadMore.setText(R.string.TEA_load_more);
      loadMore.setTextColor(activity.getResources().getColor(R.color.task_edit_deadline_gray));
      loadMore.setBackgroundColor(Color.alpha(0));
      loadMore.setOnClickListener(
          new View.OnClickListener() {
            public void onClick(View v) {
              // Perform action on click
              commentItems += 10;
              setUpListAdapter();
              if (task.getValue(Task.HISTORY_HAS_MORE) > 0)
                new FetchHistory<Task>(
                        taskDao,
                        Task.HISTORY_FETCH_DATE,
                        Task.HISTORY_HAS_MORE,
                        NameMaps.TABLE_ID_TASKS,
                        task.getUuid(),
                        task.getValue(Task.TITLE),
                        0,
                        historyCount,
                        callback)
                    .execute();
            }
          });
      this.addView(loadMore);
    } else if (items.size() == 0) {
      TextView noUpdates = new TextView(getContext());
      noUpdates.setText(R.string.TEA_no_activity);
      noUpdates.setTextColor(activity.getResources().getColor(R.color.task_edit_deadline_gray));
      noUpdates.setLayoutParams(
          new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
      noUpdates.setPadding(10, 10, 10, 10);
      noUpdates.setGravity(Gravity.CENTER);
      noUpdates.setTextSize(16);
      this.addView(noUpdates);
    }

    for (UpdatesChangedListener l : listeners) {
      l.updatesChanged();
    }
  }