Search in sources :

Example 1 with OrgDateTime

use of com.orgzly.org.datetime.OrgDateTime in project orgzly-android by orgzly.

the class ReminderService method getNoteReminders.

public static List<NoteReminder> getNoteReminders(final Context context, final ReadableInstant now, final LastRun lastRun, final int beforeOrAfter) {
    if (BuildConfig.LOG_DEBUG)
        LogUtils.d(TAG);
    final List<NoteReminder> result = new ArrayList<>();
    TimesClient.forEachTime(context, noteTime -> {
        if (isRelevantNoteTime(context, noteTime)) {
            OrgDateTime orgDateTime = OrgDateTime.parse(noteTime.orgTimestampString);
            NoteReminderPayload payload = new NoteReminderPayload(noteTime.noteId, noteTime.bookId, noteTime.bookName, noteTime.title, noteTime.timeType, orgDateTime);
            ReadableInstant[] interval = getInterval(beforeOrAfter, now, lastRun, noteTime.timeType);
            DateTime time = OrgDateTimeUtils.getFirstWarningTime(noteTime.timeType, orgDateTime, interval[0], interval[1], // Default time of day
            new OrgInterval(9, OrgInterval.Unit.HOUR), // Warning period for deadlines
            new OrgInterval(1, OrgInterval.Unit.DAY));
            if (time != null) {
                result.add(new NoteReminder(time, payload));
            }
        }
    });
    if (BuildConfig.LOG_DEBUG)
        LogUtils.d(TAG, "Fetched times, now sorting " + result.size() + " entries by time...");
    /* Sort by time, older first. */
    Collections.sort(result, (o1, o2) -> o1.getRunTime().compareTo(o2.getRunTime()));
    if (BuildConfig.LOG_DEBUG)
        LogUtils.d(TAG, "Times sorted, total " + result.size());
    return result;
}
Also used : ReadableInstant(org.joda.time.ReadableInstant) OrgInterval(com.orgzly.org.datetime.OrgInterval) ArrayList(java.util.ArrayList) OrgDateTime(com.orgzly.org.datetime.OrgDateTime) DateTime(org.joda.time.DateTime) OrgDateTime(com.orgzly.org.datetime.OrgDateTime)

Example 2 with OrgDateTime

use of com.orgzly.org.datetime.OrgDateTime in project orgzly-android by orgzly.

the class Shelf method addOpUpdateProperty.

private void addOpUpdateProperty(ArrayList<ContentProviderOperation> ops, Note note, String createdAtPropName, long dbCreatedAt, String currPropValue, Set<Long> bookIds) {
    String value = new OrgDateTime(dbCreatedAt, false).toString();
    if (!value.equals(currPropValue)) {
        if (BuildConfig.LOG_DEBUG)
            LogUtils.d(TAG, "Updating property", note.getId(), createdAtPropName, currPropValue, value);
        ops.add(ContentProviderOperation.newUpdate(ProviderContract.NoteProperties.ContentUri.notesIdProperties(note.getId())).withValue(createdAtPropName, value).build());
        // Should we remove the old property?
        bookIds.add(note.getPosition().getBookId());
    } else {
        if (BuildConfig.LOG_DEBUG)
            LogUtils.d(TAG, "Skipping update", note.getId(), createdAtPropName, value);
    }
}
Also used : OrgDateTime(com.orgzly.org.datetime.OrgDateTime)

Example 3 with OrgDateTime

use of com.orgzly.org.datetime.OrgDateTime in project orgzly-android by orgzly.

the class Shelf method writeBookToFile.

/**
 * Writes content of book from database to specified file.
 * TODO: Do in Provider under transaction
 */
