use of com.ichi2.libanki.utils.Time in project Anki-Android by ankidroid.
the class Connection method doInBackgroundSync.
/**
* In the payload, success means that the sync did occur correctly and that a change did occur.
* So success can be false without error, if no change occurred at all.
*/
private Payload doInBackgroundSync(Payload data) {
sIsCancellable = true;
Timber.d("doInBackgroundSync()");
// Block execution until any previous background task finishes, or timeout after 5s
boolean ok = TaskManager.waitToFinish(5);
// Unique key allowing to identify the user to AnkiWeb without password
String hkey = (String) data.data[0];
// Whether media should be synced too
boolean media = (Boolean) data.data[1];
// If normal sync can't occur, what to do
ConflictResolution conflictResolution = (ConflictResolution) data.data[2];
// A number AnkiWeb told us to send back. Probably to choose the best server for the user
HostNum hostNum = (HostNum) data.data[3];
// Use safe version that catches exceptions so that full sync is still possible
Collection col = CollectionHelper.getInstance().getColSafe(AnkiDroidApp.getInstance());
boolean colCorruptFullSync = false;
if (!CollectionHelper.getInstance().colIsOpen() || !ok) {
if (FULL_DOWNLOAD == conflictResolution) {
colCorruptFullSync = true;
} else {
return returnGenericError(data);
}
}
try {
CollectionHelper.getInstance().lockCollection();
RemoteServer remoteServer = new RemoteServer(this, hkey, hostNum);
Syncer client = new Syncer(col, remoteServer, hostNum);
// run sync and check state
boolean noChanges = false;
if (conflictResolution == null) {
Timber.i("Sync - starting sync");
publishProgress(R.string.sync_prepare_syncing);
Pair<ConnectionResultType, Object> ret = client.sync(this);
data.message = client.getSyncMsg();
if (ret == null) {
return returnGenericError(data);
}
if (NO_CHANGES != ret.first && SUCCESS != ret.first) {
data.success = false;
data.resultType = ret.first;
data.result = new Object[] { ret.second };
// Check if there was a sanity check error
if (SANITY_CHECK_ERROR == ret.first) {
// Force full sync next time
col.modSchemaNoCheck();
col.save();
}
return data;
}
// save and note success state
if (NO_CHANGES == ret.first) {
// publishProgress(R.string.sync_no_changes_message);
noChanges = true;
}
} else {
try {
// Disable sync cancellation for full-sync
sIsCancellable = false;
FullSyncer fullSyncServer = new FullSyncer(col, hkey, this, hostNum);
switch(conflictResolution) {
case FULL_UPLOAD:
{
Timber.i("Sync - fullsync - upload collection");
publishProgress(R.string.sync_preparing_full_sync_message);
Pair<ConnectionResultType, Object[]> ret = fullSyncServer.upload();
col.reopen();
if (ret == null) {
return returnGenericError(data);
}
if (ret.first == ARBITRARY_STRING && !ret.second[0].equals(HttpSyncer.ANKIWEB_STATUS_OK)) {
data.success = false;
data.resultType = ret.first;
data.result = ret.second;
return data;
}
break;
}
case FULL_DOWNLOAD:
{
Timber.i("Sync - fullsync - download collection");
publishProgress(R.string.sync_downloading_message);
ConnectionResultType ret = fullSyncServer.download();
if (ret == null) {
Timber.w("Sync - fullsync - unknown error");
return returnGenericError(data);
}
if (SUCCESS == ret) {
data.success = true;
col.reopen();
}
if (SUCCESS != ret) {
Timber.w("Sync - fullsync - download failed");
data.success = false;
data.resultType = ret;
if (!colCorruptFullSync) {
col.reopen();
}
return data;
}
break;
}
default:
}
} catch (OutOfMemoryError e) {
Timber.w(e);
AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync");
data.success = false;
data.resultType = OUT_OF_MEMORY_ERROR;
data.result = new Object[0];
return data;
} catch (RuntimeException e) {
Timber.w(e);
if (timeoutOccurred(e)) {
data.resultType = CONNECTION_ERROR;
} else if (USER_ABORTED_SYNC.toString().equals(e.getMessage())) {
data.resultType = USER_ABORTED_SYNC;
} else {
AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync");
data.resultType = IO_EXCEPTION;
}
data.result = new Object[] { e };
data.success = false;
return data;
}
}
// clear undo to avoid non syncing orphans (because undo resets usn too
if (!noChanges) {
col.clearUndo();
}
// then move on to media sync
sIsCancellable = true;
boolean noMediaChanges = false;
String mediaError = null;
if (media) {
RemoteMediaServer mediaServer = new RemoteMediaServer(col, hkey, this, hostNum);
MediaSyncer mediaClient = new MediaSyncer(col, mediaServer, this);
Pair<ConnectionResultType, String> ret;
try {
Timber.i("Sync - Performing media sync");
ret = mediaClient.sync();
if (ret == null || ret.first == null) {
mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_error);
} else {
if (CORRUPT == ret.first) {
mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_db_error);
noMediaChanges = true;
}
if (NO_CHANGES == ret.first) {
publishProgress(R.string.sync_media_no_changes);
noMediaChanges = true;
}
if (MEDIA_SANITY_FAILED == ret.first) {
mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_sanity_failed);
} else {
publishProgress(R.string.sync_media_success);
}
}
} catch (RuntimeException e) {
Timber.w(e);
if (timeoutOccurred(e)) {
data.resultType = CONNECTION_ERROR;
data.result = new Object[] { e };
} else if (USER_ABORTED_SYNC.toString().equals(e.getMessage())) {
data.resultType = USER_ABORTED_SYNC;
data.result = new Object[] { e };
}
int downloadedCount = mediaClient.getDownloadCount();
int uploadedCount = mediaClient.getUploadCount();
if (downloadedCount == 0 && uploadedCount == 0) {
mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_error) + "\n\n" + e.getLocalizedMessage();
} else {
mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_partial_updated, downloadedCount, uploadedCount) + "\n\n" + e.getLocalizedMessage();
}
}
}
if (noChanges && (!media || noMediaChanges)) {
// This means that there is no change at all, neither media nor collection. Not that there was an error.
data.success = false;
data.resultType = NO_CHANGES;
data.result = new Object[0];
} else {
data.success = true;
data.data = new Object[] { conflictResolution, col, mediaError };
}
return data;
} catch (MediaSyncException e) {
Timber.e("Media sync rejected by server");
data.success = false;
data.resultType = MEDIA_SYNC_SERVER_ERROR;
data.result = new Object[] { e };
AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync");
return data;
} catch (UnknownHttpResponseException e) {
Timber.e(e, "doInBackgroundSync -- unknown response code error");
data.success = false;
int code = e.getResponseCode();
String msg = e.getLocalizedMessage();
data.resultType = ERROR;
data.result = new Object[] { code, msg };
return data;
} catch (Exception e) {
// Global error catcher.
// Try to give a human readable error, otherwise print the raw error message
Timber.e(e, "doInBackgroundSync error");
data.success = false;
if (timeoutOccurred(e)) {
data.resultType = CONNECTION_ERROR;
data.result = new Object[] { e };
} else if (USER_ABORTED_SYNC.toString().equals(e.getMessage())) {
data.resultType = USER_ABORTED_SYNC;
data.result = new Object[] { e };
} else {
AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync");
data.resultType = ARBITRARY_STRING;
data.result = new Object[] { e.getLocalizedMessage(), e };
}
return data;
} finally {
Timber.i("Sync Finished - Closing Collection");
// don't bump mod time unless we explicitly save
if (col != null) {
col.close(false);
}
CollectionHelper.getInstance().unlockCollection();
}
}
use of com.ichi2.libanki.utils.Time in project Anki-Android by ankidroid.
the class MultimediaEditFieldActivity method recreateEditingUi.
private void recreateEditingUi(ChangeUIRequest newUI, @Nullable Bundle savedInstanceState) {
Timber.d("recreateEditingUi()");
// Permissions are checked async, save our current state to allow continuation
mCurrentChangeRequest = newUI;
// As we only get here a second time if we have the required permissions
if (newUI.getRequiresPermissionCheck() && performPermissionRequest(newUI.getField())) {
newUI.markAsPermissionRequested();
return;
}
IControllerFactory controllerFactory = BasicControllerFactory.getInstance();
IFieldController fieldController = controllerFactory.createControllerForField(newUI.getField());
if (fieldController == null) {
Timber.w("Field controller creation failed");
UIRecreationHandler.onControllerCreationFailed(newUI, this);
return;
}
UIRecreationHandler.onPreFieldControllerReplacement(mFieldController);
mFieldController = fieldController;
mField = newUI.getField();
setupUIController(mFieldController, savedInstanceState);
LinearLayout linearLayout = findViewById(R.id.LinearLayoutInScrollViewFieldEdit);
linearLayout.removeAllViews();
mFieldController.createUI(this, linearLayout);
UIRecreationHandler.onPostUICreation(newUI, this);
}
use of com.ichi2.libanki.utils.Time in project Anki-Android by ankidroid.
the class CardBrowser method onCollectionLoaded.
// Finish initializing the activity after the collection has been correctly loaded
@Override
protected void onCollectionLoaded(Collection col) {
super.onCollectionLoaded(col);
Timber.d("onCollectionLoaded()");
registerExternalStorageListener();
SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
// Load reference to action bar title
mActionBarTitle = findViewById(R.id.toolbar_title);
mOrder = CARD_ORDER_NONE;
String colOrder = getCol().get_config_string("sortType");
for (int c = 0; c < fSortTypes.length; ++c) {
if (fSortTypes[c].equals(colOrder)) {
mOrder = c;
break;
}
}
if (mOrder == 1 && preferences.getBoolean("cardBrowserNoSorting", false)) {
mOrder = 0;
}
// This upgrade should already have been done during
// setConf. However older version of AnkiDroid didn't call
// upgradeJSONIfNecessary during setConf, which means the
// conf saved may still have this bug.
mOrderAsc = Upgrade.upgradeJSONIfNecessary(getCol(), "sortBackwards", false);
mCards.reset();
mCardsListView = findViewById(R.id.card_browser_list);
// Create a spinner for column1
Spinner cardsColumn1Spinner = findViewById(R.id.browser_column1_spinner);
ArrayAdapter<CharSequence> column1Adapter = ArrayAdapter.createFromResource(this, R.array.browser_column1_headings, android.R.layout.simple_spinner_item);
column1Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cardsColumn1Spinner.setAdapter(column1Adapter);
mColumn1Index = AnkiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn1", 0);
cardsColumn1Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// If a new column was selected then change the key used to map from mCards to the column TextView
if (pos != mColumn1Index) {
mColumn1Index = pos;
AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit().putInt("cardBrowserColumn1", mColumn1Index).apply();
Column[] fromMap = mCardsAdapter.getFromMapping();
fromMap[0] = COLUMN1_KEYS[mColumn1Index];
mCardsAdapter.setFromMapping(fromMap);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do Nothing
}
});
// Load default value for column2 selection
mColumn2Index = AnkiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn2", 0);
// Setup the column 2 heading as a spinner so that users can easily change the column type
Spinner cardsColumn2Spinner = findViewById(R.id.browser_column2_spinner);
ArrayAdapter<CharSequence> column2Adapter = ArrayAdapter.createFromResource(this, R.array.browser_column2_headings, android.R.layout.simple_spinner_item);
column2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cardsColumn2Spinner.setAdapter(column2Adapter);
// Create a new list adapter with updated column map any time the user changes the column
cardsColumn2Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// If a new column was selected then change the key used to map from mCards to the column TextView
if (pos != mColumn2Index) {
mColumn2Index = pos;
AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit().putInt("cardBrowserColumn2", mColumn2Index).apply();
Column[] fromMap = mCardsAdapter.getFromMapping();
fromMap[1] = COLUMN2_KEYS[mColumn2Index];
mCardsAdapter.setFromMapping(fromMap);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do Nothing
}
});
// get the font and font size from the preferences
int sflRelativeFontSize = preferences.getInt("relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO);
String sflCustomFont = preferences.getString("browserEditorFont", "");
Column[] columnsContent = { COLUMN1_KEYS[mColumn1Index], COLUMN2_KEYS[mColumn2Index] };
// make a new list adapter mapping the data in mCards to column1 and column2 of R.layout.card_item_browser
mCardsAdapter = new MultiColumnListAdapter(this, R.layout.card_item_browser, columnsContent, new int[] { R.id.card_sfld, R.id.card_column2 }, sflRelativeFontSize, sflCustomFont);
// link the adapter to the main mCardsListView
mCardsListView.setAdapter(mCardsAdapter);
// make the items (e.g. question & answer) render dynamically when scrolling
mCardsListView.setOnScrollListener(new RenderOnScroll());
// set the spinner index
cardsColumn1Spinner.setSelection(mColumn1Index);
cardsColumn2Spinner.setSelection(mColumn2Index);
mCardsListView.setOnItemClickListener((parent, view, position, id) -> {
if (mInMultiSelectMode) {
// click on whole cell triggers select
CheckBox cb = view.findViewById(R.id.card_checkbox);
cb.toggle();
onCheck(position, view);
} else {
// load up the card selected on the list
long clickedCardId = getCards().get(position).getId();
saveScrollingState(position);
openNoteEditorForCard(clickedCardId);
}
});
mCardsListView.setOnItemLongClickListener((adapterView, view, position, id) -> {
if (mInMultiSelectMode) {
boolean hasChanged = false;
for (int i = Math.min(mLastSelectedPosition, position); i <= Math.max(mLastSelectedPosition, position); i++) {
CardCache card = (CardCache) mCardsListView.getItemAtPosition(i);
// Add to the set of checked cards
hasChanged |= mCheckedCards.add(card);
}
if (hasChanged) {
onSelectionChanged();
}
} else {
mLastSelectedPosition = position;
saveScrollingState(position);
loadMultiSelectMode();
// click on whole cell triggers select
CheckBox cb = view.findViewById(R.id.card_checkbox);
cb.toggle();
onCheck(position, view);
recenterListView(view);
mCardsAdapter.notifyDataSetChanged();
}
return true;
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
long deckId = getCol().getDecks().selected();
mDeckSpinnerSelection = new DeckSpinnerSelection(this, col, this.findViewById(R.id.toolbar_spinner), true, false);
mDeckSpinnerSelection.initializeActionBarDeckSpinner(this.getSupportActionBar());
selectDeckAndSave(deckId);
// If a valid value for last deck exists then use it, otherwise use libanki selected deck
if (getLastDeckId() != null && getLastDeckId() == ALL_DECKS_ID) {
selectAllDecks();
} else if (getLastDeckId() != null && getCol().getDecks().get(getLastDeckId(), false) != null) {
mDeckSpinnerSelection.selectDeckById(getLastDeckId(), false);
} else {
mDeckSpinnerSelection.selectDeckById(getCol().getDecks().selected(), false);
}
}
use of com.ichi2.libanki.utils.Time in project Anki-Android by ankidroid.
the class OverviewStatsBuilderTest method testInfoHtmlStringLife.
@Test
@Config(qualifiers = "en")
public void testInfoHtmlStringLife() {
OverviewStatsBuilder statsTester = new OverviewStatsBuilder(new WebView(getTargetContext()), getCol(), 42L, Stats.AxisType.TYPE_LIFE);
String HTML = statsTester.createInfoHtmlString();
assertEquals(HTML, "<center><style>\n" + "h1, h3 { margin-bottom: 0; margin-top: 1em; text-transform: capitalize; }\n" + ".pielabel { text-align:center; padding:0px; color:white; }\n" + "body {color:#FFFFFF;}\n" + "</style><h1>Today</h1>Studied <b>0 cards</b> in <b>0 minutes</b> today<br>Again count: <b>0</b><br>Learn: <b>0</b>, review: <b>0</b>, relearn: <b>0</b>, filtered: <b>0</b><br>No mature cards were studied today<h1>deck life</h1><h3>FORECAST</h3>Total: <b>0</b> reviews<br>Average: <b>0.0</b> reviews/day<br>Due tomorrow: <b>0</b><br><h3>REVIEW COUNT</h3>Days studied: <b>0%</b> (0 of 1)<br>Total: <b>0</b> reviews<br>Average for days studied: <b>0.0</b> reviews/day<br>If you studied every day: <b>0.0</b> reviews/day<br><h3>REVIEW TIME</h3>Days studied: <b>0%</b> (0 of 1)<br>Total: <b>0</b> minutes<br>Average for days studied: <b>0.0</b> minutes/day<br>If you studied every day: <b>0.0</b> minutes/day<br>Average answer time: <b>0.0s</b> (<b>0.00</b> cards/minute)<br><h3>ADDED</h3>Total: <b>0</b> cards<br>Average: <b>0.0</b> cards/day<br><h3>INTERVALS</h3>Average interval: <b>0.0</b> hours<br>Longest interval: <b>0.0</b> hours<h3>ANSWER BUTTONS</h3>Learning: <b>0.00%</b> correct (0 of 0)<br>Young: <b>0.00%</b> correct (0 of 0)<br>Mature: <b>0.00%</b> correct (0 of 0)<h3>CARD TYPES</h3>Total cards: <b>0</b><br>Total notes: <b>0</b><br>Lowest ease: <b>0%</b><br>Average ease: <b>0%</b><br>Highest ease: <b>0%</b></center>");
}
use of com.ichi2.libanki.utils.Time in project Anki-Android by ankidroid.
the class ReviewerTest method testLrnQueueAfterUndo.
@Test
public void testLrnQueueAfterUndo() {
Collection col = getCol();
JSONObject nw = col.getDecks().confForDid(1).getJSONObject("new");
MockTime time = (MockTime) col.getTime();
nw.put("delays", new JSONArray(new int[] { 1, 10, 60, 120 }));
Card[] cards = new Card[4];
cards[0] = addRevNoteUsingBasicModelDueToday("1", "bar").firstCard();
cards[1] = addNoteUsingBasicModel("2", "bar").firstCard();
cards[2] = addNoteUsingBasicModel("3", "bar").firstCard();
waitForAsyncTasksToComplete();
Reviewer reviewer = startReviewer();
waitForAsyncTasksToComplete();
equalFirstField(cards[0], reviewer.mCurrentCard);
reviewer.answerCard(Consts.BUTTON_ONE);
waitForAsyncTasksToComplete();
equalFirstField(cards[1], reviewer.mCurrentCard);
reviewer.answerCard(Consts.BUTTON_ONE);
waitForAsyncTasksToComplete();
undo(reviewer);
waitForAsyncTasksToComplete();
equalFirstField(cards[1], reviewer.mCurrentCard);
reviewer.answerCard(getCol().getSched().getGoodNewButton());
waitForAsyncTasksToComplete();
equalFirstField(cards[2], reviewer.mCurrentCard);
time.addM(2);
reviewer.answerCard(getCol().getSched().getGoodNewButton());
advanceRobolectricLooperWithSleep();
// This failed in #6898 because this card was not in the queue
equalFirstField(cards[0], reviewer.mCurrentCard);
}
Aggregations