2022-12-08 10:18:12 +01:00
|
|
|
/* Copyright 2017 Andrew Dawson
|
|
|
|
*
|
|
|
|
* This file is a part of Tusky.
|
|
|
|
*
|
|
|
|
* This program is free software; you can redistribute it and/or modify it under the terms of the
|
|
|
|
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
|
|
|
|
* License, or (at your option) any later version.
|
|
|
|
*
|
|
|
|
* Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
|
|
|
|
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
|
|
|
|
* Public License for more details.
|
|
|
|
*
|
|
|
|
* You should have received a copy of the GNU General Public License along with Tusky; if not,
|
|
|
|
* see <http://www.gnu.org/licenses>. */
|
|
|
|
package com.keylesspalace.tusky.fragment
|
|
|
|
|
|
|
|
import android.Manifest
|
|
|
|
import android.app.DownloadManager
|
|
|
|
import android.content.ClipData
|
|
|
|
import android.content.ClipboardManager
|
|
|
|
import android.content.Context
|
|
|
|
import android.content.DialogInterface
|
|
|
|
import android.content.Intent
|
|
|
|
import android.content.pm.PackageManager
|
|
|
|
import android.net.Uri
|
|
|
|
import android.os.Build
|
|
|
|
import android.os.Environment
|
|
|
|
import android.util.Log
|
|
|
|
import android.view.MenuItem
|
|
|
|
import android.view.View
|
|
|
|
import android.widget.Toast
|
|
|
|
import androidx.appcompat.app.AlertDialog
|
|
|
|
import androidx.appcompat.widget.PopupMenu
|
|
|
|
import androidx.core.app.ActivityOptionsCompat
|
|
|
|
import androidx.fragment.app.Fragment
|
|
|
|
import androidx.lifecycle.lifecycleScope
|
|
|
|
import at.connyduck.calladapter.networkresult.fold
|
2023-03-18 10:11:47 +01:00
|
|
|
import at.connyduck.calladapter.networkresult.onFailure
|
2022-12-08 10:18:12 +01:00
|
|
|
import com.google.android.material.snackbar.Snackbar
|
|
|
|
import com.keylesspalace.tusky.BaseActivity
|
|
|
|
import com.keylesspalace.tusky.BottomSheetActivity
|
|
|
|
import com.keylesspalace.tusky.PostLookupFallbackBehavior
|
|
|
|
import com.keylesspalace.tusky.R
|
|
|
|
import com.keylesspalace.tusky.StatusListActivity.Companion.newHashtagIntent
|
|
|
|
import com.keylesspalace.tusky.ViewMediaActivity.Companion.newIntent
|
Fix saving changes to statuses when editing (#3103)
* Fix saving changes to statuses when editing
With the previous code backing out of a status editing operation where changes
had been made (whether it was editing an existing status, a scheduled status,
or a draft) would prompt the user to save the changes as a new draft.
See https://github.com/tuskyapp/Tusky/issues/2704 and
https://github.com/tuskyapp/Tusky/issues/2705 for more detail.
The fix:
- Create an enum to represent the four different kinds of edits that can
happen
- Editing a new status (i.e., composing it for the first time)
- Editing a posted status
- Editing a draft
- Editing a scheduled status
- Store this in ComposeOptions, and set it appropriately everywhere
ComposeOptions is created.
- Check the edit kind when backing out of ComposeActivity, and use this to
show one of three different dialogs as appropriate so the user can:
- Save as new draft or discard changes
- Continue editing or discard changes
- Update existing draft or discard changes
Also fix ComposeViewModel.didChange(), which erroneously reported false if the
old text started with the new text (e.g., if the old text was "hello, world"
and it was edited to "hello", didChange() would not consider that to be a
change).
Fixes https://github.com/tuskyapp/Tusky/issues/2704,
https://github.com/tuskyapp/Tusky/issues/2705
* Use orEmpty extension function
2022-12-31 13:04:49 +01:00
|
|
|
import com.keylesspalace.tusky.components.compose.ComposeActivity
|
2022-12-08 10:18:12 +01:00
|
|
|
import com.keylesspalace.tusky.components.compose.ComposeActivity.Companion.startIntent
|
|
|
|
import com.keylesspalace.tusky.components.compose.ComposeActivity.ComposeOptions
|
2024-03-09 16:12:18 +01:00
|
|
|
import com.keylesspalace.tusky.components.instanceinfo.InstanceInfoRepository
|
2022-12-08 10:18:12 +01:00
|
|
|
import com.keylesspalace.tusky.components.report.ReportActivity.Companion.getIntent
|
|
|
|
import com.keylesspalace.tusky.db.AccountEntity
|
|
|
|
import com.keylesspalace.tusky.db.AccountManager
|
|
|
|
import com.keylesspalace.tusky.di.Injectable
|
|
|
|
import com.keylesspalace.tusky.entity.Attachment
|
|
|
|
import com.keylesspalace.tusky.entity.Status
|
2024-03-09 16:12:18 +01:00
|
|
|
import com.keylesspalace.tusky.entity.Translation
|
2022-12-08 10:18:12 +01:00
|
|
|
import com.keylesspalace.tusky.interfaces.AccountSelectionListener
|
|
|
|
import com.keylesspalace.tusky.network.MastodonApi
|
|
|
|
import com.keylesspalace.tusky.usecase.TimelineCases
|
|
|
|
import com.keylesspalace.tusky.util.openLink
|
|
|
|
import com.keylesspalace.tusky.util.parseAsMastodonHtml
|
2024-03-09 11:04:29 +01:00
|
|
|
import com.keylesspalace.tusky.util.startActivityWithSlideInAnimation
|
2022-12-08 10:18:12 +01:00
|
|
|
import com.keylesspalace.tusky.view.showMuteAccountDialog
|
|
|
|
import com.keylesspalace.tusky.viewdata.AttachmentViewData
|
2024-03-09 16:12:18 +01:00
|
|
|
import java.util.Locale
|
2022-12-08 10:18:12 +01:00
|
|
|
import javax.inject.Inject
|
2024-01-04 17:00:55 +01:00
|
|
|
import kotlinx.coroutines.launch
|
2022-12-08 10:18:12 +01:00
|
|
|
|
|
|
|
/* Note from Andrew on Jan. 22, 2017: This class is a design problem for me, so I left it with an
|
|
|
|
* awkward name. TimelineFragment and NotificationFragment have significant overlap but the nature
|
|
|
|
* of that is complicated by how they're coupled with Status and Notification and the corresponding
|
|
|
|
* adapters. I feel like the profile pages and thread viewer, which I haven't made yet, will also
|
|
|
|
* overlap functionality. So, I'm momentarily leaving it and hopefully working on those will clear
|
|
|
|
* up what needs to be where. */
|
|
|
|
abstract class SFragment : Fragment(), Injectable {
|
|
|
|
protected abstract fun removeItem(position: Int)
|
|
|
|
protected abstract fun onReblog(reblog: Boolean, position: Int)
|
2024-03-09 16:12:18 +01:00
|
|
|
|
|
|
|
/** `null` if translation is not supported on this screen */
|
|
|
|
protected abstract val onMoreTranslate: ((translate: Boolean, position: Int) -> Unit)?
|
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
private lateinit var bottomSheetActivity: BottomSheetActivity
|
|
|
|
|
|
|
|
@Inject
|
|
|
|
lateinit var mastodonApi: MastodonApi
|
|
|
|
|
|
|
|
@Inject
|
|
|
|
lateinit var accountManager: AccountManager
|
|
|
|
|
|
|
|
@Inject
|
|
|
|
lateinit var timelineCases: TimelineCases
|
|
|
|
|
2024-03-09 16:12:18 +01:00
|
|
|
@Inject
|
|
|
|
lateinit var instanceInfoRepository: InstanceInfoRepository
|
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
override fun startActivity(intent: Intent) {
|
2024-03-09 11:04:29 +01:00
|
|
|
requireActivity().startActivityWithSlideInAnimation(intent)
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
override fun onAttach(context: Context) {
|
|
|
|
super.onAttach(context)
|
|
|
|
bottomSheetActivity = if (context is BottomSheetActivity) {
|
|
|
|
context
|
|
|
|
} else {
|
|
|
|
throw IllegalStateException("Fragment must be attached to a BottomSheetActivity!")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-09 16:12:18 +01:00
|
|
|
override fun onResume() {
|
|
|
|
super.onResume()
|
|
|
|
|
|
|
|
// make sure we have instance info for when we'll need it
|
|
|
|
instanceInfoRepository.precache()
|
|
|
|
}
|
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
protected fun openReblog(status: Status?) {
|
|
|
|
if (status == null) return
|
|
|
|
bottomSheetActivity.viewAccount(status.account.id)
|
|
|
|
}
|
|
|
|
|
|
|
|
protected fun viewThread(statusId: String?, statusUrl: String?) {
|
|
|
|
bottomSheetActivity.viewThread(statusId!!, statusUrl)
|
|
|
|
}
|
|
|
|
|
|
|
|
protected fun viewAccount(accountId: String?) {
|
|
|
|
bottomSheetActivity.viewAccount(accountId!!)
|
|
|
|
}
|
|
|
|
|
|
|
|
open fun onViewUrl(url: String) {
|
|
|
|
bottomSheetActivity.viewUrl(url, PostLookupFallbackBehavior.OPEN_IN_BROWSER)
|
|
|
|
}
|
|
|
|
|
|
|
|
protected fun reply(status: Status) {
|
|
|
|
val actionableStatus = status.actionableStatus
|
|
|
|
val account = actionableStatus.account
|
|
|
|
var loggedInUsername: String? = null
|
|
|
|
val activeAccount = accountManager.activeAccount
|
|
|
|
if (activeAccount != null) {
|
|
|
|
loggedInUsername = activeAccount.username
|
|
|
|
}
|
|
|
|
val mentionedUsernames = LinkedHashSet(
|
|
|
|
listOf(account.username) + actionableStatus.mentions.map { it.username }
|
|
|
|
).apply { remove(loggedInUsername) }
|
|
|
|
|
|
|
|
val composeOptions = ComposeOptions(
|
|
|
|
inReplyToId = status.actionableId,
|
|
|
|
replyVisibility = actionableStatus.visibility,
|
|
|
|
contentWarning = actionableStatus.spoilerText,
|
|
|
|
mentionedUsernames = mentionedUsernames,
|
|
|
|
replyingStatusAuthor = account.localUsername,
|
|
|
|
replyingStatusContent = actionableStatus.content.parseAsMastodonHtml().toString(),
|
|
|
|
language = actionableStatus.language,
|
Fix saving changes to statuses when editing (#3103)
* Fix saving changes to statuses when editing
With the previous code backing out of a status editing operation where changes
had been made (whether it was editing an existing status, a scheduled status,
or a draft) would prompt the user to save the changes as a new draft.
See https://github.com/tuskyapp/Tusky/issues/2704 and
https://github.com/tuskyapp/Tusky/issues/2705 for more detail.
The fix:
- Create an enum to represent the four different kinds of edits that can
happen
- Editing a new status (i.e., composing it for the first time)
- Editing a posted status
- Editing a draft
- Editing a scheduled status
- Store this in ComposeOptions, and set it appropriately everywhere
ComposeOptions is created.
- Check the edit kind when backing out of ComposeActivity, and use this to
show one of three different dialogs as appropriate so the user can:
- Save as new draft or discard changes
- Continue editing or discard changes
- Update existing draft or discard changes
Also fix ComposeViewModel.didChange(), which erroneously reported false if the
old text started with the new text (e.g., if the old text was "hello, world"
and it was edited to "hello", didChange() would not consider that to be a
change).
Fixes https://github.com/tuskyapp/Tusky/issues/2704,
https://github.com/tuskyapp/Tusky/issues/2705
* Use orEmpty extension function
2022-12-31 13:04:49 +01:00
|
|
|
kind = ComposeActivity.ComposeKind.NEW
|
2022-12-08 10:18:12 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
val intent = startIntent(requireContext(), composeOptions)
|
|
|
|
requireActivity().startActivity(intent)
|
|
|
|
}
|
|
|
|
|
2024-03-09 16:12:18 +01:00
|
|
|
protected fun more(status: Status, view: View, position: Int, translation: Translation?) {
|
2022-12-08 10:18:12 +01:00
|
|
|
val id = status.actionableId
|
|
|
|
val accountId = status.actionableStatus.account.id
|
|
|
|
val accountUsername = status.actionableStatus.account.username
|
|
|
|
val statusUrl = status.actionableStatus.url
|
|
|
|
var loggedInAccountId: String? = null
|
|
|
|
val activeAccount = accountManager.activeAccount
|
|
|
|
if (activeAccount != null) {
|
|
|
|
loggedInAccountId = activeAccount.accountId
|
|
|
|
}
|
|
|
|
val popup = PopupMenu(requireContext(), view)
|
|
|
|
// Give a different menu depending on whether this is the user's own toot or not.
|
|
|
|
val statusIsByCurrentUser = loggedInAccountId != null && loggedInAccountId == accountId
|
|
|
|
if (statusIsByCurrentUser) {
|
|
|
|
popup.inflate(R.menu.status_more_for_user)
|
|
|
|
val menu = popup.menu
|
|
|
|
when (status.visibility) {
|
|
|
|
Status.Visibility.PUBLIC, Status.Visibility.UNLISTED -> {
|
2024-01-04 17:00:55 +01:00
|
|
|
menu.add(
|
|
|
|
0,
|
|
|
|
R.id.pin,
|
|
|
|
1,
|
|
|
|
getString(
|
Replace Gson library with Moshi (#4309)
**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
|
|
|
if (status.pinned) R.string.unpin_action else R.string.pin_action
|
2024-01-04 17:00:55 +01:00
|
|
|
)
|
|
|
|
)
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
Status.Visibility.PRIVATE -> {
|
|
|
|
val reblogged = status.reblog?.reblogged ?: status.reblogged
|
|
|
|
menu.findItem(R.id.status_reblog_private).isVisible = !reblogged
|
|
|
|
menu.findItem(R.id.status_unreblog_private).isVisible = reblogged
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
else -> {}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
popup.inflate(R.menu.status_more)
|
2024-03-09 16:12:18 +01:00
|
|
|
popup.menu.findItem(R.id.status_download_media).isVisible =
|
|
|
|
status.attachments.isNotEmpty()
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
val menu = popup.menu
|
|
|
|
val openAsItem = menu.findItem(R.id.status_open_as)
|
|
|
|
val openAsText = (activity as BaseActivity?)?.openAsText
|
|
|
|
if (openAsText == null) {
|
|
|
|
openAsItem.isVisible = false
|
|
|
|
} else {
|
|
|
|
openAsItem.title = openAsText
|
|
|
|
}
|
|
|
|
val muteConversationItem = menu.findItem(R.id.status_mute_conversation)
|
2024-03-09 16:12:18 +01:00
|
|
|
val mutable =
|
|
|
|
statusIsByCurrentUser || accountIsInMentions(activeAccount, status.mentions)
|
2022-12-08 10:18:12 +01:00
|
|
|
muteConversationItem.isVisible = mutable
|
|
|
|
if (mutable) {
|
|
|
|
muteConversationItem.setTitle(
|
Replace Gson library with Moshi (#4309)
**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
|
|
|
if (!status.muted) {
|
2022-12-08 10:18:12 +01:00
|
|
|
R.string.action_mute_conversation
|
|
|
|
} else {
|
|
|
|
R.string.action_unmute_conversation
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
|
|
|
// translation not there for your own posts
|
|
|
|
menu.findItem(R.id.status_translate)?.let { translateItem ->
|
|
|
|
translateItem.isVisible = onMoreTranslate != null &&
|
|
|
|
!status.language.equals(Locale.getDefault().language, ignoreCase = true) &&
|
|
|
|
instanceInfoRepository.cachedInstanceInfoOrFallback.translationEnabled == true
|
|
|
|
translateItem.setTitle(if (translation != null) R.string.action_show_original else R.string.action_translate)
|
|
|
|
}
|
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
popup.setOnMenuItemClickListener { item: MenuItem ->
|
|
|
|
when (item.itemId) {
|
|
|
|
R.id.post_share_content -> {
|
|
|
|
val statusToShare = status.reblog ?: status
|
|
|
|
val sendIntent = Intent().apply {
|
|
|
|
action = Intent.ACTION_SEND
|
|
|
|
type = "text/plain"
|
|
|
|
putExtra(
|
|
|
|
Intent.EXTRA_TEXT,
|
|
|
|
"${statusToShare.account.username} - ${statusToShare.content.parseAsMastodonHtml()}"
|
|
|
|
)
|
|
|
|
putExtra(Intent.EXTRA_SUBJECT, statusUrl)
|
|
|
|
}
|
|
|
|
startActivity(
|
|
|
|
Intent.createChooser(
|
|
|
|
sendIntent,
|
|
|
|
resources.getText(R.string.send_post_content_to)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.post_share_link -> {
|
|
|
|
val sendIntent = Intent().apply {
|
|
|
|
action = Intent.ACTION_SEND
|
|
|
|
putExtra(Intent.EXTRA_TEXT, statusUrl)
|
|
|
|
type = "text/plain"
|
|
|
|
}
|
|
|
|
startActivity(
|
|
|
|
Intent.createChooser(
|
|
|
|
sendIntent,
|
|
|
|
resources.getText(R.string.send_post_link_to)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_copy_link -> {
|
2024-01-04 17:00:55 +01:00
|
|
|
(
|
|
|
|
requireActivity().getSystemService(
|
|
|
|
Context.CLIPBOARD_SERVICE
|
|
|
|
) as ClipboardManager
|
|
|
|
).apply {
|
2022-12-08 10:18:12 +01:00
|
|
|
setPrimaryClip(ClipData.newPlainText(null, statusUrl))
|
|
|
|
}
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_open_as -> {
|
|
|
|
showOpenAsDialog(statusUrl, item.title)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_download_media -> {
|
|
|
|
requestDownloadAllMedia(status)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_mute -> {
|
|
|
|
onMute(accountId, accountUsername)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_block -> {
|
|
|
|
onBlock(accountId, accountUsername)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_report -> {
|
|
|
|
openReportPage(accountId, accountUsername, id)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_unreblog_private -> {
|
|
|
|
onReblog(false, position)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_reblog_private -> {
|
|
|
|
onReblog(true, position)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_delete -> {
|
|
|
|
showConfirmDeleteDialog(id, position)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_delete_and_redraft -> {
|
|
|
|
showConfirmEditDialog(id, position, status)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_edit -> {
|
|
|
|
editStatus(id, status)
|
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.pin -> {
|
2023-03-18 10:11:47 +01:00
|
|
|
lifecycleScope.launch {
|
Replace Gson library with Moshi (#4309)
**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
|
|
|
timelineCases.pin(status.id, !status.pinned)
|
2024-03-09 16:12:18 +01:00
|
|
|
.onFailure { e: Throwable ->
|
|
|
|
val message = e.message
|
Replace Gson library with Moshi (#4309)
**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
|
|
|
?: getString(if (status.pinned) R.string.failed_to_unpin else R.string.failed_to_pin)
|
2024-03-09 16:12:18 +01:00
|
|
|
Snackbar.make(requireView(), message, Snackbar.LENGTH_LONG)
|
|
|
|
.show()
|
|
|
|
}
|
2023-03-18 10:11:47 +01:00
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
R.id.status_mute_conversation -> {
|
2023-03-18 10:11:47 +01:00
|
|
|
lifecycleScope.launch {
|
Replace Gson library with Moshi (#4309)
**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
|
|
|
timelineCases.muteConversation(status.id, !status.muted)
|
2023-03-18 10:11:47 +01:00
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
return@setOnMenuItemClickListener true
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
|
|
|
R.id.status_translate -> {
|
|
|
|
onMoreTranslate?.invoke(translation == null, position)
|
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
false
|
|
|
|
}
|
|
|
|
popup.show()
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun onMute(accountId: String, accountUsername: String) {
|
2024-01-04 17:00:55 +01:00
|
|
|
showMuteAccountDialog(
|
|
|
|
this.requireActivity(),
|
|
|
|
accountUsername
|
|
|
|
) { notifications: Boolean?, duration: Int? ->
|
2022-12-28 19:06:31 +01:00
|
|
|
lifecycleScope.launch {
|
|
|
|
timelineCases.mute(accountId, notifications == true, duration)
|
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun onBlock(accountId: String, accountUsername: String) {
|
|
|
|
AlertDialog.Builder(requireContext())
|
|
|
|
.setMessage(getString(R.string.dialog_block_warning, accountUsername))
|
|
|
|
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
|
2022-12-28 19:06:31 +01:00
|
|
|
lifecycleScope.launch {
|
|
|
|
timelineCases.block(accountId)
|
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
.setNegativeButton(android.R.string.cancel, null)
|
|
|
|
.show()
|
|
|
|
}
|
|
|
|
|
|
|
|
protected fun viewMedia(urlIndex: Int, attachments: List<AttachmentViewData>, view: View?) {
|
|
|
|
val (attachment) = attachments[urlIndex]
|
|
|
|
when (attachment.type) {
|
|
|
|
Attachment.Type.GIFV, Attachment.Type.VIDEO, Attachment.Type.IMAGE, Attachment.Type.AUDIO -> {
|
|
|
|
val intent = newIntent(context, attachments, urlIndex)
|
|
|
|
if (view != null) {
|
|
|
|
val url = attachment.url
|
|
|
|
view.transitionName = url
|
|
|
|
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(
|
|
|
|
requireActivity(),
|
2023-03-13 13:16:39 +01:00
|
|
|
view,
|
|
|
|
url
|
2022-12-08 10:18:12 +01:00
|
|
|
)
|
|
|
|
startActivity(intent, options.toBundle())
|
|
|
|
} else {
|
|
|
|
startActivity(intent)
|
|
|
|
}
|
|
|
|
}
|
2024-03-09 16:12:18 +01:00
|
|
|
|
2022-12-08 10:18:12 +01:00
|
|
|
Attachment.Type.UNKNOWN -> {
|
|
|
|
requireContext().openLink(attachment.url)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
protected fun viewTag(tag: String) {
|
|
|
|
startActivity(newHashtagIntent(requireContext(), tag))
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun openReportPage(accountId: String, accountUsername: String, statusId: String) {
|
|
|
|
startActivity(getIntent(requireContext(), accountId, accountUsername, statusId))
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun showConfirmDeleteDialog(id: String, position: Int) {
|
|
|
|
AlertDialog.Builder(requireActivity())
|
|
|
|
.setMessage(R.string.dialog_delete_post_warning)
|
|
|
|
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
|
2023-01-10 21:20:00 +01:00
|
|
|
lifecycleScope.launch {
|
|
|
|
val result = timelineCases.delete(id).exceptionOrNull()
|
|
|
|
if (result != null) {
|
|
|
|
Log.w("SFragment", "error deleting status", result)
|
2022-12-08 10:18:12 +01:00
|
|
|
Toast.makeText(context, R.string.error_generic, Toast.LENGTH_SHORT).show()
|
|
|
|
}
|
2023-01-10 21:20:00 +01:00
|
|
|
// XXX: Removes the item even if there was an error. This is probably not
|
|
|
|
// correct (see similar code in showConfirmEditDialog() which only
|
|
|
|
// removes the item if the timelineCases.delete() call succeeded.
|
|
|
|
//
|
|
|
|
// Either way, this logic should be in the view model.
|
|
|
|
removeItem(position)
|
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
.setNegativeButton(android.R.string.cancel, null)
|
|
|
|
.show()
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun showConfirmEditDialog(id: String, position: Int, status: Status) {
|
|
|
|
if (activity == null) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
AlertDialog.Builder(requireActivity())
|
|
|
|
.setMessage(R.string.dialog_redraft_post_warning)
|
|
|
|
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
|
2023-01-10 21:20:00 +01:00
|
|
|
lifecycleScope.launch {
|
|
|
|
timelineCases.delete(id).fold(
|
2022-12-08 10:18:12 +01:00
|
|
|
{ deletedStatus ->
|
|
|
|
removeItem(position)
|
Replace Gson library with Moshi (#4309)
**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
2024-04-02 21:01:04 +02:00
|
|
|
val sourceStatus = if (deletedStatus.isEmpty) {
|
2022-12-08 10:18:12 +01:00
|
|
|
status.toDeletedStatus()
|
|
|
|
} else {
|
|
|
|
deletedStatus
|
|
|
|
}
|
|
|
|
val composeOptions = ComposeOptions(
|
|
|
|
content = sourceStatus.text,
|
|
|
|
inReplyToId = sourceStatus.inReplyToId,
|
|
|
|
visibility = sourceStatus.visibility,
|
|
|
|
contentWarning = sourceStatus.spoilerText,
|
|
|
|
mediaAttachments = sourceStatus.attachments,
|
|
|
|
sensitive = sourceStatus.sensitive,
|
|
|
|
modifiedInitialState = true,
|
|
|
|
language = sourceStatus.language,
|
|
|
|
poll = sourceStatus.poll?.toNewPoll(sourceStatus.createdAt),
|
Fix saving changes to statuses when editing (#3103)
* Fix saving changes to statuses when editing
With the previous code backing out of a status editing operation where changes
had been made (whether it was editing an existing status, a scheduled status,
or a draft) would prompt the user to save the changes as a new draft.
See https://github.com/tuskyapp/Tusky/issues/2704 and
https://github.com/tuskyapp/Tusky/issues/2705 for more detail.
The fix:
- Create an enum to represent the four different kinds of edits that can
happen
- Editing a new status (i.e., composing it for the first time)
- Editing a posted status
- Editing a draft
- Editing a scheduled status
- Store this in ComposeOptions, and set it appropriately everywhere
ComposeOptions is created.
- Check the edit kind when backing out of ComposeActivity, and use this to
show one of three different dialogs as appropriate so the user can:
- Save as new draft or discard changes
- Continue editing or discard changes
- Update existing draft or discard changes
Also fix ComposeViewModel.didChange(), which erroneously reported false if the
old text started with the new text (e.g., if the old text was "hello, world"
and it was edited to "hello", didChange() would not consider that to be a
change).
Fixes https://github.com/tuskyapp/Tusky/issues/2704,
https://github.com/tuskyapp/Tusky/issues/2705
* Use orEmpty extension function
2022-12-31 13:04:49 +01:00
|
|
|
kind = ComposeActivity.ComposeKind.NEW
|
2022-12-08 10:18:12 +01:00
|
|
|
)
|
|
|
|
startActivity(startIntent(requireContext(), composeOptions))
|
2023-01-10 21:20:00 +01:00
|
|
|
},
|
|
|
|
{ error: Throwable? ->
|
|
|
|
Log.w("SFragment", "error deleting status", error)
|
|
|
|
Toast.makeText(context, R.string.error_generic, Toast.LENGTH_SHORT)
|
|
|
|
.show()
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
2023-01-10 21:20:00 +01:00
|
|
|
)
|
|
|
|
}
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
.setNegativeButton(android.R.string.cancel, null)
|
|
|
|
.show()
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun editStatus(id: String, status: Status) {
|
|
|
|
lifecycleScope.launch {
|
|
|
|
mastodonApi.statusSource(id).fold(
|
|
|
|
{ source ->
|
|
|
|
val composeOptions = ComposeOptions(
|
|
|
|
content = source.text,
|
|
|
|
inReplyToId = status.inReplyToId,
|
|
|
|
visibility = status.visibility,
|
|
|
|
contentWarning = source.spoilerText,
|
|
|
|
mediaAttachments = status.attachments,
|
|
|
|
sensitive = status.sensitive,
|
|
|
|
language = status.language,
|
|
|
|
statusId = source.id,
|
|
|
|
poll = status.poll?.toNewPoll(status.createdAt),
|
Fix saving changes to statuses when editing (#3103)
* Fix saving changes to statuses when editing
With the previous code backing out of a status editing operation where changes
had been made (whether it was editing an existing status, a scheduled status,
or a draft) would prompt the user to save the changes as a new draft.
See https://github.com/tuskyapp/Tusky/issues/2704 and
https://github.com/tuskyapp/Tusky/issues/2705 for more detail.
The fix:
- Create an enum to represent the four different kinds of edits that can
happen
- Editing a new status (i.e., composing it for the first time)
- Editing a posted status
- Editing a draft
- Editing a scheduled status
- Store this in ComposeOptions, and set it appropriately everywhere
ComposeOptions is created.
- Check the edit kind when backing out of ComposeActivity, and use this to
show one of three different dialogs as appropriate so the user can:
- Save as new draft or discard changes
- Continue editing or discard changes
- Update existing draft or discard changes
Also fix ComposeViewModel.didChange(), which erroneously reported false if the
old text started with the new text (e.g., if the old text was "hello, world"
and it was edited to "hello", didChange() would not consider that to be a
change).
Fixes https://github.com/tuskyapp/Tusky/issues/2704,
https://github.com/tuskyapp/Tusky/issues/2705
* Use orEmpty extension function
2022-12-31 13:04:49 +01:00
|
|
|
kind = ComposeActivity.ComposeKind.EDIT_POSTED
|
2022-12-08 10:18:12 +01:00
|
|
|
)
|
|
|
|
startActivity(startIntent(requireContext(), composeOptions))
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Snackbar.make(
|
|
|
|
requireView(),
|
|
|
|
getString(R.string.error_status_source_load),
|
|
|
|
Snackbar.LENGTH_SHORT
|
|
|
|
).show()
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun showOpenAsDialog(statusUrl: String?, dialogTitle: CharSequence?) {
|
|
|
|
if (statusUrl == null) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
(activity as BaseActivity).apply {
|
|
|
|
showAccountChooserDialog(
|
|
|
|
dialogTitle,
|
|
|
|
false,
|
|
|
|
object : AccountSelectionListener {
|
|
|
|
override fun onAccountSelected(account: AccountEntity) {
|
|
|
|
openAsAccount(statusUrl, account)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun downloadAllMedia(status: Status) {
|
|
|
|
Toast.makeText(context, R.string.downloading_media, Toast.LENGTH_SHORT).show()
|
2024-01-04 17:00:55 +01:00
|
|
|
val downloadManager = requireActivity().getSystemService(
|
|
|
|
Context.DOWNLOAD_SERVICE
|
|
|
|
) as DownloadManager
|
2022-12-08 10:18:12 +01:00
|
|
|
|
|
|
|
for ((_, url) in status.attachments) {
|
|
|
|
val uri = Uri.parse(url)
|
|
|
|
downloadManager.enqueue(
|
|
|
|
DownloadManager.Request(uri).apply {
|
2024-01-04 17:00:55 +01:00
|
|
|
setDestinationInExternalPublicDir(
|
|
|
|
Environment.DIRECTORY_DOWNLOADS,
|
|
|
|
uri.lastPathSegment
|
|
|
|
)
|
2022-12-08 10:18:12 +01:00
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private fun requestDownloadAllMedia(status: Status) {
|
|
|
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
|
|
|
|
val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
2023-09-13 09:20:53 +02:00
|
|
|
(activity as BaseActivity).requestPermissions(permissions) { _, grantResults ->
|
2022-12-08 10:18:12 +01:00
|
|
|
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
|
|
|
downloadAllMedia(status)
|
|
|
|
} else {
|
|
|
|
Toast.makeText(
|
|
|
|
context,
|
|
|
|
R.string.error_media_download_permission,
|
|
|
|
Toast.LENGTH_SHORT
|
|
|
|
).show()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
downloadAllMedia(status)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
companion object {
|
|
|
|
private const val TAG = "SFragment"
|
2024-01-04 17:00:55 +01:00
|
|
|
private fun accountIsInMentions(
|
|
|
|
account: AccountEntity?,
|
|
|
|
mentions: List<Status.Mention>
|
|
|
|
): Boolean {
|
2022-12-08 10:18:12 +01:00
|
|
|
return mentions.any { mention ->
|
|
|
|
account?.username == mention.username && account.domain == Uri.parse(mention.url)?.host
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|