public void writeBookToFile(final Book book, BookName.Format format, File file) throws IOException {
    /* Use the same encoding. */
    String encoding = book.getUsedEncoding();
    if (encoding == null) {
        encoding = Charset.defaultCharset().name();
    }
    final PrintWriter out = new PrintWriter(file, encoding);
    try {
        String separateNotesWithNewLine = AppPreferences.separateNotesWithNewLine(mContext);
        String createdAtPropertyName = AppPreferences.createdAtProperty(mContext);
        boolean useCreatedAtProperty = AppPreferences.createdAt(mContext);
        OrgParserSettings parserSettings = OrgParserSettings.getBasic();
        if (mContext.getString(R.string.pref_value_separate_notes_with_new_line_always).equals(separateNotesWithNewLine)) {
            parserSettings.separateNotesWithNewLine = OrgParserSettings.SeparateNotesWithNewLine.ALWAYS;
        } else if (mContext.getString(R.string.pref_value_separate_notes_with_new_line_multi_line_notes_only).equals(separateNotesWithNewLine)) {
            parserSettings.separateNotesWithNewLine = OrgParserSettings.SeparateNotesWithNewLine.MULTI_LINE_NOTES_ONLY;
        } else if (mContext.getString(R.string.pref_value_separate_notes_with_new_line_never).equals(separateNotesWithNewLine)) {
            parserSettings.separateNotesWithNewLine = OrgParserSettings.SeparateNotesWithNewLine.NEVER;
        }
        parserSettings.separateHeaderAndContentWithNewLine = AppPreferences.separateHeaderAndContentWithNewLine(mContext);
        parserSettings.tagsColumn = AppPreferences.tagsColumn(mContext);
        parserSettings.orgIndentMode = AppPreferences.orgIndentMode(mContext);
        parserSettings.orgIndentIndentationPerLevel = AppPreferences.orgIndentIndentationPerLevel(mContext);
        final OrgParserWriter parserWriter = new OrgParserWriter(parserSettings);
        // Write preface
        out.write(parserWriter.whiteSpacedFilePreface(book.getPreface()));
        // Write notes
        NotesClient.forEachBookNote(mContext, book.getName(), note -> {
            // Update note properties with created-at property, if the time exists.
            if (useCreatedAtProperty && createdAtPropertyName != null && note.getCreatedAt() > 0) {
                OrgDateTime time = new OrgDateTime(note.getCreatedAt(), false);
                note.getHead().addProperty(createdAtPropertyName, time.toString());
            }
            out.write(parserWriter.whiteSpacedHead(note.getHead(), note.getPosition().getLevel(), book.getOrgFileSettings().isIndented()));
        });
    } finally {
        out.close();
    }
}
Also used : OrgParserSettings(com.orgzly.org.parser.OrgParserSettings) OrgDateTime(com.orgzly.org.datetime.OrgDateTime) PrintWriter(java.io.PrintWriter) OrgParserWriter(com.orgzly.org.parser.OrgParserWriter)

Example 4 with OrgDateTime

use of com.orgzly.org.datetime.OrgDateTime in project orgzly-android by orgzly.

the class Shelf method syncCreatedAtTimeWithProperty.

/**
 * Syncs created-at time and property, using lower value if both exist.
 */
public void syncCreatedAtTimeWithProperty() throws IOException {
    boolean useCreatedAtProperty = AppPreferences.createdAt(mContext);
    String createdAtPropName = AppPreferences.createdAtProperty(mContext);
    if (!useCreatedAtProperty) {
        return;
    }
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    // If new property is added to the note below, book has to be marked as modified.
    Set<Long> bookIds = new HashSet<>();
    /*
         * Get all notes.
         * This is slow and only notes that have either created-at time or created-at property
         * are actually needed. But since this syncing (triggered on preference change) is done
         * so rarely, we don't bother.
         */
    try (Cursor cursor = mContext.getContentResolver().query(ProviderContract.Notes.ContentUri.notes(), null, null, null, null)) {
        if (cursor != null) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                /* Get current heading string. */
                Note note = NotesClient.fromCursor(cursor);
                /* Skip root node. */
                if (note.getPosition().getLevel() == 0) {
                    continue;
                }
                long dbCreatedAt = note.getCreatedAt();
                OrgProperties properties = NotesClient.getNoteProperties(mContext, NotesClient.idFromCursor(cursor));
                String dbPropValue = properties.get(createdAtPropName);
                OrgDateTime dbPropertyValue = OrgDateTime.doParse(dbPropValue);
                // Compare dbCreatedAt and dbPropertyValue
                if (dbCreatedAt > 0 && dbPropertyValue == null) {
                    addOpUpdateProperty(ops, note, createdAtPropName, dbCreatedAt, dbPropValue, bookIds);
                } else if (dbCreatedAt > 0 && dbPropertyValue != null) {
                    // Use older created-at
                    if (dbPropertyValue.getCalendar().getTimeInMillis() < dbCreatedAt) {
                        addOpUpdateCreatedAt(ops, note, dbPropertyValue, note.getCreatedAt());
                    } else {
                        addOpUpdateProperty(ops, note, createdAtPropName, dbCreatedAt, dbPropValue, bookIds);
                    }
                // Or prefer property and set created-at time?
                // addOpUpdateCreatedAt(ops, note.getId(), dbPropertyValue, note.getCreatedAt());
                } else if (dbCreatedAt == 0 && dbPropertyValue != null) {
                    addOpUpdateCreatedAt(ops, note, dbPropertyValue, note.getCreatedAt());
                }
            // else: Neither created-at time nor property are set
            }
        }
    }
    long time = System.currentTimeMillis();
    for (long bookId : bookIds) {
        BooksClient.setModifiedTime(mContext, bookId, time);
    }
    /*
         * Apply batch.
         */
    try {
        mContext.getContentResolver().applyBatch(ProviderContract.AUTHORITY, ops);
    } catch (RemoteException | OperationApplicationException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    notifyDataChanged(mContext);
    syncOnNoteUpdate();
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) CircularArrayList(com.orgzly.android.util.CircularArrayList) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) DbNote(com.orgzly.android.provider.models.DbNote) OrgProperties(com.orgzly.org.OrgProperties) OrgDateTime(com.orgzly.org.datetime.OrgDateTime) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException) HashSet(java.util.HashSet)

Example 5 with OrgDateTime

use of com.orgzly.org.datetime.OrgDateTime in project orgzly-android by orgzly.

the class Shelf method createNote.

public Note createNote(Note note, NotePlace target) {
    long time = System.currentTimeMillis();
    // Set created-at time
    note.setCreatedAt(time);
    // Set created-at property
    if (AppPreferences.createdAt(mContext)) {
        String propName = AppPreferences.createdAtProperty(mContext);
        note.getHead().addProperty(propName, new OrgDateTime(time, false).toString());
    }
    /* Create new note. */
    Note insertedNote = NotesClient.create(mContext, note, target, time);
    notifyDataChanged(mContext);
    syncOnNoteCreate();
    return insertedNote;
}
Also used : DbNote(com.orgzly.android.provider.models.DbNote) OrgDateTime(com.orgzly.org.datetime.OrgDateTime)

Aggregations

OrgDateTime (com.orgzly.org.datetime.OrgDateTime)16 ArrayList (java.util.ArrayList)4 Cursor (android.database.Cursor)3 Calendar (java.util.Calendar)3 DateTime (org.joda.time.DateTime)3 ContentValues (android.content.ContentValues)2 DbNote (com.orgzly.android.provider.models.DbNote)2 OrgRepeater (com.orgzly.org.datetime.OrgRepeater)2 SuppressLint (android.annotation.SuppressLint)1 AlertDialog (android.app.AlertDialog)1 DatePickerDialog (android.app.DatePickerDialog)1 Dialog (android.app.Dialog)1 TimePickerDialog (android.app.TimePickerDialog)1 ContentProviderOperation (android.content.ContentProviderOperation)1 Context (android.content.Context)1 OperationApplicationException (android.content.OperationApplicationException)1 SQLiteQueryBuilder (android.database.sqlite.SQLiteQueryBuilder)1 Bundle (android.os.Bundle)1 RemoteException (android.os.RemoteException)1 DialogFragment (android.support.v4.app.DialogFragment)1