Format files (#1179)

use https://codeberg.org/qwerty287/woodpecker-intellij-formatter

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: M M Arif <mmarif@noreply.codeberg.org>
Co-authored-by: qwerty287 <ndev@web.de>
Reviewed-on: https://codeberg.org/gitnex/GitNex/pulls/1179
Reviewed-by: 6543 <6543@noreply.codeberg.org>
Co-authored-by: qwerty287 <qwerty287@noreply.codeberg.org>
Co-committed-by: qwerty287 <qwerty287@noreply.codeberg.org>
This commit is contained in:
qwerty287 2022-08-15 16:26:02 +02:00 committed by 6543
parent 151cb8429c
commit a7d9918b67
552 changed files with 15039 additions and 15130 deletions

View File

@ -13,6 +13,7 @@ line_comment = //
block_comment_start = /* block_comment_start = /*
block_comment = * block_comment = *
block_comment_end = */ block_comment_end = */
max_line_length = 220
[*.json] [*.json]
indent_size = 2 indent_size = 2

View File

@ -9,6 +9,7 @@ labels:
--- ---
## # Describe your matter briefly ## # Describe your matter briefly
<br><br> <br><br>
##### What did you expect? ##### What did you expect?
@ -24,7 +25,7 @@ labels:
* Current android version and phone model/manufacturer: * Current android version and phone model/manufacturer:
* The type of certificate your instance is using (self-signed, signed): * The type of certificate your instance is using (self-signed, signed):
* How you used to log in (via password or token): * How you used to log in (via password or token):
<br> <br>
##### We would appreciate some screenshots or stacktrace's, but this is also not required. ##### We would appreciate some screenshots or stacktrace's, but this is also not required.
--- ---
@ -32,6 +33,6 @@ labels:
<br><br> <br><br>
- [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing). - [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing).
<br> <br>
<!-- Thank you for your time. --> <!-- Thank you for your time. -->

View File

@ -9,9 +9,10 @@ labels:
--- ---
## # Describe your matter briefly ## # Describe your matter briefly
<br><br> <br><br>
- [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing). - [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing).
<br> <br>
<!-- Thank you for your time. --> <!-- Thank you for your time. -->

View File

@ -9,6 +9,7 @@ labels:
--- ---
## # Describe your matter briefly ## # Describe your matter briefly
<br><br> <br><br>
##### What did you expect? ##### What did you expect?
@ -24,7 +25,7 @@ labels:
* Current android version and phone model/manufacturer: * Current android version and phone model/manufacturer:
* The type of certificate your instance is using (self-signed, signed): * The type of certificate your instance is using (self-signed, signed):
* How you used to log in (via password or token): * How you used to log in (via password or token):
<br> <br>
##### We would appreciate some screenshots or stacktrace's, but this is also not required. ##### We would appreciate some screenshots or stacktrace's, but this is also not required.
--- ---
@ -32,6 +33,6 @@ labels:
<br><br> <br><br>
- [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing). - [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing).
<br> <br>
<!-- Thank you for your time. --> <!-- Thank you for your time. -->

View File

@ -1,4 +1,5 @@
### Describe what your pull request does and which issue youre targeting ### Describe what your pull request does and which issue youre targeting
<!-- Create a new issue, if it doesn't exist yet --> <!-- Create a new issue, if it doesn't exist yet -->
<br><br> <br><br>
@ -6,4 +7,5 @@
- [ ] I carefully read the [contribution guidelines](https://codeberg.org/GitNex/GitNex/src/branch/main/CONTRIBUTING.md). - [ ] I carefully read the [contribution guidelines](https://codeberg.org/GitNex/GitNex/src/branch/main/CONTRIBUTING.md).
- [ ] I'm following the code standards as defined [here](https://codeberg.org/gitnex/GitNex/wiki/Code-Standards). - [ ] I'm following the code standards as defined [here](https://codeberg.org/gitnex/GitNex/wiki/Code-Standards).
- [ ] By submitting this pull request, I permit GitNex to license my work under the [GNU General Public License v3](https://codeberg.org/GitNex/GitNex/src/branch/main/LICENSE). - [ ] By submitting this pull request, I permit GitNex to license my work under
the [GNU General Public License v3](https://codeberg.org/GitNex/GitNex/src/branch/main/LICENSE).

View File

@ -1,182 +1,166 @@
<component name="ProjectCodeStyleConfiguration"> <component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173"> <code_scheme name="Project" version="173">
<JavaCodeStyleSettings> <JavaCodeStyleSettings>
<option name="IMPORT_LAYOUT_TABLE"> <option name="IMPORT_LAYOUT_TABLE">
<value> <value>
<package name="android" withSubpackages="true" static="false" /> <package name="android" withSubpackages="true" static="false"/>
<package name="androidx" withSubpackages="true" static="false" /> <package name="androidx" withSubpackages="true" static="false"/>
<package name="com" withSubpackages="true" static="false" /> <package name="com" withSubpackages="true" static="false"/>
<package name="junit" withSubpackages="true" static="false" /> <package name="junit" withSubpackages="true" static="false"/>
<package name="net" withSubpackages="true" static="false" /> <package name="net" withSubpackages="true" static="false"/>
<package name="org" withSubpackages="true" static="false" /> <package name="org" withSubpackages="true" static="false"/>
<package name="java" withSubpackages="true" static="false" /> <package name="java" withSubpackages="true" static="false"/>
<package name="javax" withSubpackages="true" static="false" /> <package name="javax" withSubpackages="true" static="false"/>
<package name="" withSubpackages="true" static="false" /> <package name="" withSubpackages="true" static="false"/>
<package name="" withSubpackages="true" static="true" /> <package name="" withSubpackages="true" static="true"/>
</value> </value>
</option> </option>
</JavaCodeStyleSettings> </JavaCodeStyleSettings>
<JetCodeStyleSettings> <XML>
<option name="PACKAGES_TO_USE_STAR_IMPORTS"> <option name="XML_ALIGN_ATTRIBUTES" value="false"/>
<value> </XML>
<package name="java.util" alias="false" withSubpackages="false" /> <codeStyleSettings language="JAVA">
<package name="kotlinx.android.synthetic" alias="false" withSubpackages="true" /> <option name="RIGHT_MARGIN" value="220"/>
<package name="io.ktor" alias="false" withSubpackages="true" /> <option name="KEEP_LINE_BREAKS" value="false"/>
</value> <option name="KEEP_FIRST_COLUMN_COMMENT" value="false"/>
</option> <option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false"/>
<option name="PACKAGES_IMPORT_LAYOUT"> <option name="BLANK_LINES_AROUND_FIELD_IN_INTERFACE" value="1"/>
<value> <option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1"/>
<package name="" alias="false" withSubpackages="true" /> <option name="BLANK_LINES_BEFORE_CLASS_END" value="1"/>
<package name="java" alias="false" withSubpackages="true" /> <option name="ELSE_ON_NEW_LINE" value="true"/>
<package name="javax" alias="false" withSubpackages="true" /> <option name="CATCH_ON_NEW_LINE" value="true"/>
<package name="kotlin" alias="false" withSubpackages="true" /> <option name="FINALLY_ON_NEW_LINE" value="true"/>
<package name="" alias="true" withSubpackages="true" /> <option name="ALIGN_MULTILINE_PARAMETERS" value="false"/>
</value> <option name="SPACE_BEFORE_IF_PARENTHESES" value="false"/>
</option> <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false"/>
</JetCodeStyleSettings> <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false"/>
<codeStyleSettings language="JAVA"> <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false"/>
<option name="RIGHT_MARGIN" value="220" /> <option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false"/>
<option name="KEEP_LINE_BREAKS" value="false" /> <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false"/>
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" /> <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false"/>
<option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false" /> <option name="CALL_PARAMETERS_WRAP" value="1"/>
<option name="BLANK_LINES_AROUND_FIELD_IN_INTERFACE" value="1" /> <option name="METHOD_PARAMETERS_WRAP" value="1"/>
<option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1" /> <option name="THROWS_LIST_WRAP" value="1"/>
<option name="BLANK_LINES_AFTER_ANONYMOUS_CLASS_HEADER" value="1" /> <option name="METHOD_CALL_CHAIN_WRAP" value="1"/>
<option name="BLANK_LINES_BEFORE_CLASS_END" value="1" /> <option name="TERNARY_OPERATION_WRAP" value="1"/>
<option name="ELSE_ON_NEW_LINE" value="true" /> <option name="ARRAY_INITIALIZER_WRAP" value="1"/>
<option name="CATCH_ON_NEW_LINE" value="true" /> <option name="IF_BRACE_FORCE" value="3"/>
<option name="FINALLY_ON_NEW_LINE" value="true" /> <indentOptions>
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" /> <option name="USE_TAB_CHARACTER" value="true"/>
<option name="SPACE_BEFORE_IF_PARENTHESES" value="false" /> <option name="SMART_TABS" value="true"/>
<option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" /> </indentOptions>
<option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" /> </codeStyleSettings>
<option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" /> <codeStyleSettings language="XML">
<option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" /> <indentOptions>
<option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" /> <option name="CONTINUATION_INDENT_SIZE" value="4"/>
<option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" /> </indentOptions>
<option name="CALL_PARAMETERS_WRAP" value="1" /> <arrangement>
<option name="METHOD_PARAMETERS_WRAP" value="1" /> <rules>
<option name="THROWS_LIST_WRAP" value="1" /> <section>
<option name="METHOD_CALL_CHAIN_WRAP" value="1" /> <rule>
<option name="TERNARY_OPERATION_WRAP" value="1" /> <match>
<option name="ARRAY_INITIALIZER_WRAP" value="1" /> <AND>
<option name="IF_BRACE_FORCE" value="3" /> <NAME>xmlns:android</NAME>
<indentOptions> <XML_ATTRIBUTE/>
<option name="USE_TAB_CHARACTER" value="true" /> <XML_NAMESPACE>^$</XML_NAMESPACE>
<option name="SMART_TABS" value="true" /> </AND>
</indentOptions> </match>
</codeStyleSettings> </rule>
<codeStyleSettings language="XML"> </section>
<indentOptions> <section>
<option name="CONTINUATION_INDENT_SIZE" value="4" /> <rule>
</indentOptions> <match>
<arrangement> <AND>
<rules> <NAME>xmlns:.*</NAME>
<section> <XML_ATTRIBUTE/>
<rule> <XML_NAMESPACE>^$</XML_NAMESPACE>
<match> </AND>
<AND> </match>
<NAME>xmlns:android</NAME> <order>BY_NAME</order>
<XML_ATTRIBUTE /> </rule>
<XML_NAMESPACE>^$</XML_NAMESPACE> </section>
</AND> <section>
</match> <rule>
</rule> <match>
</section> <AND>
<section> <NAME>.*:id</NAME>
<rule> <XML_ATTRIBUTE/>
<match> <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
<AND> </AND>
<NAME>xmlns:.*</NAME> </match>
<XML_ATTRIBUTE /> </rule>
<XML_NAMESPACE>^$</XML_NAMESPACE> </section>
</AND> <section>
</match> <rule>
<order>BY_NAME</order> <match>
</rule> <AND>
</section> <NAME>.*:name</NAME>
<section> <XML_ATTRIBUTE/>
<rule> <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
<match> </AND>
<AND> </match>
<NAME>.*:id</NAME> </rule>
<XML_ATTRIBUTE /> </section>
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE> <section>
</AND> <rule>
</match> <match>
</rule> <AND>
</section> <NAME>name</NAME>
<section> <XML_ATTRIBUTE/>
<rule> <XML_NAMESPACE>^$</XML_NAMESPACE>
<match> </AND>
<AND> </match>
<NAME>.*:name</NAME> </rule>
<XML_ATTRIBUTE /> </section>
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE> <section>
</AND> <rule>
</match> <match>
</rule> <AND>
</section> <NAME>style</NAME>
<section> <XML_ATTRIBUTE/>
<rule> <XML_NAMESPACE>^$</XML_NAMESPACE>
<match> </AND>
<AND> </match>
<NAME>name</NAME> </rule>
<XML_ATTRIBUTE /> </section>
<XML_NAMESPACE>^$</XML_NAMESPACE> <section>
</AND> <rule>
</match> <match>
</rule> <AND>
</section> <NAME>.*</NAME>
<section> <XML_ATTRIBUTE/>
<rule> <XML_NAMESPACE>^$</XML_NAMESPACE>
<match> </AND>
<AND> </match>
<NAME>style</NAME> <order>BY_NAME</order>
<XML_ATTRIBUTE /> </rule>
<XML_NAMESPACE>^$</XML_NAMESPACE> </section>
</AND> <section>
</match> <rule>
</rule> <match>
</section> <AND>
<section> <NAME>.*</NAME>
<rule> <XML_ATTRIBUTE/>
<match> <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
<AND> </AND>
<NAME>.*</NAME> </match>
<XML_ATTRIBUTE /> <order>ANDROID_ATTRIBUTE_ORDER</order>
<XML_NAMESPACE>^$</XML_NAMESPACE> </rule>
</AND> </section>
</match> <section>
<order>BY_NAME</order> <rule>
</rule> <match>
</section> <AND>
<section> <NAME>.*</NAME>
<rule> <XML_ATTRIBUTE/>
<match> <XML_NAMESPACE>.*</XML_NAMESPACE>
<AND> </AND>
<NAME>.*</NAME> </match>
<XML_ATTRIBUTE /> <order>BY_NAME</order>
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE> </rule>
</AND> </section>
</match> </rules>
<order>ANDROID_ATTRIBUTE_ORDER</order> </arrangement>
</rule> </codeStyleSettings>
</section> </code_scheme>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
</code_scheme>
</component> </component>

View File

@ -1,5 +1,5 @@
<component name="ProjectCodeStyleConfiguration"> <component name="ProjectCodeStyleConfiguration">
<state> <state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" /> <option name="USE_PER_PROJECT_SETTINGS" value="true"/>
</state> </state>
</component> </component>

View File

@ -1,6 +1,7 @@
pipeline: pipeline:
author-header: author-header:
image: qwerty287/woodpecker-regex-check image: qwerty287/woodpecker-regex-check
group: check
settings: settings:
pattern: "*.java" pattern: "*.java"
regex: " \\\\* \\\\@author [\\\\S\\\\s]+" regex: " \\\\* \\\\@author [\\\\S\\\\s]+"
@ -8,3 +9,7 @@ pipeline:
style: style:
image: qwerty287/woodpecker-intellij-formatter image: qwerty287/woodpecker-intellij-formatter
group: check
settings:
file_pattern: "*.java"
path: "app/"

View File

@ -1,22 +1,22 @@
depends_on: depends_on:
- build - build
- locale - locale
- check - check
run_on: [ success, failure ] run_on: [ success, failure ]
skip_clone: true skip_clone: true
pipeline: pipeline:
discord: discord:
image: appleboy/drone-discord image: appleboy/drone-discord
settings: settings:
message: "{{#success build.status}} ✅ Build #{{build.number}} of `{{repo.name}}` succeeded.\n\n📝 Commit by {{commit.author}}:\n``` {{commit.message}} ```\n\n🌐 {{ build.link }} {{else}} ❌ Build #{{build.number}} of `{{repo.name}}` failed.\n\n📝 Commit by {{commit.author}}:\n``` {{commit.message}} ```\n\n🌐 {{ build.link }} {{/success}}\n" message: "{{#success build.status}} ✅ Build #{{build.number}} of `{{repo.name}}` succeeded.\n\n📝 Commit by {{commit.author}}:\n``` {{commit.message}} ```\n\n🌐 {{ build.link }} {{else}} ❌ Build #{{build.number}} of `{{repo.name}}` failed.\n\n📝 Commit by {{commit.author}}:\n``` {{commit.message}} ```\n\n🌐 {{ build.link }} {{/success}}\n"
webhook_id: webhook_id:
from_secret: from_secret:
DISCORD_BOT_ID DISCORD_BOT_ID
webhook_token: webhook_token:
from_secret: from_secret:
DISCORD_BOT_SECRET DISCORD_BOT_SECRET
when: when:
event: [ push ] event: [ push ]
branch: main branch: main

View File

@ -1,2 +1,3 @@
# Changelog # Changelog
[Check out the release notes](https://codeberg.org/gitnex/GitNex/releases) [Check out the release notes](https://codeberg.org/gitnex/GitNex/releases)

View File

@ -4,26 +4,33 @@
# GitNex - Android client for Gitea # GitNex - Android client for Gitea
GitNex is a free/paid, open-source Android client for Git repository management tool Gitea. Gitea is a community managed fork of Gogs, lightweight code hosting solution written in Go. GitNex is a free/paid, open-source Android client for Git repository management tool Gitea. Gitea is a community managed fork of Gogs, lightweight
code hosting solution written in Go.
GitNex is licensed under GPLv3 License. See the LICENSE file for the full license text. **No trackers are used** and source code is available here for anyone to audit. GitNex is licensed under GPLv3 License. See the LICENSE file for the full license text. **No trackers are used** and source code is available here for
anyone to audit.
## Downloads ## Downloads
[<img alt='Get it on F-Droid' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/fdroid.png' height="80"/>](https://f-droid.org/en/packages/org.mian.gitnex/) [<img alt='Get it on F-Droid' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/fdroid.png' height="80"/>](https://f-droid.org/en/packages/org.mian.gitnex/)
[<img alt='Get it on Google Play' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/google-play.png' height="80"/>](https://play.google.com/store/apps/details?id=org.mian.gitnex.pro) [<img alt='Get it on Google Play' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/google-play.png' height="80"/>](https://play.google.com/store/apps/details?id=org.mian.gitnex.pro)
[<img alt='Download builds and releases' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/apk-badge.png' height="82"/>](https://cloud.swatian.com/s/DN7E5xxtaw4fRbE) [<img alt='Download builds and releases' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/apk-badge.png' height="82"/>](https://cloud.swatian.com/s/DN7E5xxtaw4fRbE)
## Note about Gitea version ## Note about Gitea version
Please make sure that you are on latest stable release or later for better app experience. Please make sure that you are on latest stable release or later for better app experience.
Check the versions [compatibility page](https://codeberg.org/gitnex/GitNex/wiki/Compatibility) which lists all the supported versions with compatibility ratio. Check the versions [compatibility page](https://codeberg.org/gitnex/GitNex/wiki/Compatibility) which lists all the supported versions with
compatibility ratio.
## Build from source ## Build from source
Option 1 - Download the source code, open it in Android Studio and build it there. Option 1 - Download the source code, open it in Android Studio and build it there.
Option 2 - Open terminal(Linux) and cd to the project dir. Run `./gradlew assembleFree`. Option 2 - Open terminal(Linux) and cd to the project dir. Run `./gradlew assembleFree`.
## Features ## Features
- Multiple accounts support - Multiple accounts support
- File and directory browser - File and directory browser
- File viewer - File viewer
@ -37,12 +44,15 @@ Option 2 - Open terminal(Linux) and cd to the project dir. Run `./gradlew assemb
- [& more...](https://codeberg.org/gitnex/GitNex/wiki/Features) - [& more...](https://codeberg.org/gitnex/GitNex/wiki/Features)
## Contributing ## Contributing
[Contributing](https://codeberg.org/gitnex/GitNex/wiki/Contributing) [Contributing](https://codeberg.org/gitnex/GitNex/wiki/Contributing)
## Translation ## Translation
Help us translate GitNex to your native language. Help us translate GitNex to your native language.
We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your language is not listed, please request [here](https://codeberg.org/gitnex/GitNex/issues) to add it to the project. We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your language is not listed, please
request [here](https://codeberg.org/gitnex/GitNex/issues) to add it to the project.
**Link: https://crowdin.com/project/GitNex** **Link: https://crowdin.com/project/GitNex**
@ -53,6 +63,7 @@ We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your la
[<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png" alt="005.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png" alt="006.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png" alt="007.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png" alt="008.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png) [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png" alt="005.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png" alt="006.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png" alt="007.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png" alt="008.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png)
## Links ## Links
[Website](https://gitnex.com) [Website](https://gitnex.com)
[Wiki](https://codeberg.org/gitnex/GitNex/wiki/Home) [Wiki](https://codeberg.org/gitnex/GitNex/wiki/Home)
@ -64,9 +75,11 @@ We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your la
[Release Blog](https://gitnex.codeberg.page) [Release Blog](https://gitnex.codeberg.page)
## Thanks ## Thanks
Thanks to all the open source libraries, contributors and donators. Thanks to all the open source libraries, contributors and donators.
#### Open source libraries #### Open source libraries
- [square/retrofit](https://github.com/square/retrofit) - [square/retrofit](https://github.com/square/retrofit)
- [google/gson](https://github.com/google/gson) - [google/gson](https://github.com/google/gson)
- [square/okhttp](https://github.com/square/okhttp) - [square/okhttp](https://github.com/square/okhttp)
@ -89,6 +102,7 @@ Thanks to all the open source libraries, contributors and donators.
- [AmrDeveloper/CodeView](https://github.com/AmrDeveloper/CodeView) - [AmrDeveloper/CodeView](https://github.com/AmrDeveloper/CodeView)
#### Icon sets #### Icon sets
- [lucide-icons/lucide](https://github.com/lucide-icons/lucide) - [lucide-icons/lucide](https://github.com/lucide-icons/lucide)
- [primer/octicons](https://github.com/primer/octicons) - [primer/octicons](https://github.com/primer/octicons)
- [google/material-design-icons](https://github.com/google/material-design-icons) - [google/material-design-icons](https://github.com/google/material-design-icons)

View File

@ -39,7 +39,7 @@ android {
lint { lint {
abortOnError false abortOnError false
} }
defaultConfig{ defaultConfig {
vectorDrawables.useSupportLibrary = true vectorDrawables.useSupportLibrary = true
} }
} }

View File

@ -8,9 +8,7 @@ import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
/** /**
* @author qwerty287 * @author qwerty287
@ -109,5 +107,6 @@ public class AppUtilTest {
assertEquals("https://gitnex.com", AppUtil.changeScheme(Uri.parse("http://gitnex.com"), "https").toString()); assertEquals("https://gitnex.com", AppUtil.changeScheme(Uri.parse("http://gitnex.com"), "https").toString());
assertEquals("ssh://codeberg.org/gitnex/GitNex", AppUtil.changeScheme(Uri.parse("http://codeberg.org/gitnex/GitNex"), "ssh").toString()); assertEquals("ssh://codeberg.org/gitnex/GitNex", AppUtil.changeScheme(Uri.parse("http://codeberg.org/gitnex/GitNex"), "ssh").toString());
} }
} }

View File

@ -3,10 +3,10 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
package="org.mian.gitnex"> package="org.mian.gitnex">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<application <application
android:name=".core.MainApplication" android:name=".core.MainApplication"
@ -20,182 +20,183 @@
tools:targetApi="n"> tools:targetApi="n">
<activity <activity
android:name=".activities.MergePullRequestActivity" android:name=".activities.MergePullRequestActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.FileViewActivity" android:name=".activities.FileViewActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme.NoActionBar" /> android:theme="@style/AppTheme.NoActionBar"/>
<activity <activity
android:name=".activities.CreateFileActivity" android:name=".activities.CreateFileActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme.NoActionBar" /> android:theme="@style/AppTheme.NoActionBar"/>
<activity <activity
android:name=".activities.RepoWatchersActivity" android:name=".activities.RepoWatchersActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme.NoActionBar" /> android:theme="@style/AppTheme.NoActionBar"/>
<activity <activity
android:name=".activities.RepoStargazersActivity" android:name=".activities.RepoStargazersActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme.NoActionBar" /> android:theme="@style/AppTheme.NoActionBar"/>
<activity <activity
android:name=".activities.AdminGetUsersActivity" android:name=".activities.AdminGetUsersActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.AdminUnadoptedReposActivity" android:name=".activities.AdminUnadoptedReposActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreateReleaseActivity" android:name=".activities.CreateReleaseActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.EditIssueActivity" android:name=".activities.EditIssueActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreateNewUserActivity" android:name=".activities.CreateNewUserActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.MyProfileEmailActivity" android:name=".activities.MyProfileEmailActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.AddCollaboratorToRepositoryActivity" android:name=".activities.AddCollaboratorToRepositoryActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreateTeamByOrgActivity" android:name=".activities.CreateTeamByOrgActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.OrganizationTeamInfoActivity" android:name=".activities.OrganizationTeamInfoActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.OrganizationDetailActivity" android:name=".activities.OrganizationDetailActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme.NoActionBar" /> android:theme="@style/AppTheme.NoActionBar"/>
<activity <activity
android:name=".activities.CreateLabelActivity" android:name=".activities.CreateLabelActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreateIssueActivity" android:name=".activities.CreateIssueActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreateMilestoneActivity" android:name=".activities.CreateMilestoneActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.IssueDetailActivity" android:name=".activities.IssueDetailActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:windowSoftInputMode="adjustNothing" /> android:windowSoftInputMode="adjustNothing"/>
<activity <activity
android:name=".activities.RepoDetailActivity" android:name=".activities.RepoDetailActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme.NoActionBar" /> android:theme="@style/AppTheme.NoActionBar"/>
<activity <activity
android:name=".activities.MainActivity" android:name=".activities.MainActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@android:style/Theme.NoTitleBar" android:exported="true"
android:exported="true"> android:theme="@android:style/Theme.NoTitleBar">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </intent-filter>
</activity> </activity>
<activity <activity
android:name=".activities.LoginActivity" android:name=".activities.LoginActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:launchMode="singleTask" android:launchMode="singleTask"
android:theme="@android:style/Theme.NoTitleBar" /> android:theme="@android:style/Theme.NoTitleBar"/>
<activity <activity
android:name=".activities.CreateRepoActivity" android:name=".activities.CreateRepoActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreateOrganizationActivity" android:name=".activities.CreateOrganizationActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.DiffActivity" android:name=".activities.DiffActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@android:style/Theme.NoTitleBar" /> android:theme="@android:style/Theme.NoTitleBar"/>
<activity <activity
android:name=".activities.CommitsActivity" android:name=".activities.CommitsActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CommitDetailActivity" android:name=".activities.CommitDetailActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@android:style/Theme.NoTitleBar" /> android:theme="@android:style/Theme.NoTitleBar"/>
<activity <activity
android:name=".activities.SettingsAppearanceActivity" android:name=".activities.SettingsAppearanceActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.ProfileActivity" android:name=".activities.ProfileActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.SettingsSecurityActivity" android:name=".activities.SettingsSecurityActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.SettingsTranslationActivity" android:name=".activities.SettingsTranslationActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.SettingsReportsActivity" android:name=".activities.SettingsReportsActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.AddNewTeamMemberActivity" android:name=".activities.AddNewTeamMemberActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.AddNewTeamRepoActivity" android:name=".activities.AddNewTeamRepoActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.SettingsDraftsActivity" android:name=".activities.SettingsDraftsActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.RepoForksActivity" android:name=".activities.RepoForksActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.AddNewAccountActivity" android:name=".activities.AddNewAccountActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.RepositorySettingsActivity" android:name=".activities.RepositorySettingsActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.CreatePullRequestActivity" android:name=".activities.CreatePullRequestActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.SettingsGeneralActivity" android:name=".activities.SettingsGeneralActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.SettingsNotificationsActivity" android:name=".activities.SettingsNotificationsActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.AdminCronTasksActivity" android:name=".activities.AdminCronTasksActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:name=".activities.WikiActivity" android:name=".activities.WikiActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:windowSoftInputMode="adjustResize"
android:name=".activities.CodeEditorActivity" android:name=".activities.CodeEditorActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:windowSoftInputMode="adjustResize"/>
<meta-data <meta-data
android:name="com.samsung.android.keepalive.density" android:name="com.samsung.android.keepalive.density"
android:value="true" /> <!-- Version >= 3.0. DeX Dual Mode support --> android:value="true"/> <!-- Version >= 3.0. DeX Dual Mode support -->
<meta-data <meta-data
android:name="com.samsung.android.multidisplay.keep_process_alive" android:name="com.samsung.android.multidisplay.keep_process_alive"
android:value="true" /> <!-- deep links --> android:value="true"/> <!-- deep links -->
<activity <activity
android:name=".activities.DeepLinksActivity" android:name=".activities.DeepLinksActivity"
android:exported="true"
android:launchMode="singleTask" android:launchMode="singleTask"
android:noHistory="true" android:noHistory="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:theme="@android:style/Theme.Translucent.NoTitleBar">
android:exported="true">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http" /> <data android:scheme="http"/>
<data android:scheme="https" /> <data android:scheme="https"/>
<data android:host="codeberg.org" /> <data android:host="codeberg.org"/>
<data android:host="gitea.com" /> <data android:host="gitea.com"/>
<data android:host="try.gitea.io" /> <data android:host="try.gitea.io"/>
<data android:host="code.obermui.de" /> <data android:host="code.obermui.de"/>
<data android:host="git.fsfe.org" /> <data android:host="git.fsfe.org"/>
<data android:host="opendev.org" /> <data android:host="opendev.org"/>
</intent-filter> </intent-filter>
</activity> </activity>
</application> </application>

View File

@ -14,11 +14,8 @@ import java.util.concurrent.TimeUnit;
public class ActionResult<R> { public class ActionResult<R> {
public enum Status { SUCCESS, FAILED }
private final BlockingQueue<Boolean> blockingQueue; private final BlockingQueue<Boolean> blockingQueue;
private final List<OnFinishedListener<R>> onFinishedListeners; private final List<OnFinishedListener<R>> onFinishedListeners;
private boolean invalidated = false; private boolean invalidated = false;
public ActionResult() { public ActionResult() {
@ -42,13 +39,17 @@ public class ActionResult<R> {
onFinishedListener.onFinished(status, result); onFinishedListener.onFinished(status, result);
} }
} catch (InterruptedException ignored) {} }
catch(InterruptedException ignored) {
}
} }
public void invalidate() { public void invalidate() {
if(invalidated) throw new IllegalStateException("Already invalidated"); if(invalidated) {
throw new IllegalStateException("Already invalidated");
}
this.invalidated = true; this.invalidated = true;
} }
@ -70,11 +71,16 @@ public class ActionResult<R> {
} }
public static class None {} public enum Status {SUCCESS, FAILED}
public interface OnFinishedListener<R> { public interface OnFinishedListener<R> {
void onFinished(Status status, R result); void onFinished(Status status, R result);
}
public static class None {
} }
} }

View File

@ -24,9 +24,7 @@ public class AssigneesActions {
public static void getCurrentIssueAssignees(Context ctx, String repoOwner, String repoName, int issueIndex, List<String> currentAssignees) { public static void getCurrentIssueAssignees(Context ctx, String repoOwner, String repoName, int issueIndex, List<String> currentAssignees) {
Call<Issue> callSingleIssueLabels = RetrofitClient Call<Issue> callSingleIssueLabels = RetrofitClient.getApiInterface(ctx).issueGetIssue(repoOwner, repoName, (long) issueIndex);
.getApiInterface(ctx)
.issueGetIssue(repoOwner, repoName, (long) issueIndex);
callSingleIssueLabels.enqueue(new Callback<>() { callSingleIssueLabels.enqueue(new Callback<>() {
@ -63,11 +61,10 @@ public class AssigneesActions {
}); });
} }
public static void getRepositoryAssignees(Context ctx, String repoOwner, String repoName, List<User> assigneesList, MaterialAlertDialogBuilder materialAlertDialogBuilder, AssigneesListAdapter assigneesAdapter, CustomAssigneesSelectionDialogBinding assigneesBinding, ProgressBar progressBar) { public static void getRepositoryAssignees(Context ctx, String repoOwner, String repoName, List<User> assigneesList, MaterialAlertDialogBuilder materialAlertDialogBuilder, AssigneesListAdapter assigneesAdapter,
CustomAssigneesSelectionDialogBinding assigneesBinding, ProgressBar progressBar) {
Call<List<User>> call = RetrofitClient Call<List<User>> call = RetrofitClient.getApiInterface(ctx).repoGetAssignees(repoOwner, repoName);
.getApiInterface(ctx)
.repoGetAssignees(repoOwner, repoName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -113,4 +110,5 @@ public class AssigneesActions {
} }
}); });
} }
} }

View File

@ -19,97 +19,94 @@ import retrofit2.Callback;
public class CollaboratorActions { public class CollaboratorActions {
public static void deleteCollaborator(final Context context, String userName, RepositoryContext repository) { public static void deleteCollaborator(final Context context, String userName, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoDeleteCollaborator(repository.getOwner(), repository.getName(), userName);
.getApiInterface(context)
.repoDeleteCollaborator(repository.getOwner(), repository.getName(), userName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 204) { if(response.code() == 204) {
CollaboratorsFragment.refreshCollaborators = true; CollaboratorsFragment.refreshCollaborators = true;
Toasty.success(context, context.getString(R.string.removeCollaboratorToastText)); Toasty.success(context, context.getString(R.string.removeCollaboratorToastText));
((AddCollaboratorToRepositoryActivity) context).finish(); ((AddCollaboratorToRepositoryActivity) context).finish();
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(context); AlertDialogs.authorizationTokenRevokedDialog(context);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError)); Toasty.error(context, context.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
Toasty.warning(context, context.getString(R.string.apiNotFound)); Toasty.warning(context, context.getString(R.string.apiNotFound));
} }
else { else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getResources().getString(R.string.genericServerResponseError)); Toasty.error(context, context.getResources().getString(R.string.genericServerResponseError));
} }
}); });
} }
public static void addCollaborator(final Context context, String permission, String userName, RepositoryContext repository) { public static void addCollaborator(final Context context, String permission, String userName, RepositoryContext repository) {
AddCollaboratorOption permissionString = new AddCollaboratorOption(); AddCollaboratorOption permissionString = new AddCollaboratorOption();
permissionString.setPermission(permission); permissionString.setPermission(permission);
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoAddCollaborator(repository.getOwner(), repository.getName(), userName, permissionString);
.getApiInterface(context)
.repoAddCollaborator(repository.getOwner(), repository.getName(), userName, permissionString);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 204) { if(response.code() == 204) {
CollaboratorsFragment.refreshCollaborators = true; CollaboratorsFragment.refreshCollaborators = true;
Toasty.success(context, context.getString(R.string.addCollaboratorToastText)); Toasty.success(context, context.getString(R.string.addCollaboratorToastText));
((AddCollaboratorToRepositoryActivity) context).finish(); ((AddCollaboratorToRepositoryActivity) context).finish();
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(context); AlertDialogs.authorizationTokenRevokedDialog(context);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError)); Toasty.error(context, context.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
Toasty.warning(context, context.getString(R.string.apiNotFound)); Toasty.warning(context, context.getString(R.string.apiNotFound));
} }
else { else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getResources().getString(R.string.genericServerResponseError));
}
});
}
Toasty.error(context, context.getResources().getString(R.string.genericServerResponseError));
}
});
}
} }

View File

@ -3,11 +3,7 @@ package org.mian.gitnex.actions;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.Comment; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateIssueCommentOption;
import org.gitnex.tea4j.v2.models.EditIssueCommentOption;
import org.gitnex.tea4j.v2.models.EditIssueOption;
import org.gitnex.tea4j.v2.models.Issue;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.BaseActivity; import org.mian.gitnex.activities.BaseActivity;
import org.mian.gitnex.activities.IssueDetailActivity; import org.mian.gitnex.activities.IssueDetailActivity;
@ -35,10 +31,7 @@ public class IssueActions {
EditIssueCommentOption commentObj = new EditIssueCommentOption(); EditIssueCommentOption commentObj = new EditIssueCommentOption();
commentObj.setBody(comment); commentObj.setBody(comment);
Call<Comment> call = RetrofitClient Call<Comment> call = RetrofitClient.getApiInterface(context).issueEditComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) commentId, commentObj);
.getApiInterface(context)
.issueEditComment(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) commentId, commentObj);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -77,10 +70,7 @@ public class IssueActions {
EditIssueOption issueStatJson = new EditIssueOption(); EditIssueOption issueStatJson = new EditIssueOption();
issueStatJson.setState(issueState); issueStatJson.setState(issueState);
Call<Issue> call = RetrofitClient Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueEditIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), issueStatJson);
.getApiInterface(ctx)
.issueEditIssue(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) issue.getIssueIndex(), issueStatJson);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -113,8 +103,7 @@ public class IssueActions {
IssueDetailActivity.singleIssueUpdate = true; IssueDetailActivity.singleIssueUpdate = true;
((IssueDetailActivity) ctx).onResume(); ((IssueDetailActivity) ctx).onResume();
if(((Activity) ctx).getIntent().getStringExtra("openedFromLink") == null || if(((Activity) ctx).getIntent().getStringExtra("openedFromLink") == null || !((Activity) ctx).getIntent().getStringExtra("openedFromLink").equals("true")) {
!((Activity) ctx).getIntent().getStringExtra("openedFromLink").equals("true")) {
RepoDetailActivity.updateRepo = true; RepoDetailActivity.updateRepo = true;
} }
} }
@ -150,10 +139,8 @@ public class IssueActions {
Call<Void> call; Call<Void> call;
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx)
.getApiInterface(ctx) .issueAddSubscription(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName());
.issueAddSubscription(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -193,8 +180,8 @@ public class IssueActions {
Call<Void> call; Call<Void> call;
call = RetrofitClient.getApiInterface(ctx).issueDeleteSubscription(issue.getRepository().getOwner(), call = RetrofitClient.getApiInterface(ctx)
issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName()); .issueDeleteSubscription(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -237,10 +224,7 @@ public class IssueActions {
CreateIssueCommentOption issueComment = new CreateIssueCommentOption(); CreateIssueCommentOption issueComment = new CreateIssueCommentOption();
issueComment.setBody(comment); issueComment.setBody(comment);
Call<Comment> call = RetrofitClient Call<Comment> call = RetrofitClient.getApiInterface(context).issueCreateComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), issueComment);
.getApiInterface(context)
.issueCreateComment(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) issue.getIssueIndex(), issueComment);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -275,4 +259,5 @@ public class IssueActions {
return actionResult; return actionResult;
} }
} }

View File

@ -23,9 +23,7 @@ public class LabelsActions {
public static void getCurrentIssueLabels(Context ctx, String repoOwner, String repoName, int issueIndex, List<Integer> currentLabelsIds) { public static void getCurrentIssueLabels(Context ctx, String repoOwner, String repoName, int issueIndex, List<Integer> currentLabelsIds) {
Call<List<Label>> callSingleIssueLabels = RetrofitClient Call<List<Label>> callSingleIssueLabels = RetrofitClient.getApiInterface(ctx).issueGetLabels(repoOwner, repoName, (long) issueIndex);
.getApiInterface(ctx)
.issueGetLabels(repoOwner, repoName, (long) issueIndex);
callSingleIssueLabels.enqueue(new Callback<>() { callSingleIssueLabels.enqueue(new Callback<>() {
@ -59,11 +57,10 @@ public class LabelsActions {
}); });
} }
public static void getRepositoryLabels(Context ctx, String repoOwner, String repoName, List<Label> labelsList, MaterialAlertDialogBuilder materialAlertDialogBuilder, LabelsListAdapter labelsAdapter, CustomLabelsSelectionDialogBinding labelsBinding, ProgressBar progressBar) { public static void getRepositoryLabels(Context ctx, String repoOwner, String repoName, List<Label> labelsList, MaterialAlertDialogBuilder materialAlertDialogBuilder, LabelsListAdapter labelsAdapter,
CustomLabelsSelectionDialogBinding labelsBinding, ProgressBar progressBar) {
Call<List<Label>> call = RetrofitClient Call<List<Label>> call = RetrofitClient.getApiInterface(ctx).issueListLabels(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.issueListLabels(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -80,9 +77,7 @@ public class LabelsActions {
} }
// Load organization labels // Load organization labels
Call<List<Label>> callOrgLabels = RetrofitClient Call<List<Label>> callOrgLabels = RetrofitClient.getApiInterface(ctx).orgListLabels(repoOwner, null, null);
.getApiInterface(ctx)
.orgListLabels(repoOwner, null, null);
callOrgLabels.enqueue(new Callback<>() { callOrgLabels.enqueue(new Callback<>() {
@ -129,4 +124,5 @@ public class LabelsActions {
} }
}); });
} }
} }

View File

@ -32,9 +32,7 @@ public class MilestoneActions {
EditMilestoneOption milestoneStateJson = new EditMilestoneOption(); EditMilestoneOption milestoneStateJson = new EditMilestoneOption();
milestoneStateJson.setState(state); milestoneStateJson.setState(state);
Call<Milestone> call = RetrofitClient Call<Milestone> call = RetrofitClient.getApiInterface(ctx).issueEditMilestone(repository.getOwner(), repository.getName(), String.valueOf(milestoneId_), milestoneStateJson);
.getApiInterface(ctx)
.issueEditMilestone(repository.getOwner(), repository.getName(), String.valueOf(milestoneId_), milestoneStateJson);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {

View File

@ -17,9 +17,7 @@ import retrofit2.Response;
public class PullRequestActions { public class PullRequestActions {
public static void deleteHeadBranch(Context context, String repoOwner, String repoName, String headBranch, boolean showToasts) { public static void deleteHeadBranch(Context context, String repoOwner, String repoName, String headBranch, boolean showToasts) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoDeleteBranch(repoOwner, repoName, headBranch);
.getApiInterface(context)
.repoDeleteBranch(repoOwner, repoName, headBranch);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -79,8 +77,7 @@ public class PullRequestActions {
else { else {
strategy = "rebase"; strategy = "rebase";
} }
RetrofitClient.getApiInterface(context).repoUpdatePullRequest(repoOwner, repoName, Long.valueOf(index), strategy) RetrofitClient.getApiInterface(context).repoUpdatePullRequest(repoOwner, repoName, Long.valueOf(index), strategy).enqueue(new Callback<>() {
.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call call, @NonNull Response response) { public void onResponse(@NonNull Call call, @NonNull Response response) {
@ -108,4 +105,5 @@ public class PullRequestActions {
} }
}); });
} }
} }

View File

@ -18,177 +18,170 @@ import retrofit2.Callback;
public class RepositoryActions { public class RepositoryActions {
public static void starRepository(final Context context, RepositoryContext repository) { public static void starRepository(final Context context, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).userCurrentPutStar(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentPutStar(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 204) { if(response.code() == 204) {
MainActivity.reloadRepos = true; MainActivity.reloadRepos = true;
Toasty.success(context, context.getString(R.string.starRepositorySuccess)); Toasty.success(context, context.getString(R.string.starRepositorySuccess));
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(context); AlertDialogs.authorizationTokenRevokedDialog(context);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError)); Toasty.error(context, context.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
Toasty.warning(context, context.getString(R.string.apiNotFound)); Toasty.warning(context, context.getString(R.string.apiNotFound));
} }
else { else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getString(R.string.genericServerResponseError)); Toasty.error(context, context.getString(R.string.genericServerResponseError));
} }
}); });
} }
public static void unStarRepository(final Context context, RepositoryContext repository) { public static void unStarRepository(final Context context, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).userCurrentDeleteStar(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentDeleteStar(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 204) { if(response.code() == 204) {
MainActivity.reloadRepos = true; MainActivity.reloadRepos = true;
Toasty.success(context, context.getString(R.string.unStarRepositorySuccess)); Toasty.success(context, context.getString(R.string.unStarRepositorySuccess));
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(context); AlertDialogs.authorizationTokenRevokedDialog(context);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError)); Toasty.error(context, context.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
Toasty.warning(context, context.getString(R.string.apiNotFound)); Toasty.warning(context, context.getString(R.string.apiNotFound));
} }
else { else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getString(R.string.genericServerResponseError)); Toasty.error(context, context.getString(R.string.genericServerResponseError));
} }
}); });
} }
public static void watchRepository(final Context context, RepositoryContext repository) { public static void watchRepository(final Context context, RepositoryContext repository) {
Call<WatchInfo> call = RetrofitClient Call<WatchInfo> call = RetrofitClient.getApiInterface(context).userCurrentPutSubscription(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentPutSubscription(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<WatchInfo> call, @NonNull retrofit2.Response<WatchInfo> response) { public void onResponse(@NonNull Call<WatchInfo> call, @NonNull retrofit2.Response<WatchInfo> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 200) { if(response.code() == 200) {
Toasty.success(context, context.getString(R.string.watchRepositorySuccess)); Toasty.success(context, context.getString(R.string.watchRepositorySuccess));
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(context); AlertDialogs.authorizationTokenRevokedDialog(context);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError)); Toasty.error(context, context.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
Toasty.warning(context, context.getString(R.string.apiNotFound)); Toasty.warning(context, context.getString(R.string.apiNotFound));
} }
else { else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<WatchInfo> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<WatchInfo> call, @NonNull Throwable t) {
Toasty.error(context, context.getString(R.string.genericServerResponseError)); Toasty.error(context, context.getString(R.string.genericServerResponseError));
} }
}); });
} }
public static void unWatchRepository(final Context context, RepositoryContext repository) { public static void unWatchRepository(final Context context, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).userCurrentDeleteStar(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentDeleteStar(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
if(response.code() == 204) { if(response.code() == 204) {
Toasty.success(context, context.getString(R.string.unWatchRepositorySuccess)); Toasty.success(context, context.getString(R.string.unWatchRepositorySuccess));
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(context); AlertDialogs.authorizationTokenRevokedDialog(context);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError)); Toasty.error(context, context.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
Toasty.warning(context, context.getString(R.string.apiNotFound)); Toasty.warning(context, context.getString(R.string.apiNotFound));
} }
else { else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getString(R.string.genericServerResponseError));
}
});
}
Toasty.error(context, context.getString(R.string.genericServerResponseError));
}
});
}
} }

View File

@ -20,9 +20,7 @@ public class TeamActions {
public static void removeTeamMember(final Context context, String userName, int teamId) { public static void removeTeamMember(final Context context, String userName, int teamId) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgRemoveTeamMember((long) teamId, userName);
.getApiInterface(context)
.orgRemoveTeamMember((long) teamId, userName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -66,9 +64,7 @@ public class TeamActions {
public static void addTeamMember(final Context context, String userName, int teamId) { public static void addTeamMember(final Context context, String userName, int teamId) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgAddTeamMember((long) teamId, userName);
.getApiInterface(context)
.orgAddTeamMember((long) teamId, userName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -111,9 +107,7 @@ public class TeamActions {
public static void removeTeamRepo(final Context context, String orgName, int teamId, String repo) { public static void removeTeamRepo(final Context context, String orgName, int teamId, String repo) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgRemoveTeamRepository((long) teamId, orgName, repo);
.getApiInterface(context)
.orgRemoveTeamRepository((long) teamId, orgName, repo);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -158,9 +152,7 @@ public class TeamActions {
public static void addTeamRepo(final Context context, String orgName, int teamId, String repo) { public static void addTeamRepo(final Context context, String orgName, int teamId, String repo) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgAddTeamRepository((long) teamId, orgName, repo);
.getApiInterface(context)
.orgAddTeamRepository((long) teamId, orgName, repo);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -201,4 +193,5 @@ public class TeamActions {
} }
}); });
} }
} }

View File

@ -29,106 +29,104 @@ import retrofit2.Response;
public class AddCollaboratorToRepositoryActivity extends BaseActivity { public class AddCollaboratorToRepositoryActivity extends BaseActivity {
private ActivityAddCollaboratorToRepositoryBinding activityAddCollaboratorToRepositoryBinding; private ActivityAddCollaboratorToRepositoryBinding activityAddCollaboratorToRepositoryBinding;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private RepositoryContext repository; private RepositoryContext repository;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
activityAddCollaboratorToRepositoryBinding = ActivityAddCollaboratorToRepositoryBinding.inflate(getLayoutInflater()); activityAddCollaboratorToRepositoryBinding = ActivityAddCollaboratorToRepositoryBinding.inflate(getLayoutInflater());
setContentView(activityAddCollaboratorToRepositoryBinding.getRoot()); setContentView(activityAddCollaboratorToRepositoryBinding.getRoot());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.requestFocus(); activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch, InputMethodManager.SHOW_IMPLICIT);
initCloseListener(); initCloseListener();
activityAddCollaboratorToRepositoryBinding.close.setOnClickListener(onClickListener); activityAddCollaboratorToRepositoryBinding.close.setOnClickListener(onClickListener);
activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.setOnEditorActionListener((v, actionId, event) -> { activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEND) { if(actionId == EditorInfo.IME_ACTION_SEND) {
if(!Objects.requireNonNull(activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.getText()).toString().equals("")) { if(!Objects.requireNonNull(activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.getText()).toString().equals("")) {
activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.VISIBLE); activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.VISIBLE);
loadUserSearchList(activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.getText().toString()); loadUserSearchList(activityAddCollaboratorToRepositoryBinding.addCollaboratorSearch.getText().toString());
} }
} }
return false; return false;
}); });
} }
public void loadUserSearchList(String searchKeyword) { public void loadUserSearchList(String searchKeyword) {
Call<InlineResponse2001> call = RetrofitClient Call<InlineResponse2001> call = RetrofitClient.getApiInterface(ctx).userSearch(searchKeyword, null, 1, 10);
.getApiInterface(ctx)
.userSearch(searchKeyword, null, 1, 10);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<InlineResponse2001> call, @NonNull Response<InlineResponse2001> response) { public void onResponse(@NonNull Call<InlineResponse2001> call, @NonNull Response<InlineResponse2001> response) {
activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.GONE); activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.GONE);
if(response.isSuccessful()) { if(response.isSuccessful()) {
assert response.body() != null; assert response.body() != null;
getUsersList(response.body().getData(), ctx); getUsersList(response.body().getData(), ctx);
} }
else { else {
Toasty.error(ctx, ctx.getString(R.string.genericError)); Toasty.error(ctx, ctx.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<InlineResponse2001> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<InlineResponse2001> call, @NonNull Throwable t) {
Toasty.error(ctx, ctx.getString(R.string.genericServerResponseError)); Toasty.error(ctx, ctx.getString(R.string.genericServerResponseError));
} }
}); });
} }
private void getUsersList(List<User> dataList, Context context) { private void getUsersList(List<User> dataList, Context context) {
CollaboratorSearchAdapter adapter = new CollaboratorSearchAdapter(dataList, context, repository); CollaboratorSearchAdapter adapter = new CollaboratorSearchAdapter(dataList, context, repository);
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setHasFixedSize(true); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setHasFixedSize(true);
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setLayoutManager(new LinearLayoutManager(ctx)); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.addItemDecoration(dividerItemDecoration);
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.addItemDecoration(dividerItemDecoration);
activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.VISIBLE); activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.VISIBLE);
if(adapter.getItemCount() > 0) { if(adapter.getItemCount() > 0) {
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setAdapter(adapter); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setAdapter(adapter);
activityAddCollaboratorToRepositoryBinding.noData.setVisibility(View.GONE); activityAddCollaboratorToRepositoryBinding.noData.setVisibility(View.GONE);
} }
else { else {
activityAddCollaboratorToRepositoryBinding.noData.setVisibility(View.VISIBLE); activityAddCollaboratorToRepositoryBinding.noData.setVisibility(View.VISIBLE);
} }
activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.GONE); activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.GONE);
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -17,11 +17,7 @@ import org.mian.gitnex.database.api.BaseApi;
import org.mian.gitnex.database.api.UserAccountsApi; import org.mian.gitnex.database.api.UserAccountsApi;
import org.mian.gitnex.database.models.UserAccount; import org.mian.gitnex.database.models.UserAccount;
import org.mian.gitnex.databinding.ActivityAddNewAccountBinding; import org.mian.gitnex.databinding.ActivityAddNewAccountBinding;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.PathsHelper;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.UrlHelper;
import org.mian.gitnex.helpers.Version;
import org.mian.gitnex.structs.Protocol; import org.mian.gitnex.structs.Protocol;
import java.net.URI; import java.net.URI;
import java.util.Objects; import java.util.Objects;
@ -58,10 +54,11 @@ public class AddNewAccountActivity extends BaseActivity {
viewBinding.instanceUrl.setText(getIntent().getStringExtra("instanceUrl")); viewBinding.instanceUrl.setText(getIntent().getStringExtra("instanceUrl"));
viewBinding.loginToken.setText(getIntent().getStringExtra("token")); viewBinding.loginToken.setText(getIntent().getStringExtra("token"));
String scheme = getIntent().getStringExtra("scheme"); String scheme = getIntent().getStringExtra("scheme");
if(scheme != null && scheme.equals("http")) { if(scheme != null && scheme.equals("http")) {
viewBinding.protocolSpinner.setText(Protocol.HTTP.toString()); viewBinding.protocolSpinner.setText(Protocol.HTTP.toString());
spinnerSelectedValue = Protocol.HTTP.toString(); spinnerSelectedValue = Protocol.HTTP.toString();
} else { // default is https }
else { // default is https
viewBinding.protocolSpinner.setText(Protocol.HTTPS.toString()); viewBinding.protocolSpinner.setText(Protocol.HTTPS.toString());
spinnerSelectedValue = Protocol.HTTPS.toString(); spinnerSelectedValue = Protocol.HTTPS.toString();
} }
@ -114,8 +111,7 @@ public class AddNewAccountActivity extends BaseActivity {
URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET, "http")).toUri(); URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET, "http")).toUri();
URI instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(protocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")) URI instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(protocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")).toUri();
.toUri();
versionCheck(instanceUrl.toString(), loginToken); versionCheck(instanceUrl.toString(), loginToken);
serverPageLimitSettings(); serverPageLimitSettings();
@ -152,10 +148,8 @@ public class AddNewAccountActivity extends BaseActivity {
if(giteaVersion.less(getString(R.string.versionLow))) { if(giteaVersion.less(getString(R.string.versionLow))) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(getString(R.string.versionAlertDialogHeader))
.setTitle(getString(R.string.versionAlertDialogHeader)) .setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion())).setNeutralButton(getString(R.string.cancelButton), null)
.setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion()))
.setNeutralButton(getString(R.string.cancelButton), null)
.setPositiveButton(getString(R.string.textContinue), (dialog, which) -> { .setPositiveButton(getString(R.string.textContinue), (dialog, which) -> {
dialog.dismiss(); dialog.dismiss();
@ -290,4 +284,5 @@ public class AddNewAccountActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -70,7 +70,7 @@ public class AddNewTeamMemberActivity extends BaseActivity {
mRecyclerView.setHasFixedSize(true); mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(ctx)); mRecyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(dividerItemDecoration); mRecyclerView.addItemDecoration(dividerItemDecoration);
dataList = new ArrayList<>(); dataList = new ArrayList<>();

View File

@ -51,7 +51,7 @@ public class AddNewTeamRepoActivity extends BaseActivity {
addNewTeamRepositoryBinding.recyclerViewTeamRepos.setHasFixedSize(true); addNewTeamRepositoryBinding.recyclerViewTeamRepos.setHasFixedSize(true);
addNewTeamRepositoryBinding.recyclerViewTeamRepos.setLayoutManager(new LinearLayoutManager(ctx)); addNewTeamRepositoryBinding.recyclerViewTeamRepos.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(addNewTeamRepositoryBinding.recyclerViewTeamRepos.getContext(), DividerItemDecoration.VERTICAL); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(addNewTeamRepositoryBinding.recyclerViewTeamRepos.getContext(), DividerItemDecoration.VERTICAL);
addNewTeamRepositoryBinding.recyclerViewTeamRepos.addItemDecoration(dividerItemDecoration); addNewTeamRepositoryBinding.recyclerViewTeamRepos.addItemDecoration(dividerItemDecoration);
dataList = new ArrayList<>(); dataList = new ArrayList<>();
@ -105,4 +105,5 @@ public class AddNewTeamRepoActivity extends BaseActivity {
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -20,13 +20,11 @@ import org.mian.gitnex.viewmodels.AdminCronTasksViewModel;
public class AdminCronTasksActivity extends BaseActivity { public class AdminCronTasksActivity extends BaseActivity {
private final int PAGE = 1;
private AdminCronTasksViewModel adminCronTasksViewModel; private AdminCronTasksViewModel adminCronTasksViewModel;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private AdminCronTasksAdapter adapter; private AdminCronTasksAdapter adapter;
private ActivityAdminCronTasksBinding activityAdminCronTasksBinding; private ActivityAdminCronTasksBinding activityAdminCronTasksBinding;
private final int PAGE = 1;
private int resultLimit; private int resultLimit;
@Override @Override
@ -48,8 +46,7 @@ public class AdminCronTasksActivity extends BaseActivity {
activityAdminCronTasksBinding.recyclerView.setHasFixedSize(true); activityAdminCronTasksBinding.recyclerView.setHasFixedSize(true);
activityAdminCronTasksBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx)); activityAdminCronTasksBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminCronTasksBinding.recyclerView.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminCronTasksBinding.recyclerView.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
activityAdminCronTasksBinding.recyclerView.addItemDecoration(dividerItemDecoration); activityAdminCronTasksBinding.recyclerView.addItemDecoration(dividerItemDecoration);
activityAdminCronTasksBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { activityAdminCronTasksBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -83,4 +80,5 @@ public class AdminCronTasksActivity extends BaseActivity {
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -55,8 +55,7 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
activityAdminGetUsersBinding.recyclerView.setHasFixedSize(true); activityAdminGetUsersBinding.recyclerView.setHasFixedSize(true);
activityAdminGetUsersBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx)); activityAdminGetUsersBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminGetUsersBinding.recyclerView.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminGetUsersBinding.recyclerView.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
activityAdminGetUsersBinding.recyclerView.addItemDecoration(dividerItemDecoration); activityAdminGetUsersBinding.recyclerView.addItemDecoration(dividerItemDecoration);
activityAdminGetUsersBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { activityAdminGetUsersBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -68,7 +67,7 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
}, 50)); }, 50));
fetchDataAsync(); fetchDataAsync();
}; }
private void fetchDataAsync() { private void fetchDataAsync() {
@ -109,77 +108,80 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
}); });
} }
@Override @Override
public boolean onCreateOptionsMenu(final Menu menu) { public boolean onCreateOptionsMenu(final Menu menu) {
final MenuInflater inflater = getMenuInflater(); final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.generic_nav_dotted_menu, menu); inflater.inflate(R.menu.generic_nav_dotted_menu, menu);
new Handler(Looper.getMainLooper()).postDelayed(() -> { new Handler(Looper.getMainLooper()).postDelayed(() -> {
if(searchFilter) { if(searchFilter) {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
inflater.inflate(R.menu.search_menu, menu); inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search); MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView(); SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE); searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
if(!connToInternet) { if(!connToInternet) {
return; return;
} }
searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener() { searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener() {
@Override @Override
public boolean onQueryTextSubmit(String query) { return true; } public boolean onQueryTextSubmit(String query) {
return true;
}
@Override @Override
public boolean onQueryTextChange(String newText) { public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText); adapter.getFilter().filter(newText);
return false; return false;
} }
}); });
} }
}, 500); }, 500);
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); int id = item.getItemId();
if(id == android.R.id.home) { if(id == android.R.id.home) {
finish(); finish();
return true; return true;
} }
else if(id == R.id.genericMenu) { else if(id == R.id.genericMenu) {
BottomSheetAdminUsersFragment bottomSheet = new BottomSheetAdminUsersFragment(); BottomSheetAdminUsersFragment bottomSheet = new BottomSheetAdminUsersFragment();
bottomSheet.show(getSupportFragmentManager(), "usersBottomSheet"); bottomSheet.show(getSupportFragmentManager(), "usersBottomSheet");
return true; return true;
} }
else { else {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
@Override @Override
public void onButtonClicked(String text) { public void onButtonClicked(String text) {
if("newUser".equals(text)) { if("newUser".equals(text)) {
startActivity(new Intent(AdminGetUsersActivity.this, CreateNewUserActivity.class)); startActivity(new Intent(AdminGetUsersActivity.this, CreateNewUserActivity.class));
} }
} }
private void initCloseListener() {
onClickListener = view -> finish();
}
private void initCloseListener() {
onClickListener = view -> finish();
}
} }

View File

@ -55,8 +55,7 @@ public class AdminUnadoptedReposActivity extends BaseActivity {
binding.recyclerView.setHasFixedSize(true); binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx)); binding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(binding.recyclerView.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(binding.recyclerView.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
binding.recyclerView.addItemDecoration(dividerItemDecoration); binding.recyclerView.addItemDecoration(dividerItemDecoration);
binding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { binding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -112,4 +111,5 @@ public class AdminUnadoptedReposActivity extends BaseActivity {
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -45,12 +45,7 @@ public abstract class BaseActivity extends AppCompatActivity {
break; break;
case 2: case 2:
if(TimeHelper.timeBetweenHours( if(TimeHelper.timeBetweenHours(tinyDB.getInt("darkThemeTimeHour", 18), tinyDB.getInt("lightThemeTimeHour", 6), tinyDB.getInt("darkThemeTimeMinute", 0), tinyDB.getInt("lightThemeTimeMinute", 0))) {
tinyDB.getInt("darkThemeTimeHour", 18),
tinyDB.getInt("lightThemeTimeHour", 6),
tinyDB.getInt("darkThemeTimeMinute", 0),
tinyDB.getInt("lightThemeTimeMinute", 0))
) {
setTheme(R.style.AppTheme); setTheme(R.style.AppTheme);
} }
@ -64,12 +59,7 @@ public abstract class BaseActivity extends AppCompatActivity {
setTheme(R.style.AppThemeRetro); setTheme(R.style.AppThemeRetro);
break; break;
case 4: case 4:
if(TimeHelper.timeBetweenHours( if(TimeHelper.timeBetweenHours(tinyDB.getInt("darkThemeTimeHour", 18), tinyDB.getInt("lightThemeTimeHour", 6), tinyDB.getInt("darkThemeTimeMinute", 0), tinyDB.getInt("lightThemeTimeMinute", 0))) {
tinyDB.getInt("darkThemeTimeHour", 18),
tinyDB.getInt("lightThemeTimeHour", 6),
tinyDB.getInt("darkThemeTimeMinute", 0),
tinyDB.getInt("lightThemeTimeMinute", 0))
) {
setTheme(R.style.AppTheme); setTheme(R.style.AppTheme);
} }
@ -91,7 +81,7 @@ public abstract class BaseActivity extends AppCompatActivity {
} }
String locale = tinyDB.getString("locale"); String locale = tinyDB.getString("locale");
if (locale.isEmpty()) { if(locale.isEmpty()) {
AppUtil.setAppLocale(getResources(), Locale.getDefault().getLanguage()); AppUtil.setAppLocale(getResources(), Locale.getDefault().getLanguage());
} }
else { else {
@ -127,15 +117,14 @@ public abstract class BaseActivity extends AppCompatActivity {
} }
// Authentication failed, close the app // Authentication failed, close the app
@Override public void onAuthenticationFailed() { @Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed(); super.onAuthenticationFailed();
} }
}); });
BiometricPrompt.PromptInfo biometricPromptBuilder = new BiometricPrompt.PromptInfo.Builder() BiometricPrompt.PromptInfo biometricPromptBuilder = new BiometricPrompt.PromptInfo.Builder().setTitle(getString(R.string.biometricAuthTitle)).setSubtitle(getString(R.string.biometricAuthSubTitle))
.setTitle(getString(R.string.biometricAuthTitle))
.setSubtitle(getString(R.string.biometricAuthSubTitle))
.setNegativeButtonText(getString(R.string.cancelButton)).build(); .setNegativeButtonText(getString(R.string.cancelButton)).build();
biometricPrompt.authenticate(biometricPromptBuilder); biometricPrompt.authenticate(biometricPromptBuilder);
@ -146,6 +135,7 @@ public abstract class BaseActivity extends AppCompatActivity {
public AccountContext getAccount() { public AccountContext getAccount() {
return ((MainApplication) getApplication()).currentAccount; return ((MainApplication) getApplication()).currentAccount;
} }
} }

View File

@ -10,11 +10,7 @@ import com.amrdeveloper.codeview.Code;
import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.EnumUtils;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.databinding.ActivityCodeEditorBinding; import org.mian.gitnex.databinding.ActivityCodeEditorBinding;
import org.mian.gitnex.helpers.codeeditor.CustomCodeViewAdapter; import org.mian.gitnex.helpers.codeeditor.*;
import org.mian.gitnex.helpers.codeeditor.LanguageManager;
import org.mian.gitnex.helpers.codeeditor.LanguageName;
import org.mian.gitnex.helpers.codeeditor.SourcePositionListener;
import org.mian.gitnex.helpers.codeeditor.ThemeName;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -26,10 +22,10 @@ import java.util.Map;
public class CodeEditorActivity extends BaseActivity { public class CodeEditorActivity extends BaseActivity {
private final ThemeName currentTheme = ThemeName.FIVE_COLOR;
private ActivityCodeEditorBinding binding; private ActivityCodeEditorBinding binding;
private LanguageManager languageManager; private LanguageManager languageManager;
private LanguageName currentLanguage = LanguageName.UNKNOWN; private LanguageName currentLanguage = LanguageName.UNKNOWN;
private final ThemeName currentTheme = ThemeName.FIVE_COLOR;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -105,7 +101,7 @@ public class CodeEditorActivity extends BaseActivity {
private void configLanguageAutoComplete() { private void configLanguageAutoComplete() {
boolean useModernAutoCompleteAdapter = true; boolean useModernAutoCompleteAdapter = true;
if (useModernAutoCompleteAdapter) { if(useModernAutoCompleteAdapter) {
List<Code> codeList = languageManager.getLanguageCodeList(currentLanguage); List<Code> codeList = languageManager.getLanguageCodeList(currentLanguage);
CustomCodeViewAdapter adapter = new CustomCodeViewAdapter(this, codeList); CustomCodeViewAdapter adapter = new CustomCodeViewAdapter(this, codeList);
@ -146,4 +142,5 @@ public class CodeEditorActivity extends BaseActivity {
binding.sourcePosition.setText(getString(R.string.sourcePosition, line, column)); binding.sourcePosition.setText(getString(R.string.sourcePosition, line, column));
}); });
} }
} }

View File

@ -29,20 +29,15 @@ public class CommitDetailActivity extends BaseActivity {
@Override @Override
public void handleOnBackPressed() { public void handleOnBackPressed() {
if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) { if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) {
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction() }
.replace(R.id.fragment_container, fragment) else {
.commit();
} else {
finish(); finish();
} }
} }
}); });
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
} }

View File

@ -38,17 +38,16 @@ import retrofit2.Response;
public class CommitsActivity extends BaseActivity { public class CommitsActivity extends BaseActivity {
private final String TAG = "CommitsActivity";
public RepositoryContext repository;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private TextView noData; private TextView noData;
private ProgressBar progressBar; private ProgressBar progressBar;
private final String TAG = "CommitsActivity";
private int resultLimit; private int resultLimit;
private int pageSize = 1; private int pageSize = 1;
private RecyclerView recyclerView; private RecyclerView recyclerView;
private List<Commit> commitsList; private List<Commit> commitsList;
private CommitsAdapter adapter; private CommitsAdapter adapter;
public RepositoryContext repository;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {

View File

@ -15,12 +15,7 @@ import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts; import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateFileOptions;
import org.gitnex.tea4j.v2.models.DeleteFileOptions;
import org.gitnex.tea4j.v2.models.FileDeleteResponse;
import org.gitnex.tea4j.v2.models.FileResponse;
import org.gitnex.tea4j.v2.models.UpdateFileOptions;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.ActivityCreateFileBinding; import org.mian.gitnex.databinding.ActivityCreateFileBinding;
@ -41,98 +36,98 @@ import retrofit2.Callback;
public class CreateFileActivity extends BaseActivity { public class CreateFileActivity extends BaseActivity {
private ActivityCreateFileBinding binding;
public static final int FILE_ACTION_CREATE = 0; public static final int FILE_ACTION_CREATE = 0;
public static final int FILE_ACTION_DELETE = 1; public static final int FILE_ACTION_DELETE = 1;
public static final int FILE_ACTION_EDIT = 2; public static final int FILE_ACTION_EDIT = 2;
private final List<String> branches = new ArrayList<>();
private ActivityCreateFileBinding binding;
ActivityResultLauncher<Intent> codeEditorActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
assert data != null;
binding.newFileContent.setText(data.getStringExtra("fileContentFromActivity"));
}
});
private int fileAction = FILE_ACTION_CREATE; private int fileAction = FILE_ACTION_CREATE;
private String filePath; private String filePath;
private String fileSha; private String fileSha;
private final List<String> branches = new ArrayList<>();
private RepositoryContext repository; private RepositoryContext repository;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
binding = ActivityCreateFileBinding.inflate(getLayoutInflater()); binding = ActivityCreateFileBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot()); setContentView(binding.getRoot());
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
TextView toolbarTitle = binding.toolbarTitle; TextView toolbarTitle = binding.toolbarTitle;
binding.newFileName.requestFocus(); binding.newFileName.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
assert inputMethodManager != null; assert inputMethodManager != null;
inputMethodManager.showSoftInput(binding.newFileName, InputMethodManager.SHOW_IMPLICIT); inputMethodManager.showSoftInput(binding.newFileName, InputMethodManager.SHOW_IMPLICIT);
binding.close.setOnClickListener(view -> finish()); binding.close.setOnClickListener(view -> finish());
binding.newFileContent.setOnTouchListener((touchView, motionEvent) -> { binding.newFileContent.setOnTouchListener((touchView, motionEvent) -> {
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
(motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
return false; return false;
}); });
if(getIntent().getStringExtra("filePath") != null && getIntent().getIntExtra("fileAction", FILE_ACTION_DELETE) == FILE_ACTION_DELETE) { if(getIntent().getStringExtra("filePath") != null && getIntent().getIntExtra("fileAction", FILE_ACTION_DELETE) == FILE_ACTION_DELETE) {
fileAction = getIntent().getIntExtra("fileAction", FILE_ACTION_DELETE); fileAction = getIntent().getIntExtra("fileAction", FILE_ACTION_DELETE);
filePath = getIntent().getStringExtra("filePath"); filePath = getIntent().getStringExtra("filePath");
fileSha = getIntent().getStringExtra("fileSha"); fileSha = getIntent().getStringExtra("fileSha");
toolbarTitle.setText(getString(R.string.deleteGenericTitle, filePath)); toolbarTitle.setText(getString(R.string.deleteGenericTitle, filePath));
binding.newFileCreate.setText(R.string.deleteFile); binding.newFileCreate.setText(R.string.deleteFile);
binding.newFileNameLayout.setVisibility(View.GONE); binding.newFileNameLayout.setVisibility(View.GONE);
binding.newFileContentLayout.setVisibility(View.GONE); binding.newFileContentLayout.setVisibility(View.GONE);
} }
if(getIntent().getStringExtra("filePath") != null && getIntent().getIntExtra("fileAction", FILE_ACTION_EDIT) == FILE_ACTION_EDIT) { if(getIntent().getStringExtra("filePath") != null && getIntent().getIntExtra("fileAction", FILE_ACTION_EDIT) == FILE_ACTION_EDIT) {
fileAction = getIntent().getIntExtra("fileAction", FILE_ACTION_EDIT); fileAction = getIntent().getIntExtra("fileAction", FILE_ACTION_EDIT);
filePath = getIntent().getStringExtra("filePath"); filePath = getIntent().getStringExtra("filePath");
fileSha = getIntent().getStringExtra("fileSha"); fileSha = getIntent().getStringExtra("fileSha");
toolbarTitle.setText(getString(R.string.editFileText, filePath)); toolbarTitle.setText(getString(R.string.editFileText, filePath));
binding.newFileCreate.setText(R.string.editFile); binding.newFileCreate.setText(R.string.editFile);
binding.newFileName.setText(filePath); binding.newFileName.setText(filePath);
binding.newFileName.setEnabled(false); binding.newFileName.setEnabled(false);
binding.newFileName.setFocusable(false); binding.newFileName.setFocusable(false);
binding.newFileContent.setText(getIntent().getStringExtra("fileContents")); binding.newFileContent.setText(getIntent().getStringExtra("fileContents"));
} }
getBranches(repository.getOwner(), repository.getName()); getBranches(repository.getOwner(), repository.getName());
disableProcessButton(); disableProcessButton();
binding.openCodeEditor.setOnClickListener(v -> binding.openCodeEditor.setOnClickListener(
launchCodeEditorActivityForResult(Objects.requireNonNull(binding.newFileContent.getText()).toString(), FilenameUtils.getExtension(String.valueOf(binding.newFileName.getText()))) v -> launchCodeEditorActivityForResult(Objects.requireNonNull(binding.newFileContent.getText()).toString(), FilenameUtils.getExtension(String.valueOf(binding.newFileName.getText()))));
);
NetworkStatusObserver networkStatusObserver = NetworkStatusObserver.getInstance(ctx); NetworkStatusObserver networkStatusObserver = NetworkStatusObserver.getInstance(ctx);
networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> binding.newFileCreate.setEnabled(hasNetworkConnection))); networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> binding.newFileCreate.setEnabled(hasNetworkConnection)));
binding.newFileCreate.setOnClickListener(v -> processNewFile()); binding.newFileCreate.setOnClickListener(v -> processNewFile());
} }
public void launchCodeEditorActivityForResult(String fileContent, String fileExtension) { public void launchCodeEditorActivityForResult(String fileContent, String fileExtension) {
Intent intent = new Intent(this, CodeEditorActivity.class); Intent intent = new Intent(this, CodeEditorActivity.class);
@ -141,63 +136,54 @@ public class CreateFileActivity extends BaseActivity {
codeEditorActivityResultLauncher.launch(intent); codeEditorActivityResultLauncher.launch(intent);
} }
ActivityResultLauncher<Intent> codeEditorActivityResultLauncher = registerForActivityResult( private void processNewFile() {
new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
assert data != null;
binding.newFileContent.setText(data.getStringExtra("fileContentFromActivity"));
}
});
private void processNewFile() { String newFileName = binding.newFileName.getText() != null ? binding.newFileName.getText().toString() : "";
String newFileContent = binding.newFileContent.getText() != null ? binding.newFileContent.getText().toString() : "";
String newFileBranchName = binding.newFileBranches.getText() != null ? binding.newFileBranches.getText().toString() : "";
String newFileCommitMessage = binding.newFileCommitMessage.getText() != null ? binding.newFileCommitMessage.getText().toString() : "";
String newFileName = binding.newFileName.getText() != null ? binding.newFileName.getText().toString() : ""; if(!AppUtil.hasNetworkConnection(appCtx)) {
String newFileContent = binding.newFileContent.getText() != null ? binding.newFileContent.getText().toString() : ""; Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
String newFileBranchName = binding.newFileBranches.getText() != null ? binding.newFileBranches.getText().toString() : ""; return;
String newFileCommitMessage = binding.newFileCommitMessage.getText() != null ? binding.newFileCommitMessage.getText().toString() : ""; }
if(!AppUtil.hasNetworkConnection(appCtx)) { if(((newFileName.isEmpty() || newFileContent.isEmpty()) && fileAction != FILE_ACTION_DELETE) || newFileCommitMessage.isEmpty()) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getString(R.string.newFileRequiredFields));
return; return;
} }
if(((newFileName.isEmpty() || newFileContent.isEmpty()) && fileAction != FILE_ACTION_DELETE) || newFileCommitMessage.isEmpty()) { if(!AppUtil.checkStringsWithDash(newFileBranchName)) {
Toasty.error(ctx, getString(R.string.newFileRequiredFields)); Toasty.error(ctx, getString(R.string.newFileInvalidBranchName));
return; return;
} }
if(!AppUtil.checkStringsWithDash(newFileBranchName)) { if(newFileCommitMessage.length() > 255) {
Toasty.error(ctx, getString(R.string.newFileInvalidBranchName)); Toasty.warning(ctx, getString(R.string.newFileCommitMessageError));
return; return;
} }
if(newFileCommitMessage.length() > 255) { disableProcessButton();
Toasty.warning(ctx, getString(R.string.newFileCommitMessageError));
return;
}
disableProcessButton(); switch(fileAction) {
switch(fileAction) { case FILE_ACTION_CREATE:
createNewFile(repository.getOwner(), repository.getName(), newFileName, AppUtil.encodeBase64(newFileContent), newFileCommitMessage, newFileBranchName);
break;
case FILE_ACTION_CREATE: case FILE_ACTION_DELETE:
createNewFile(repository.getOwner(), repository.getName(), newFileName, AppUtil.encodeBase64(newFileContent), newFileCommitMessage, newFileBranchName); deleteFile(repository.getOwner(), repository.getName(), filePath, newFileCommitMessage, newFileBranchName, fileSha);
break; break;
case FILE_ACTION_DELETE: case FILE_ACTION_EDIT:
deleteFile(repository.getOwner(), repository.getName(), filePath, newFileCommitMessage, newFileBranchName, fileSha); editFile(repository.getOwner(), repository.getName(), filePath, AppUtil.encodeBase64(newFileContent), newFileCommitMessage, newFileBranchName, fileSha);
break; break;
}
}
case FILE_ACTION_EDIT: private void createNewFile(String repoOwner, String repoName, String fileName, String fileContent, String fileCommitMessage, String branchName) {
editFile(repository.getOwner(), repository.getName(), filePath, AppUtil.encodeBase64(newFileContent), newFileCommitMessage, newFileBranchName, fileSha);
break;
}
}
private void createNewFile(String repoOwner, String repoName, String fileName, String fileContent, String fileCommitMessage, String branchName) { CreateFileOptions createNewFileJsonStr = new CreateFileOptions();
CreateFileOptions createNewFileJsonStr = new CreateFileOptions();
createNewFileJsonStr.setContent(fileContent); createNewFileJsonStr.setContent(fileContent);
createNewFileJsonStr.setMessage(fileCommitMessage); createNewFileJsonStr.setMessage(fileCommitMessage);
@ -208,56 +194,54 @@ public class CreateFileActivity extends BaseActivity {
createNewFileJsonStr.setNewBranch(branchName); createNewFileJsonStr.setNewBranch(branchName);
} }
Call<FileResponse> call = RetrofitClient Call<FileResponse> call = RetrofitClient.getApiInterface(ctx).repoCreateFile(createNewFileJsonStr, repoOwner, repoName, fileName);
.getApiInterface(ctx)
.repoCreateFile(createNewFileJsonStr, repoOwner, repoName, fileName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<FileResponse> call, @NonNull retrofit2.Response<FileResponse> response) { public void onResponse(@NonNull Call<FileResponse> call, @NonNull retrofit2.Response<FileResponse> response) {
switch(response.code()) { switch(response.code()) {
case 201: case 201:
enableProcessButton(); enableProcessButton();
Toasty.success(ctx, getString(R.string.newFileSuccessMessage)); Toasty.success(ctx, getString(R.string.newFileSuccessMessage));
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("fileModified", true); result.putExtra("fileModified", true);
result.putExtra("fileAction", fileAction); result.putExtra("fileAction", fileAction);
setResult(200, result); setResult(200, result);
finish(); finish();
break; break;
case 401: case 401:
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
break; break;
case 404: case 404:
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, getString(R.string.apiNotFound)); Toasty.warning(ctx, getString(R.string.apiNotFound));
break; break;
default: default:
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
break; break;
} }
} }
@Override @Override
public void onFailure(@NonNull Call<FileResponse> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<FileResponse> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void deleteFile(String repoOwner, String repoName, String fileName, String fileCommitMessage, String branchName, String fileSha) { private void deleteFile(String repoOwner, String repoName, String fileName, String fileCommitMessage, String branchName, String fileSha) {
DeleteFileOptions deleteFileJsonStr = new DeleteFileOptions(); DeleteFileOptions deleteFileJsonStr = new DeleteFileOptions();
deleteFileJsonStr.setMessage(fileCommitMessage); deleteFileJsonStr.setMessage(fileCommitMessage);
deleteFileJsonStr.setSha(fileSha); deleteFileJsonStr.setSha(fileSha);
@ -268,9 +252,7 @@ public class CreateFileActivity extends BaseActivity {
deleteFileJsonStr.setNewBranch(branchName); deleteFileJsonStr.setNewBranch(branchName);
} }
Call<FileDeleteResponse> call = RetrofitClient Call<FileDeleteResponse> call = RetrofitClient.getApiInterface(ctx).repoDeleteFileWithBody(repoOwner, repoName, fileName, deleteFileJsonStr);
.getApiInterface(ctx)
.repoDeleteFileWithBody(repoOwner, repoName, fileName, deleteFileJsonStr);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -329,9 +311,7 @@ public class CreateFileActivity extends BaseActivity {
editFileJsonStr.setNewBranch(branchName); editFileJsonStr.setNewBranch(branchName);
} }
Call<FileResponse> call = RetrofitClient Call<FileResponse> call = RetrofitClient.getApiInterface(ctx).repoUpdateFile(editFileJsonStr, repoOwner, repoName, fileName);
.getApiInterface(ctx)
.repoUpdateFile(editFileJsonStr, repoOwner, repoName, fileName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -376,46 +356,50 @@ public class CreateFileActivity extends BaseActivity {
}); });
} }
private void getBranches(String repoOwner, String repoName) { private void getBranches(String repoOwner, String repoName) {
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.repoListBranches(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<List<Branch>> call, @NonNull retrofit2.Response<List<Branch>> response) { public void onResponse(@NonNull Call<List<Branch>> call, @NonNull retrofit2.Response<List<Branch>> response) {
if(response.code() == 200) { if(response.code() == 200) {
assert response.body() != null; assert response.body() != null;
for(Branch branch : response.body()) for(Branch branch : response.body())
branches.add(branch.getName()); branches.add(branch.getName());
ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateFileActivity.this, R.layout.list_spinner_items, branches); ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateFileActivity.this, R.layout.list_spinner_items, branches);
binding.newFileBranches.setAdapter(adapter); binding.newFileBranches.setAdapter(adapter);
binding.newFileBranches.setText(repository.getBranchRef(), false); binding.newFileBranches.setText(repository.getBranchRef(), false);
enableProcessButton(); enableProcessButton();
} }
} }
@Override @Override
public void onFailure(@NonNull Call<List<Branch>> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<List<Branch>> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
} }
}); });
} }
private void disableProcessButton() { binding.newFileCreate.setEnabled(false); } private void disableProcessButton() {
private void enableProcessButton() { binding.newFileCreate.setEnabled(true); } binding.newFileCreate.setEnabled(false);
}
private void enableProcessButton() {
binding.newFileCreate.setEnabled(true);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -12,11 +12,7 @@ import android.widget.ArrayAdapter;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import org.gitnex.tea4j.v2.models.CreateIssueOption; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Issue;
import org.gitnex.tea4j.v2.models.Label;
import org.gitnex.tea4j.v2.models.Milestone;
import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.actions.AssigneesActions; import org.mian.gitnex.actions.AssigneesActions;
import org.mian.gitnex.actions.LabelsActions; import org.mian.gitnex.actions.LabelsActions;
@ -32,12 +28,7 @@ import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Constants; import org.mian.gitnex.helpers.Constants;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -47,93 +38,89 @@ import retrofit2.Callback;
public class CreateIssueActivity extends BaseActivity implements View.OnClickListener, LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener { public class CreateIssueActivity extends BaseActivity implements View.OnClickListener, LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener {
private final List<Label> labelsList = new ArrayList<>();
private final LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private final List<User> assigneesList = new ArrayList<>();
private ActivityCreateIssueBinding viewBinding; private ActivityCreateIssueBinding viewBinding;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private int milestoneId; private int milestoneId;
private Date currentDate = null; private Date currentDate = null;
private RepositoryContext repository; private RepositoryContext repository;
private LabelsListAdapter labelsAdapter; private LabelsListAdapter labelsAdapter;
private AssigneesListAdapter assigneesAdapter; private AssigneesListAdapter assigneesAdapter;
private MaterialAlertDialogBuilder materialAlertDialogBuilder; private MaterialAlertDialogBuilder materialAlertDialogBuilder;
private List<Integer> labelsIds = new ArrayList<>(); private List<Integer> labelsIds = new ArrayList<>();
private final List<Label> labelsList = new ArrayList<>();
private final LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private final List<User> assigneesList = new ArrayList<>();
private List<String> assigneesListData = new ArrayList<>(); private List<String> assigneesListData = new ArrayList<>();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
viewBinding = ActivityCreateIssueBinding.inflate(getLayoutInflater()); viewBinding = ActivityCreateIssueBinding.inflate(getLayoutInflater());
setContentView(viewBinding.getRoot()); setContentView(viewBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx, R.style.ThemeOverlay_Material3_Dialog_Alert); materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx, R.style.ThemeOverlay_Material3_Dialog_Alert);
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
int resultLimit = Constants.getCurrentResultLimit(ctx); int resultLimit = Constants.getCurrentResultLimit(ctx);
viewBinding.newIssueTitle.requestFocus(); viewBinding.newIssueTitle.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(viewBinding.newIssueTitle, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(viewBinding.newIssueTitle, InputMethodManager.SHOW_IMPLICIT);
viewBinding.newIssueDescription.setOnTouchListener((touchView, motionEvent) -> { viewBinding.newIssueDescription.setOnTouchListener((touchView, motionEvent) -> {
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) { if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
return false; return false;
}); });
labelsAdapter = new LabelsListAdapter(labelsList, CreateIssueActivity.this, labelsIds); labelsAdapter = new LabelsListAdapter(labelsList, CreateIssueActivity.this, labelsIds);
assigneesAdapter = new AssigneesListAdapter(ctx, assigneesList, CreateIssueActivity.this, assigneesListData); assigneesAdapter = new AssigneesListAdapter(ctx, assigneesList, CreateIssueActivity.this, assigneesListData);
initCloseListener(); initCloseListener();
viewBinding.close.setOnClickListener(onClickListener); viewBinding.close.setOnClickListener(onClickListener);
viewBinding.newIssueAssigneesList.setOnClickListener(this); viewBinding.newIssueAssigneesList.setOnClickListener(this);
viewBinding.newIssueLabels.setOnClickListener(this); viewBinding.newIssueLabels.setOnClickListener(this);
viewBinding.newIssueDueDate.setOnClickListener(this); viewBinding.newIssueDueDate.setOnClickListener(this);
getMilestones(repository.getOwner(), repository.getName(), resultLimit); getMilestones(repository.getOwner(), repository.getName(), resultLimit);
disableProcessButton(); disableProcessButton();
viewBinding.newIssueLabels.setOnClickListener(newIssueLabels -> showLabels()); viewBinding.newIssueLabels.setOnClickListener(newIssueLabels -> showLabels());
viewBinding.newIssueAssigneesList.setOnClickListener(newIssueAssigneesList -> showAssignees()); viewBinding.newIssueAssigneesList.setOnClickListener(newIssueAssigneesList -> showAssignees());
if(!connToInternet) { if(!connToInternet) {
viewBinding.createNewIssueButton.setEnabled(false); viewBinding.createNewIssueButton.setEnabled(false);
} }
else { else {
viewBinding.createNewIssueButton.setOnClickListener(this); viewBinding.createNewIssueButton.setOnClickListener(this);
} }
if(!repository.getPermissions().isPush()) { if(!repository.getPermissions().isPush()) {
viewBinding.newIssueAssigneesListLayout.setVisibility(View.GONE); viewBinding.newIssueAssigneesListLayout.setVisibility(View.GONE);
viewBinding.newIssueMilestoneSpinnerLayout.setVisibility(View.GONE); viewBinding.newIssueMilestoneSpinnerLayout.setVisibility(View.GONE);
viewBinding.newIssueLabelsLayout.setVisibility(View.GONE); viewBinding.newIssueLabelsLayout.setVisibility(View.GONE);
viewBinding.newIssueDueDateLayout.setVisibility(View.GONE); viewBinding.newIssueDueDateLayout.setVisibility(View.GONE);
} }
} }
@Override @Override
public void assigneesInterface(List<String> data) { public void assigneesInterface(List<String> data) {
@ -160,23 +147,20 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate( CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = assigneesBinding.getRoot(); View view = assigneesBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
materialAlertDialogBuilder.setNeutralButton(R.string.close, null); materialAlertDialogBuilder.setNeutralButton(R.string.close, null);
AssigneesActions.getRepositoryAssignees(ctx, repository.getOwner(), repository.getName(), assigneesList, materialAlertDialogBuilder, assigneesAdapter, AssigneesActions.getRepositoryAssignees(ctx, repository.getOwner(), repository.getName(), assigneesList, materialAlertDialogBuilder, assigneesAdapter, assigneesBinding, viewBinding.progressBar);
assigneesBinding, viewBinding.progressBar);
} }
private void showLabels() { private void showLabels() {
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate( CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = labelsBinding.getRoot(); View view = labelsBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
@ -185,38 +169,38 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
LabelsActions.getRepositoryLabels(ctx, repository.getOwner(), repository.getName(), labelsList, materialAlertDialogBuilder, labelsAdapter, labelsBinding, viewBinding.progressBar); LabelsActions.getRepositoryLabels(ctx, repository.getOwner(), repository.getName(), labelsList, materialAlertDialogBuilder, labelsAdapter, labelsBinding, viewBinding.progressBar);
} }
private void processNewIssue() { private void processNewIssue() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
String newIssueTitleForm = Objects.requireNonNull(viewBinding.newIssueTitle.getText()).toString(); String newIssueTitleForm = Objects.requireNonNull(viewBinding.newIssueTitle.getText()).toString();
String newIssueDescriptionForm = Objects.requireNonNull(viewBinding.newIssueDescription.getText()).toString(); String newIssueDescriptionForm = Objects.requireNonNull(viewBinding.newIssueDescription.getText()).toString();
String newIssueDueDateForm = Objects.requireNonNull(viewBinding.newIssueDueDate.getText()).toString(); String newIssueDueDateForm = Objects.requireNonNull(viewBinding.newIssueDueDate.getText()).toString();
if(!connToInternet) { if(!connToInternet) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return; return;
} }
if (newIssueTitleForm.equals("")) { if(newIssueTitleForm.equals("")) {
Toasty.error(ctx, getString(R.string.issueTitleEmpty)); Toasty.error(ctx, getString(R.string.issueTitleEmpty));
return; return;
} }
disableProcessButton(); disableProcessButton();
createNewIssueFunc(repository.getOwner(), repository.getName(), newIssueDescriptionForm, milestoneId, newIssueTitleForm); createNewIssueFunc(repository.getOwner(), repository.getName(), newIssueDescriptionForm, milestoneId, newIssueTitleForm);
} }
private void createNewIssueFunc(String repoOwner, String repoName, String newIssueDescriptionForm, int newIssueMilestoneIdForm, String newIssueTitleForm) { private void createNewIssueFunc(String repoOwner, String repoName, String newIssueDescriptionForm, int newIssueMilestoneIdForm, String newIssueTitleForm) {
ArrayList<Long> labelIds = new ArrayList<>(); ArrayList<Long> labelIds = new ArrayList<>();
for(Integer i : labelsIds) { for(Integer i : labelsIds) {
labelIds.add((long) i); labelIds.add((long) i);
} }
CreateIssueOption createNewIssueJson = new CreateIssueOption(); CreateIssueOption createNewIssueJson = new CreateIssueOption();
createNewIssueJson.setBody(newIssueDescriptionForm); createNewIssueJson.setBody(newIssueDescriptionForm);
createNewIssueJson.setMilestone((long) newIssueMilestoneIdForm); createNewIssueJson.setMilestone((long) newIssueMilestoneIdForm);
createNewIssueJson.setDueDate(currentDate); createNewIssueJson.setDueDate(currentDate);
@ -224,150 +208,146 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
createNewIssueJson.setAssignees(assigneesListData); createNewIssueJson.setAssignees(assigneesListData);
createNewIssueJson.setLabels(labelIds); createNewIssueJson.setLabels(labelIds);
Call<Issue> call3 = RetrofitClient Call<Issue> call3 = RetrofitClient.getApiInterface(ctx).issueCreateIssue(repoOwner, repoName, createNewIssueJson);
.getApiInterface(ctx)
.issueCreateIssue(repoOwner, repoName, createNewIssueJson);
call3.enqueue(new Callback<>() { call3.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Issue> call, @NonNull retrofit2.Response<Issue> response2) { public void onResponse(@NonNull Call<Issue> call, @NonNull retrofit2.Response<Issue> response2) {
if(response2.code() == 201) { if(response2.code() == 201) {
IssuesFragment.resumeIssues = true; IssuesFragment.resumeIssues = true;
Toasty.success(ctx, getString(R.string.issueCreated)); Toasty.success(ctx, getString(R.string.issueCreated));
enableProcessButton(); enableProcessButton();
RepoDetailActivity.updateRepo = true; RepoDetailActivity.updateRepo = true;
MainActivity.reloadRepos = true; MainActivity.reloadRepos = true;
finish(); finish();
} }
else if(response2.code() == 401) { else if(response2.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
enableProcessButton(); enableProcessButton();
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Issue> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Issue> call, @NonNull Throwable t) {
Toasty.error(ctx, getString(R.string.genericServerResponseError)); Toasty.error(ctx, getString(R.string.genericServerResponseError));
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void getMilestones(String repoOwner, String repoName, int resultLimit) { private void getMilestones(String repoOwner, String repoName, int resultLimit) {
String msState = "open"; String msState = "open";
Call<List<Milestone>> call = RetrofitClient Call<List<Milestone>> call = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
.getApiInterface(ctx)
.issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<List<Milestone>> call, @NonNull retrofit2.Response<List<Milestone>> response) { public void onResponse(@NonNull Call<List<Milestone>> call, @NonNull retrofit2.Response<List<Milestone>> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 200) { if(response.code() == 200) {
List<Milestone> milestonesList_ = response.body(); List<Milestone> milestonesList_ = response.body();
Milestone ms = new Milestone(); Milestone ms = new Milestone();
ms.setId(0L); ms.setId(0L);
ms.setTitle(getString(R.string.issueCreatedNoMilestone)); ms.setTitle(getString(R.string.issueCreatedNoMilestone));
milestonesList.put(ms.getTitle(), ms); milestonesList.put(ms.getTitle(), ms);
assert milestonesList_ != null; assert milestonesList_ != null;
if(milestonesList_.size() > 0) { if(milestonesList_.size() > 0) {
for(Milestone milestone : milestonesList_) { for(Milestone milestone : milestonesList_) {
//Don't translate "open" is a enum //Don't translate "open" is a enum
if(milestone.getState().equals("open")) { if(milestone.getState().equals("open")) {
milestonesList.put(milestone.getTitle(), milestone); milestonesList.put(milestone.getTitle(), milestone);
} }
} }
} }
ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateIssueActivity.this, R.layout.list_spinner_items, new ArrayList<>(milestonesList.keySet())); ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateIssueActivity.this, R.layout.list_spinner_items, new ArrayList<>(milestonesList.keySet()));
viewBinding.newIssueMilestoneSpinner.setAdapter(adapter); viewBinding.newIssueMilestoneSpinner.setAdapter(adapter);
enableProcessButton(); enableProcessButton();
viewBinding.newIssueMilestoneSpinner.setOnItemClickListener((parent, view, position, id) -> { viewBinding.newIssueMilestoneSpinner.setOnItemClickListener((parent, view, position, id) -> {
if(position == 0) { if(position == 0) {
milestoneId = 0; milestoneId = 0;
} }
else if(view instanceof TextView) { else if(view instanceof TextView) {
milestoneId = Math.toIntExact(Objects.requireNonNull(milestonesList.get(((TextView) view).getText().toString())).getId()); milestoneId = Math.toIntExact(Objects.requireNonNull(milestonesList.get(((TextView) view).getText().toString())).getId());
} }
}); });
} }
} }
} }
@Override @Override
public void onFailure(@NonNull Call<List<Milestone>> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<List<Milestone>> call, @NonNull Throwable t) {
Toasty.error(ctx, getString(R.string.genericServerResponseError)); Toasty.error(ctx, getString(R.string.genericServerResponseError));
} }
}); });
} }
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (v == viewBinding.newIssueDueDate) { if(v == viewBinding.newIssueDueDate) {
final Calendar c = Calendar.getInstance(); final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
viewBinding.newIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); viewBinding.newIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
datePickerDialog.show(); datePickerDialog.show();
} }
else if(v == viewBinding.createNewIssueButton) { else if(v == viewBinding.createNewIssueButton) {
processNewIssue(); processNewIssue();
} }
} }
private void disableProcessButton() { private void disableProcessButton() {
viewBinding.createNewIssueButton.setEnabled(false); viewBinding.createNewIssueButton.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
viewBinding.createNewIssueButton.setEnabled(true); viewBinding.createNewIssueButton.setEnabled(true);
} }
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -35,333 +35,333 @@ public class CreateLabelActivity extends BaseActivity {
public static boolean refreshLabels = false; public static boolean refreshLabels = false;
private ActivityCreateLabelBinding activityCreateLabelBinding; private ActivityCreateLabelBinding activityCreateLabelBinding;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private RepositoryContext repository; private RepositoryContext repository;
private String labelColor = ""; private String labelColor = "";
private String labelColorDefault = ""; private final View.OnClickListener createLabelListener = v -> processCreateLabel();
private String labelColorDefault = "";
private final View.OnClickListener updateLabelListener = v -> processUpdateLabel();
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
activityCreateLabelBinding = ActivityCreateLabelBinding.inflate(getLayoutInflater()); activityCreateLabelBinding = ActivityCreateLabelBinding.inflate(getLayoutInflater());
setContentView(activityCreateLabelBinding.getRoot()); setContentView(activityCreateLabelBinding.getRoot());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
if(getIntent().getStringExtra("labelAction") != null && Objects.requireNonNull(getIntent().getStringExtra("labelAction")).equals("delete")) { if(getIntent().getStringExtra("labelAction") != null && Objects.requireNonNull(getIntent().getStringExtra("labelAction")).equals("delete")) {
deleteLabel(Integer.parseInt(Objects.requireNonNull(getIntent().getStringExtra("labelId")))); deleteLabel(Integer.parseInt(Objects.requireNonNull(getIntent().getStringExtra("labelId"))));
finish(); finish();
return; return;
} }
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
activityCreateLabelBinding.labelName.requestFocus(); activityCreateLabelBinding.labelName.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(activityCreateLabelBinding.labelName, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(activityCreateLabelBinding.labelName, InputMethodManager.SHOW_IMPLICIT);
final ColorPicker cp = new ColorPicker(CreateLabelActivity.this, 235, 113, 33); final ColorPicker cp = new ColorPicker(CreateLabelActivity.this, 235, 113, 33);
initCloseListener(); initCloseListener();
activityCreateLabelBinding.close.setOnClickListener(onClickListener); activityCreateLabelBinding.close.setOnClickListener(onClickListener);
activityCreateLabelBinding.colorPicker.setOnClickListener(v -> cp.show()); activityCreateLabelBinding.colorPicker.setOnClickListener(v -> cp.show());
cp.setCallback(color -> { cp.setCallback(color -> {
//Log.i("#Hex no alpha", String.format("#%06X", (0xFFFFFF & color))); //Log.i("#Hex no alpha", String.format("#%06X", (0xFFFFFF & color)));
activityCreateLabelBinding.colorPicker.setBackgroundColor(color); activityCreateLabelBinding.colorPicker.setBackgroundColor(color);
labelColor = String.format("#%06X", (0xFFFFFF & color)); labelColor = String.format("#%06X", (0xFFFFFF & color));
cp.dismiss(); cp.dismiss();
}); });
if(getIntent().getStringExtra("labelAction") != null && Objects.requireNonNull(getIntent().getStringExtra("labelAction")).equals("edit")) { if(getIntent().getStringExtra("labelAction") != null && Objects.requireNonNull(getIntent().getStringExtra("labelAction")).equals("edit")) {
activityCreateLabelBinding.labelName.setText(getIntent().getStringExtra("labelTitle")); activityCreateLabelBinding.labelName.setText(getIntent().getStringExtra("labelTitle"));
int labelColor_ = Color.parseColor("#" + getIntent().getStringExtra("labelColor")); int labelColor_ = Color.parseColor("#" + getIntent().getStringExtra("labelColor"));
activityCreateLabelBinding.colorPicker.setBackgroundColor(labelColor_); activityCreateLabelBinding.colorPicker.setBackgroundColor(labelColor_);
labelColorDefault = "#" + getIntent().getStringExtra("labelColor"); labelColorDefault = "#" + getIntent().getStringExtra("labelColor");
TextView toolbar_title = activityCreateLabelBinding.toolbarTitle; TextView toolbar_title = activityCreateLabelBinding.toolbarTitle;
toolbar_title.setText(getResources().getString(R.string.pageTitleLabelUpdate)); toolbar_title.setText(getResources().getString(R.string.pageTitleLabelUpdate));
activityCreateLabelBinding.createLabelButton.setText(getResources().getString(R.string.newUpdateButtonCopy)); activityCreateLabelBinding.createLabelButton.setText(getResources().getString(R.string.newUpdateButtonCopy));
activityCreateLabelBinding.createLabelButton.setOnClickListener(updateLabelListener); activityCreateLabelBinding.createLabelButton.setOnClickListener(updateLabelListener);
return; return;
} }
if(!connToInternet) { if(!connToInternet) {
activityCreateLabelBinding.createLabelButton.setEnabled(false); activityCreateLabelBinding.createLabelButton.setEnabled(false);
} }
else { else {
activityCreateLabelBinding.createLabelButton.setOnClickListener(createLabelListener); activityCreateLabelBinding.createLabelButton.setOnClickListener(createLabelListener);
} }
} }
private final View.OnClickListener createLabelListener = v -> processCreateLabel(); private void processUpdateLabel() {
private final View.OnClickListener updateLabelListener = v -> processUpdateLabel(); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
private void processUpdateLabel() { String updateLabelName = Objects.requireNonNull(activityCreateLabelBinding.labelName.getText()).toString();
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); String updateLabelColor;
if(labelColor.isEmpty()) {
String updateLabelName = Objects.requireNonNull(activityCreateLabelBinding.labelName.getText()).toString(); updateLabelColor = labelColorDefault;
}
else {
String updateLabelColor; updateLabelColor = labelColor;
if(labelColor.isEmpty()) { }
updateLabelColor = labelColorDefault; if(!connToInternet) {
}
else {
updateLabelColor = labelColor; Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
} return;
}
if(!connToInternet) { if(updateLabelName.equals("")) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getString(R.string.labelEmptyError));
return; return;
} }
if(updateLabelName.equals("")) { if(!AppUtil.checkStrings(updateLabelName)) {
Toasty.error(ctx, getString(R.string.labelEmptyError)); Toasty.error(ctx, getString(R.string.labelNameError));
return; return;
} }
if(!AppUtil.checkStrings(updateLabelName)) { disableProcessButton();
patchLabel(repository, updateLabelName, updateLabelColor, Integer.parseInt(Objects.requireNonNull(getIntent().getStringExtra("labelId"))));
}
Toasty.error(ctx, getString(R.string.labelNameError)); private void processCreateLabel() {
return;
}
disableProcessButton(); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
patchLabel(repository, updateLabelName, updateLabelColor, Integer.parseInt(
Objects.requireNonNull(getIntent().getStringExtra("labelId"))));
}
private void processCreateLabel() { String newLabelName = Objects.requireNonNull(activityCreateLabelBinding.labelName.getText()).toString();
String newLabelColor;
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); if(labelColor.isEmpty()) {
String newLabelName = Objects.requireNonNull(activityCreateLabelBinding.labelName.getText()).toString(); newLabelColor = String.format("#%06X", (0xFFFFFF & ContextCompat.getColor(ctx, R.color.releasePre)));
String newLabelColor; }
else {
if(labelColor.isEmpty()) { newLabelColor = labelColor;
}
newLabelColor = String.format("#%06X", (0xFFFFFF & ContextCompat.getColor(ctx, R.color.releasePre))); if(!connToInternet) {
}
else {
newLabelColor = labelColor; Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
} return;
}
if(!connToInternet) { if(newLabelName.equals("")) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getString(R.string.labelEmptyError));
return; return;
} }
if(newLabelName.equals("")) { if(!AppUtil.checkStrings(newLabelName)) {
Toasty.error(ctx, getString(R.string.labelEmptyError)); Toasty.error(ctx, getString(R.string.labelNameError));
return; return;
} }
if(!AppUtil.checkStrings(newLabelName)) { disableProcessButton();
createNewLabel(newLabelName, newLabelColor);
}
Toasty.error(ctx, getString(R.string.labelNameError)); private void createNewLabel(String newLabelName, String newLabelColor) {
return;
}
disableProcessButton(); CreateLabelOption createLabelFunc = new CreateLabelOption();
createNewLabel(newLabelName, newLabelColor);
}
private void createNewLabel(String newLabelName, String newLabelColor) {
CreateLabelOption createLabelFunc = new CreateLabelOption();
createLabelFunc.setColor(newLabelColor); createLabelFunc.setColor(newLabelColor);
createLabelFunc.setName(newLabelName); createLabelFunc.setName(newLabelName);
Call<Label> call; Call<Label> call;
if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) { if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) {
call = RetrofitClient.getApiInterface(ctx).orgCreateLabel(getIntent().getStringExtra("orgName"), createLabelFunc); call = RetrofitClient.getApiInterface(ctx).orgCreateLabel(getIntent().getStringExtra("orgName"), createLabelFunc);
} }
else if(repository != null) { else if(repository != null) {
call = RetrofitClient.getApiInterface(ctx).issueCreateLabel(repository.getOwner(), repository.getName(), createLabelFunc); call = RetrofitClient.getApiInterface(ctx).issueCreateLabel(repository.getOwner(), repository.getName(), createLabelFunc);
} else { }
else {
return; return;
} }
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Label> call, @NonNull retrofit2.Response<Label> response) { public void onResponse(@NonNull Call<Label> call, @NonNull retrofit2.Response<Label> response) {
if(response.code() == 201) { if(response.code() == 201) {
Toasty.success(ctx, getString(R.string.labelCreated)); Toasty.success(ctx, getString(R.string.labelCreated));
refreshLabels = true; refreshLabels = true;
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Label> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Label> call, @NonNull Throwable t) {
labelColor = ""; labelColor = "";
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void patchLabel(RepositoryContext repository, String updateLabelName, String updateLabelColor, int labelId) { private void patchLabel(RepositoryContext repository, String updateLabelName, String updateLabelColor, int labelId) {
EditLabelOption createLabelFunc = new EditLabelOption(); EditLabelOption createLabelFunc = new EditLabelOption();
createLabelFunc.setColor(updateLabelColor); createLabelFunc.setColor(updateLabelColor);
createLabelFunc.setName(updateLabelName); createLabelFunc.setName(updateLabelName);
Call<Label> call; Call<Label> call;
if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) { if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) {
call = RetrofitClient.getApiInterface(ctx).orgEditLabel(getIntent().getStringExtra("orgName"), (long) labelId, createLabelFunc); call = RetrofitClient.getApiInterface(ctx).orgEditLabel(getIntent().getStringExtra("orgName"), (long) labelId, createLabelFunc);
} }
else { else {
call = RetrofitClient.getApiInterface(ctx).issueEditLabel(repository.getOwner(), repository.getName(), (long) labelId, createLabelFunc); call = RetrofitClient.getApiInterface(ctx).issueEditLabel(repository.getOwner(), repository.getName(), (long) labelId, createLabelFunc);
} }
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Label> call, @NonNull retrofit2.Response<Label> response) { public void onResponse(@NonNull Call<Label> call, @NonNull retrofit2.Response<Label> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 200) { if(response.code() == 200) {
Toasty.success(ctx, getString(R.string.labelUpdated)); Toasty.success(ctx, getString(R.string.labelUpdated));
refreshLabels = true; refreshLabels = true;
finish(); finish();
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Label> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Label> call, @NonNull Throwable t) {
labelColor = ""; labelColor = "";
labelColorDefault = ""; labelColorDefault = "";
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void deleteLabel(int labelId) { private void deleteLabel(int labelId) {
Call<Void> call; Call<Void> call;
if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) { if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) {
call = RetrofitClient.getApiInterface(ctx).orgDeleteLabel(getIntent().getStringExtra("orgName"), (long) labelId); call = RetrofitClient.getApiInterface(ctx).orgDeleteLabel(getIntent().getStringExtra("orgName"), (long) labelId);
} }
else { else {
call = RetrofitClient.getApiInterface(ctx).issueDeleteLabel(repository.getOwner(), repository.getName(), (long) labelId); call = RetrofitClient.getApiInterface(ctx).issueDeleteLabel(repository.getOwner(), repository.getName(), (long) labelId);
} }
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 204) { if(response.code() == 204) {
Toasty.success(ctx, getString(R.string.labelDeleteText)); Toasty.success(ctx, getString(R.string.labelDeleteText));
if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) { if(getIntent().getStringExtra("type") != null && Objects.requireNonNull(getIntent().getStringExtra("type")).equals("org")) {
OrganizationLabelsViewModel.loadOrgLabelsList(getIntent().getStringExtra("orgName"), ctx, null, null); OrganizationLabelsViewModel.loadOrgLabelsList(getIntent().getStringExtra("orgName"), ctx, null, null);
} }
else { else {
LabelsViewModel.loadLabelsList(repository.getOwner(), repository.getName(), ctx); LabelsViewModel.loadLabelsList(repository.getOwner(), repository.getName(), ctx);
} }
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
} }
}); });
} }
private void disableProcessButton() { private void disableProcessButton() {
activityCreateLabelBinding.createLabelButton.setEnabled(false); activityCreateLabelBinding.createLabelButton.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
activityCreateLabelBinding.createLabelButton.setEnabled(true); activityCreateLabelBinding.createLabelButton.setEnabled(true);
} }
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if(repository == null) return; if(repository == null) {
return;
}
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }

View File

@ -33,185 +33,181 @@ import retrofit2.Callback;
public class CreateMilestoneActivity extends BaseActivity implements View.OnClickListener { public class CreateMilestoneActivity extends BaseActivity implements View.OnClickListener {
private EditText milestoneDueDate; private EditText milestoneDueDate;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private EditText milestoneTitle; private EditText milestoneTitle;
private EditText milestoneDescription; private EditText milestoneDescription;
private Button createNewMilestoneButton; private Button createNewMilestoneButton;
private RepositoryContext repository; private RepositoryContext repository;
private Date currentDate = null; private Date currentDate = null;
private final View.OnClickListener createMilestoneListener = v -> processNewMilestone();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityCreateMilestoneBinding activityCreateMilestoneBinding = ActivityCreateMilestoneBinding.inflate(getLayoutInflater()); ActivityCreateMilestoneBinding activityCreateMilestoneBinding = ActivityCreateMilestoneBinding.inflate(getLayoutInflater());
setContentView(activityCreateMilestoneBinding.getRoot()); setContentView(activityCreateMilestoneBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
milestoneDueDate = activityCreateMilestoneBinding.milestoneDueDate; milestoneDueDate = activityCreateMilestoneBinding.milestoneDueDate;
ImageView closeActivity = activityCreateMilestoneBinding.close; ImageView closeActivity = activityCreateMilestoneBinding.close;
createNewMilestoneButton = activityCreateMilestoneBinding.createNewMilestoneButton; createNewMilestoneButton = activityCreateMilestoneBinding.createNewMilestoneButton;
milestoneTitle = activityCreateMilestoneBinding.milestoneTitle; milestoneTitle = activityCreateMilestoneBinding.milestoneTitle;
milestoneDescription = activityCreateMilestoneBinding.milestoneDescription; milestoneDescription = activityCreateMilestoneBinding.milestoneDescription;
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
milestoneTitle.requestFocus(); milestoneTitle.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(milestoneTitle, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(milestoneTitle, InputMethodManager.SHOW_IMPLICIT);
milestoneDescription.setOnTouchListener((touchView, motionEvent) -> { milestoneDescription.setOnTouchListener((touchView, motionEvent) -> {
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) { if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
return false; return false;
}); });
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
milestoneDueDate.setOnClickListener(this); milestoneDueDate.setOnClickListener(this);
if(!connToInternet) { if(!connToInternet) {
createNewMilestoneButton.setEnabled(false); createNewMilestoneButton.setEnabled(false);
} }
else { else {
createNewMilestoneButton.setOnClickListener(createMilestoneListener); createNewMilestoneButton.setOnClickListener(createMilestoneListener);
} }
} }
private final View.OnClickListener createMilestoneListener = v -> processNewMilestone(); private void processNewMilestone() {
private void processNewMilestone() { boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); String newMilestoneTitle = milestoneTitle.getText().toString();
String newMilestoneDescription = milestoneDescription.getText().toString();
String newMilestoneTitle = milestoneTitle.getText().toString(); if(!connToInternet) {
String newMilestoneDescription = milestoneDescription.getText().toString();
if(!connToInternet) { Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return;
}
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); if(newMilestoneTitle.equals("")) {
return;
}
if(newMilestoneTitle.equals("")) { Toasty.error(ctx, getString(R.string.milestoneNameErrorEmpty));
return;
}
Toasty.error(ctx, getString(R.string.milestoneNameErrorEmpty)); if(!newMilestoneDescription.equals("")) {
return;
}
if(!newMilestoneDescription.equals("")) { if(newMilestoneDescription.length() > 255) {
if (newMilestoneDescription.length() > 255) { Toasty.warning(ctx, getString(R.string.milestoneDescError));
return;
}
}
Toasty.warning(ctx, getString(R.string.milestoneDescError)); disableProcessButton();
return; createNewMilestone(repository.getOwner(), repository.getName(), newMilestoneTitle, newMilestoneDescription);
} }
}
disableProcessButton(); private void createNewMilestone(String repoOwner, String repoName, String newMilestoneTitle, String newMilestoneDescription) {
createNewMilestone(repository.getOwner(), repository.getName(), newMilestoneTitle, newMilestoneDescription);
}
private void createNewMilestone(String repoOwner, String repoName, String newMilestoneTitle, String newMilestoneDescription) { CreateMilestoneOption createMilestone = new CreateMilestoneOption();
CreateMilestoneOption createMilestone = new CreateMilestoneOption();
createMilestone.setDescription(newMilestoneDescription); createMilestone.setDescription(newMilestoneDescription);
createMilestone.setTitle(newMilestoneTitle); createMilestone.setTitle(newMilestoneTitle);
createMilestone.setDueOn(currentDate); createMilestone.setDueOn(currentDate);
Call<Milestone> call; Call<Milestone> call;
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx).issueCreateMilestone(repoOwner, repoName, createMilestone);
.getApiInterface(ctx)
.issueCreateMilestone(repoOwner, repoName, createMilestone);
call.enqueue(new Callback<Milestone>() { call.enqueue(new Callback<Milestone>() {
@Override @Override
public void onResponse(@NonNull Call<Milestone> call, @NonNull retrofit2.Response<Milestone> response) { public void onResponse(@NonNull Call<Milestone> call, @NonNull retrofit2.Response<Milestone> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 201) { if(response.code() == 201) {
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("milestoneCreated", true); result.putExtra("milestoneCreated", true);
setResult(201, result); setResult(201, result);
Toasty.success(ctx, getString(R.string.milestoneCreated)); Toasty.success(ctx, getString(R.string.milestoneCreated));
enableProcessButton(); enableProcessButton();
finish(); finish();
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Milestone> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Milestone> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (v == milestoneDueDate) { if(v == milestoneDueDate) {
final Calendar c = Calendar.getInstance(); final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
milestoneDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); milestoneDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
datePickerDialog.show(); datePickerDialog.show();
} }
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void disableProcessButton() { private void disableProcessButton() {
createNewMilestoneButton.setEnabled(false); createNewMilestoneButton.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
createNewMilestoneButton.setEnabled(true); createNewMilestoneButton.setEnabled(true);
} }
@Override @Override
public void onResume() { public void onResume() {

View File

@ -27,168 +27,165 @@ import retrofit2.Callback;
public class CreateNewUserActivity extends BaseActivity { public class CreateNewUserActivity extends BaseActivity {
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private EditText fullName; private EditText fullName;
private EditText userUserName; private EditText userUserName;
private EditText userEmail; private EditText userEmail;
private EditText userPassword; private EditText userPassword;
private Button createUserButton; private Button createUserButton;
private final View.OnClickListener createNewUserListener = v -> processCreateNewUser();
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityCreateNewUserBinding activityCreateNewUserBinding = ActivityCreateNewUserBinding.inflate(getLayoutInflater()); ActivityCreateNewUserBinding activityCreateNewUserBinding = ActivityCreateNewUserBinding.inflate(getLayoutInflater());
setContentView(activityCreateNewUserBinding.getRoot()); setContentView(activityCreateNewUserBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
ImageView closeActivity = activityCreateNewUserBinding.close; ImageView closeActivity = activityCreateNewUserBinding.close;
createUserButton = activityCreateNewUserBinding.createUserButton; createUserButton = activityCreateNewUserBinding.createUserButton;
fullName = activityCreateNewUserBinding.fullName; fullName = activityCreateNewUserBinding.fullName;
userUserName = activityCreateNewUserBinding.userUserName; userUserName = activityCreateNewUserBinding.userUserName;
userEmail = activityCreateNewUserBinding.userEmail; userEmail = activityCreateNewUserBinding.userEmail;
userPassword = activityCreateNewUserBinding.userPassword; userPassword = activityCreateNewUserBinding.userPassword;
fullName.requestFocus(); fullName.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(fullName, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(fullName, InputMethodManager.SHOW_IMPLICIT);
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
if(!connToInternet) { if(!connToInternet) {
disableProcessButton(); disableProcessButton();
} }
else { else {
createUserButton.setOnClickListener(createNewUserListener); createUserButton.setOnClickListener(createNewUserListener);
} }
} }
private void processCreateNewUser() { private void processCreateNewUser() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
String newFullName = fullName.getText().toString().trim(); String newFullName = fullName.getText().toString().trim();
String newUserName = userUserName.getText().toString().trim(); String newUserName = userUserName.getText().toString().trim();
String newUserEmail = userEmail.getText().toString().trim(); String newUserEmail = userEmail.getText().toString().trim();
String newUserPassword = userPassword.getText().toString(); String newUserPassword = userPassword.getText().toString();
if(!connToInternet) { if(!connToInternet) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return; return;
} }
if(newFullName.equals("") || newUserName.equals("") | newUserEmail.equals("") || newUserPassword.equals("")) { if(newFullName.equals("") || newUserName.equals("") | newUserEmail.equals("") || newUserPassword.equals("")) {
Toasty.error(ctx, getString(R.string.emptyFields)); Toasty.error(ctx, getString(R.string.emptyFields));
return; return;
} }
if(!AppUtil.checkStrings(newFullName)) { if(!AppUtil.checkStrings(newFullName)) {
Toasty.error(ctx, getString(R.string.userInvalidFullName)); Toasty.error(ctx, getString(R.string.userInvalidFullName));
return; return;
} }
if(!AppUtil.checkStringsWithAlphaNumeric(newUserName)) { if(!AppUtil.checkStringsWithAlphaNumeric(newUserName)) {
Toasty.error(ctx, getString(R.string.userInvalidUserName)); Toasty.error(ctx, getString(R.string.userInvalidUserName));
return; return;
} }
if(!Patterns.EMAIL_ADDRESS.matcher(newUserEmail).matches()) { if(!Patterns.EMAIL_ADDRESS.matcher(newUserEmail).matches()) {
Toasty.error(ctx, getString(R.string.userInvalidEmail)); Toasty.error(ctx, getString(R.string.userInvalidEmail));
return; return;
} }
disableProcessButton(); disableProcessButton();
createNewUser(newFullName, newUserName, newUserEmail, newUserPassword); createNewUser(newFullName, newUserName, newUserEmail, newUserPassword);
} }
private void createNewUser(String newFullName, String newUserName, String newUserEmail, String newUserPassword) { private void createNewUser(String newFullName, String newUserName, String newUserEmail, String newUserPassword) {
CreateUserOption createUser = new CreateUserOption(); CreateUserOption createUser = new CreateUserOption();
createUser.setEmail(newUserEmail); createUser.setEmail(newUserEmail);
createUser.setFullName(newFullName); createUser.setFullName(newFullName);
createUser.setUsername(newUserName); createUser.setUsername(newUserName);
createUser.setPassword(newUserPassword); createUser.setPassword(newUserPassword);
createUser.setMustChangePassword(true); createUser.setMustChangePassword(true);
Call<User> call = RetrofitClient Call<User> call = RetrofitClient.getApiInterface(ctx).adminCreateUser(createUser);
.getApiInterface(ctx)
.adminCreateUser(createUser);
call.enqueue(new Callback<User>() { call.enqueue(new Callback<User>() {
@Override @Override
public void onResponse(@NonNull Call<User> call, @NonNull retrofit2.Response<User> response) { public void onResponse(@NonNull Call<User> call, @NonNull retrofit2.Response<User> response) {
if(response.code() == 201) { if(response.code() == 201) {
Toasty.success(ctx, getString(R.string.userCreatedText)); Toasty.success(ctx, getString(R.string.userCreatedText));
enableProcessButton(); enableProcessButton();
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, ctx.getString(R.string.authorizeError)); Toasty.error(ctx, ctx.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound)); Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
} }
else if(response.code() == 422) { else if(response.code() == 422) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, ctx.getString(R.string.userExistsError)); Toasty.warning(ctx, ctx.getString(R.string.userExistsError));
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<User> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<User> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private final View.OnClickListener createNewUserListener = v -> processCreateNewUser(); private void initCloseListener() {
private void initCloseListener() { onClickListener = view -> finish();
}
onClickListener = view -> finish(); private void disableProcessButton() {
}
private void disableProcessButton() { createUserButton.setEnabled(false);
}
createUserButton.setEnabled(false); private void enableProcessButton() {
}
private void enableProcessButton() { createUserButton.setEnabled(true);
}
createUserButton.setEnabled(true);
}
} }

View File

@ -29,175 +29,172 @@ import retrofit2.Callback;
public class CreateOrganizationActivity extends BaseActivity { public class CreateOrganizationActivity extends BaseActivity {
public ImageView closeActivity; public ImageView closeActivity;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private Button createOrganizationButton; private Button createOrganizationButton;
private EditText orgName; private EditText orgName;
private EditText orgDesc; private EditText orgDesc;
private final View.OnClickListener createOrgListener = v -> processNewOrganization();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityCreateOrganizationBinding activityCreateOrganizationBinding = ActivityCreateOrganizationBinding.inflate(getLayoutInflater()); ActivityCreateOrganizationBinding activityCreateOrganizationBinding = ActivityCreateOrganizationBinding.inflate(getLayoutInflater());
setContentView(activityCreateOrganizationBinding.getRoot()); setContentView(activityCreateOrganizationBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
closeActivity = activityCreateOrganizationBinding.close; closeActivity = activityCreateOrganizationBinding.close;
orgName = activityCreateOrganizationBinding.newOrganizationName; orgName = activityCreateOrganizationBinding.newOrganizationName;
orgDesc = activityCreateOrganizationBinding.newOrganizationDescription; orgDesc = activityCreateOrganizationBinding.newOrganizationDescription;
orgName.requestFocus(); orgName.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(orgName, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(orgName, InputMethodManager.SHOW_IMPLICIT);
orgDesc.setOnTouchListener((touchView, motionEvent) -> { orgDesc.setOnTouchListener((touchView, motionEvent) -> {
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) { if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
return false; return false;
}); });
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
createOrganizationButton = activityCreateOrganizationBinding.createNewOrganizationButton; createOrganizationButton = activityCreateOrganizationBinding.createNewOrganizationButton;
if(!connToInternet) { if(!connToInternet) {
createOrganizationButton.setEnabled(false); createOrganizationButton.setEnabled(false);
} }
else { else {
createOrganizationButton.setOnClickListener(createOrgListener); createOrganizationButton.setOnClickListener(createOrgListener);
} }
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private final View.OnClickListener createOrgListener = v -> processNewOrganization(); private void processNewOrganization() {
private void processNewOrganization() { boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); String newOrgName = orgName.getText().toString();
String newOrgDesc = orgDesc.getText().toString();
String newOrgName = orgName.getText().toString(); if(!connToInternet) {
String newOrgDesc = orgDesc.getText().toString();
if(!connToInternet) { Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return;
}
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); if(!newOrgDesc.equals("")) {
return;
}
if(!newOrgDesc.equals("")) { if(newOrgDesc.length() > 255) {
if (newOrgDesc.length() > 255) { Toasty.warning(ctx, getString(R.string.orgDescError));
return;
}
}
Toasty.warning(ctx, getString(R.string.orgDescError)); if(newOrgName.equals("")) {
return;
}
}
if(newOrgName.equals("")) { Toasty.error(ctx, getString(R.string.orgNameErrorEmpty));
}
else if(!AppUtil.checkStrings(newOrgName)) {
Toasty.error(ctx, getString(R.string.orgNameErrorEmpty)); Toasty.warning(ctx, getString(R.string.orgNameErrorInvalid));
} }
else if(!AppUtil.checkStrings(newOrgName)) { else {
Toasty.warning(ctx, getString(R.string.orgNameErrorInvalid)); disableProcessButton();
} createNewOrganization(newOrgName, newOrgDesc);
else { }
disableProcessButton(); }
createNewOrganization(newOrgName, newOrgDesc);
}
} private void createNewOrganization(String orgName, String orgDesc) {
private void createNewOrganization(String orgName, String orgDesc) { CreateOrgOption createOrganization = new CreateOrgOption();
CreateOrgOption createOrganization = new CreateOrgOption();
createOrganization.setDescription(orgDesc); createOrganization.setDescription(orgDesc);
createOrganization.setUsername(orgName); createOrganization.setUsername(orgName);
Call<Organization> call = RetrofitClient Call<Organization> call = RetrofitClient.getApiInterface(ctx).orgCreate(createOrganization);
.getApiInterface(ctx)
.orgCreate(createOrganization);
call.enqueue(new Callback<Organization>() { call.enqueue(new Callback<Organization>() {
@Override @Override
public void onResponse(@NonNull Call<Organization> call, @NonNull retrofit2.Response<Organization> response) { public void onResponse(@NonNull Call<Organization> call, @NonNull retrofit2.Response<Organization> response) {
if(response.code() == 201) { if(response.code() == 201) {
OrganizationsFragment.orgCreated = true; OrganizationsFragment.orgCreated = true;
enableProcessButton(); enableProcessButton();
Toasty.success(ctx, getString(R.string.orgCreated)); Toasty.success(ctx, getString(R.string.orgCreated));
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else if(response.code() == 409) { else if(response.code() == 409) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, getString(R.string.orgExistsError)); Toasty.warning(ctx, getString(R.string.orgExistsError));
} }
else if(response.code() == 422) { else if(response.code() == 422) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, getString(R.string.orgExistsError)); Toasty.warning(ctx, getString(R.string.orgExistsError));
} }
else { else {
if(response.code() == 404) { if(response.code() == 404) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, getString(R.string.apiNotFound)); Toasty.warning(ctx, getString(R.string.apiNotFound));
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Organization> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Organization> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void disableProcessButton() { private void disableProcessButton() {
createOrganizationButton.setEnabled(false); createOrganizationButton.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
createOrganizationButton.setEnabled(true); createOrganizationButton.setEnabled(true);
} }
} }

View File

@ -11,11 +11,7 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreatePullRequestOption;
import org.gitnex.tea4j.v2.models.Label;
import org.gitnex.tea4j.v2.models.Milestone;
import org.gitnex.tea4j.v2.models.PullRequest;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.actions.LabelsActions; import org.mian.gitnex.actions.LabelsActions;
import org.mian.gitnex.adapters.LabelsListAdapter; import org.mian.gitnex.adapters.LabelsListAdapter;
@ -26,12 +22,7 @@ import org.mian.gitnex.fragments.PullRequestsFragment;
import org.mian.gitnex.helpers.Constants; import org.mian.gitnex.helpers.Constants;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -41,21 +32,18 @@ import retrofit2.Callback;
public class CreatePullRequestActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener { public class CreatePullRequestActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener {
private View.OnClickListener onClickListener;
private ActivityCreatePrBinding viewBinding;
private List<Integer> labelsIds = new ArrayList<>();
private final List<String> assignees = new ArrayList<>(); private final List<String> assignees = new ArrayList<>();
private int milestoneId;
private Date currentDate = null;
private RepositoryContext repository;
private LabelsListAdapter labelsAdapter;
private MaterialAlertDialogBuilder materialAlertDialogBuilder;
LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>(); LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
List<String> branchesList = new ArrayList<>(); List<String> branchesList = new ArrayList<>();
List<Label> labelsList = new ArrayList<>(); List<Label> labelsList = new ArrayList<>();
private View.OnClickListener onClickListener;
private ActivityCreatePrBinding viewBinding;
private List<Integer> labelsIds = new ArrayList<>();
private int milestoneId;
private Date currentDate = null;
private RepositoryContext repository;
private LabelsListAdapter labelsAdapter;
private MaterialAlertDialogBuilder materialAlertDialogBuilder;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
@ -76,23 +64,21 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) { if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
return false; return false;
}); });
labelsAdapter = new LabelsListAdapter(labelsList, CreatePullRequestActivity.this, labelsIds); labelsAdapter = new LabelsListAdapter(labelsList, CreatePullRequestActivity.this, labelsIds);
ImageView closeActivity = findViewById(R.id.close); ImageView closeActivity = findViewById(R.id.close);
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
viewBinding.prDueDate.setOnClickListener(dueDate -> viewBinding.prDueDate.setOnClickListener(dueDate -> setDueDate());
setDueDate()
);
disableProcessButton(); disableProcessButton();
@ -119,7 +105,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
assignees.add(""); assignees.add("");
if (labelsIds.size() == 0) { if(labelsIds.size() == 0) {
labelsIds.add(0); labelsIds.add(0);
} }
@ -163,9 +149,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
createPullRequest.setLabels(labelIds); createPullRequest.setLabels(labelIds);
createPullRequest.setDueDate(currentDate); createPullRequest.setDueDate(currentDate);
Call<PullRequest> transferCall = RetrofitClient Call<PullRequest> transferCall = RetrofitClient.getApiInterface(ctx).repoCreatePullRequest(repository.getOwner(), repository.getName(), createPullRequest);
.getApiInterface(ctx)
.repoCreatePullRequest(repository.getOwner(), repository.getName(), createPullRequest);
transferCall.enqueue(new Callback<>() { transferCall.enqueue(new Callback<>() {
@ -224,8 +208,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
private void showLabels() { private void showLabels() {
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate( CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = labelsBinding.getRoot(); View view = labelsBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
@ -235,9 +218,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
private void getBranches(String repoOwner, String repoName) { private void getBranches(String repoOwner, String repoName) {
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.repoListBranches(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -277,9 +258,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
private void getMilestones(String repoOwner, String repoName, int resultLimit) { private void getMilestones(String repoOwner, String repoName, int resultLimit) {
String msState = "open"; String msState = "open";
Call<List<Milestone>> call = RetrofitClient Call<List<Milestone>> call = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
.getApiInterface(ctx)
.issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -336,11 +315,10 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
viewBinding.prDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); viewBinding.prDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
datePickerDialog.show(); datePickerDialog.show();
} }
@ -364,4 +342,5 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -8,18 +8,9 @@ import android.util.Log;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateReleaseOption;
import org.gitnex.tea4j.v2.models.CreateTagOption;
import org.gitnex.tea4j.v2.models.Release;
import org.gitnex.tea4j.v2.models.Tag;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.ActivityCreateReleaseBinding; import org.mian.gitnex.databinding.ActivityCreateReleaseBinding;
@ -38,313 +29,305 @@ import retrofit2.Callback;
public class CreateReleaseActivity extends BaseActivity { public class CreateReleaseActivity extends BaseActivity {
private View.OnClickListener onClickListener; public ImageView closeActivity;
public ImageView closeActivity; List<String> branchesList = new ArrayList<>();
private EditText releaseTagName; private View.OnClickListener onClickListener;
private AutoCompleteTextView releaseBranch; private EditText releaseTagName;
private EditText releaseTitle; private AutoCompleteTextView releaseBranch;
private EditText releaseContent; private EditText releaseTitle;
private CheckBox releaseType; private EditText releaseContent;
private CheckBox releaseDraft; private CheckBox releaseType;
private Button createNewRelease; private CheckBox releaseDraft;
private String selectedBranch; private Button createNewRelease;
private Button createNewTag; private String selectedBranch;
private Button createNewTag;
private RepositoryContext repository; private RepositoryContext repository;
private final View.OnClickListener createReleaseListener = v -> processNewRelease();
List<String> branchesList = new ArrayList<>(); @SuppressLint("ClickableViewAccessibility")
@Override
public void onCreate(Bundle savedInstanceState) {
@SuppressLint("ClickableViewAccessibility") super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); ActivityCreateReleaseBinding activityCreateReleaseBinding = ActivityCreateReleaseBinding.inflate(getLayoutInflater());
setContentView(activityCreateReleaseBinding.getRoot());
ActivityCreateReleaseBinding activityCreateReleaseBinding = ActivityCreateReleaseBinding.inflate(getLayoutInflater()); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
setContentView(activityCreateReleaseBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); repository = RepositoryContext.fromIntent(getIntent());
repository = RepositoryContext.fromIntent(getIntent()); closeActivity = activityCreateReleaseBinding.close;
releaseTagName = activityCreateReleaseBinding.releaseTagName;
releaseTitle = activityCreateReleaseBinding.releaseTitle;
releaseContent = activityCreateReleaseBinding.releaseContent;
releaseType = activityCreateReleaseBinding.releaseType;
releaseDraft = activityCreateReleaseBinding.releaseDraft;
closeActivity = activityCreateReleaseBinding.close; releaseTitle.requestFocus();
releaseTagName = activityCreateReleaseBinding.releaseTagName; assert imm != null;
releaseTitle = activityCreateReleaseBinding.releaseTitle; imm.showSoftInput(releaseTitle, InputMethodManager.SHOW_IMPLICIT);
releaseContent = activityCreateReleaseBinding.releaseContent;
releaseType = activityCreateReleaseBinding.releaseType;
releaseDraft = activityCreateReleaseBinding.releaseDraft;
releaseTitle.requestFocus(); releaseContent.setOnTouchListener((touchView, motionEvent) -> {
assert imm != null;
imm.showSoftInput(releaseTitle, InputMethodManager.SHOW_IMPLICIT);
releaseContent.setOnTouchListener((touchView, motionEvent) -> { touchView.getParent().requestDisallowInterceptTouchEvent(true);
touchView.getParent().requestDisallowInterceptTouchEvent(true); if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) { touchView.getParent().requestDisallowInterceptTouchEvent(false);
}
return false;
});
touchView.getParent().requestDisallowInterceptTouchEvent(false); initCloseListener();
} closeActivity.setOnClickListener(onClickListener);
return false;
});
initCloseListener(); releaseBranch = activityCreateReleaseBinding.releaseBranch;
closeActivity.setOnClickListener(onClickListener); getBranches(repository.getOwner(), repository.getName());
releaseBranch = activityCreateReleaseBinding.releaseBranch; createNewRelease = activityCreateReleaseBinding.createNewRelease;
getBranches(repository.getOwner(), repository.getName()); createNewTag = activityCreateReleaseBinding.createNewTag;
disableProcessButton();
createNewRelease = activityCreateReleaseBinding.createNewRelease; if(!connToInternet) {
createNewTag = activityCreateReleaseBinding.createNewTag;
disableProcessButton();
if(!connToInternet) { disableProcessButton();
}
else {
disableProcessButton(); createNewRelease.setOnClickListener(createReleaseListener);
} }
else {
createNewRelease.setOnClickListener(createReleaseListener); createNewTag.setOnClickListener(v -> createNewTag());
} }
createNewTag.setOnClickListener(v -> createNewTag()); private void createNewTag() {
} boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
private void createNewTag() { String tagName = releaseTagName.getText().toString();
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); String message = releaseTitle.getText().toString() + "\n\n" + releaseContent.getText().toString();
String tagName = releaseTagName.getText().toString(); if(!connToInternet) {
String message = releaseTitle.getText().toString() + "\n\n" + releaseContent.getText().toString(); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return;
}
if(!connToInternet) { if(tagName.equals("")) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getString(R.string.tagNameErrorEmpty));
return; return;
} }
if(tagName.equals("")) { if(selectedBranch == null) {
Toasty.error(ctx, getString(R.string.tagNameErrorEmpty)); Toasty.error(ctx, getString(R.string.selectBranchError));
return; return;
} }
if(selectedBranch == null) { disableProcessButton();
Toasty.error(ctx, getString(R.string.selectBranchError));
return;
}
disableProcessButton(); CreateTagOption createReleaseJson = new CreateTagOption();
CreateTagOption createReleaseJson = new CreateTagOption();
createReleaseJson.setMessage(message); createReleaseJson.setMessage(message);
createReleaseJson.setTagName(tagName); createReleaseJson.setTagName(tagName);
createReleaseJson.setTarget(selectedBranch); createReleaseJson.setTarget(selectedBranch);
Call<Tag> call = RetrofitClient Call<Tag> call = RetrofitClient.getApiInterface(ctx).repoCreateTag(repository.getOwner(), repository.getName(), createReleaseJson);
.getApiInterface(ctx)
.repoCreateTag(repository.getOwner(), repository.getName(), createReleaseJson);
call.enqueue(new Callback<Tag>() { call.enqueue(new Callback<Tag>() {
@Override @Override
public void onResponse(@NonNull Call<Tag> call, @NonNull retrofit2.Response<Tag> response) { public void onResponse(@NonNull Call<Tag> call, @NonNull retrofit2.Response<Tag> response) {
if (response.code() == 201) { if(response.code() == 201) {
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("updateReleases", true); result.putExtra("updateReleases", true);
setResult(201, result); setResult(201, result);
Toasty.success(ctx, getString(R.string.tagCreated)); Toasty.success(ctx, getString(R.string.tagCreated));
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, ctx.getString(R.string.authorizeError)); Toasty.error(ctx, ctx.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound)); Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, ctx.getString(R.string.genericError)); Toasty.error(ctx, ctx.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Tag> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Tag> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private final View.OnClickListener createReleaseListener = v -> processNewRelease(); private void processNewRelease() {
private void processNewRelease() { boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); String newReleaseTagName = releaseTagName.getText().toString();
String newReleaseTitle = releaseTitle.getText().toString();
String newReleaseContent = releaseContent.getText().toString();
String checkBranch = selectedBranch;
boolean newReleaseType = releaseType.isChecked();
boolean newReleaseDraft = releaseDraft.isChecked();
String newReleaseTagName = releaseTagName.getText().toString(); if(!connToInternet) {
String newReleaseTitle = releaseTitle.getText().toString();
String newReleaseContent = releaseContent.getText().toString();
String checkBranch = selectedBranch;
boolean newReleaseType = releaseType.isChecked();
boolean newReleaseDraft = releaseDraft.isChecked();
if(!connToInternet) { Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return;
}
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); if(newReleaseTitle.equals("")) {
return;
}
if(newReleaseTitle.equals("")) { Toasty.error(ctx, getString(R.string.titleErrorEmpty));
return;
}
Toasty.error(ctx, getString(R.string.titleErrorEmpty)); if(newReleaseTagName.equals("")) {
return;
}
if(newReleaseTagName.equals("")) { Toasty.error(ctx, getString(R.string.tagNameErrorEmpty));
return;
}
Toasty.error(ctx, getString(R.string.tagNameErrorEmpty)); if(checkBranch == null) {
return;
}
if(checkBranch == null) { Toasty.error(ctx, getString(R.string.selectBranchError));
return;
}
Toasty.error(ctx, getString(R.string.selectBranchError)); disableProcessButton();
return; createNewReleaseFunc(repository.getOwner(), repository.getName(), newReleaseTagName, newReleaseTitle, newReleaseContent, selectedBranch, newReleaseType, newReleaseDraft);
} }
disableProcessButton(); private void createNewReleaseFunc(String repoOwner, String repoName, String newReleaseTagName, String newReleaseTitle, String newReleaseContent, String selectedBranch, boolean newReleaseType,
createNewReleaseFunc(repository.getOwner(), repository.getName(), newReleaseTagName, newReleaseTitle, newReleaseContent, selectedBranch, newReleaseType, newReleaseDraft); boolean newReleaseDraft) {
}
private void createNewReleaseFunc(String repoOwner, String repoName, String newReleaseTagName, String newReleaseTitle, String newReleaseContent, CreateReleaseOption createReleaseJson = new CreateReleaseOption();
String selectedBranch, boolean newReleaseType, boolean newReleaseDraft) { createReleaseJson.setName(newReleaseTitle);
CreateReleaseOption createReleaseJson = new CreateReleaseOption();
createReleaseJson.setName(newReleaseTitle);
createReleaseJson.setTagName(newReleaseTagName); createReleaseJson.setTagName(newReleaseTagName);
createReleaseJson.setBody(newReleaseContent); createReleaseJson.setBody(newReleaseContent);
createReleaseJson.setDraft(newReleaseDraft); createReleaseJson.setDraft(newReleaseDraft);
createReleaseJson.setPrerelease(newReleaseType); createReleaseJson.setPrerelease(newReleaseType);
createReleaseJson.setTargetCommitish(selectedBranch); createReleaseJson.setTargetCommitish(selectedBranch);
Call<Release> call = RetrofitClient Call<Release> call = RetrofitClient.getApiInterface(ctx).repoCreateRelease(repoOwner, repoName, createReleaseJson);
.getApiInterface(ctx)
.repoCreateRelease(repoOwner, repoName, createReleaseJson);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Release> call, @NonNull retrofit2.Response<Release> response) { public void onResponse(@NonNull Call<Release> call, @NonNull retrofit2.Response<Release> response) {
if(response.code() == 201) { if(response.code() == 201) {
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("updateReleases", true); result.putExtra("updateReleases", true);
setResult(201, result); setResult(201, result);
Toasty.success(ctx, getString(R.string.releaseCreatedText)); Toasty.success(ctx, getString(R.string.releaseCreatedText));
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, ctx.getString(R.string.authorizeError)); Toasty.error(ctx, ctx.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound)); Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, ctx.getString(R.string.genericError)); Toasty.error(ctx, ctx.getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Release> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Release> call, @NonNull Throwable t) {
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void getBranches(final String repoOwner, final String repoName) { private void getBranches(final String repoOwner, final String repoName) {
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.repoListBranches(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<List<Branch>> call, @NonNull retrofit2.Response<List<Branch>> response) { public void onResponse(@NonNull Call<List<Branch>> call, @NonNull retrofit2.Response<List<Branch>> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
if(response.code() == 200) { if(response.code() == 200) {
List<Branch> branchesList_ = response.body(); List<Branch> branchesList_ = response.body();
assert branchesList_ != null; assert branchesList_ != null;
for(Branch i : branchesList_) { for(Branch i : branchesList_) {
branchesList.add(i.getName()); branchesList.add(i.getName());
} }
ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateReleaseActivity.this, R.layout.list_spinner_items, branchesList); ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateReleaseActivity.this, R.layout.list_spinner_items, branchesList);
releaseBranch.setAdapter(adapter); releaseBranch.setAdapter(adapter);
enableProcessButton(); enableProcessButton();
releaseBranch.setOnItemClickListener((parent, view, position, id) -> selectedBranch = branchesList.get(position)); releaseBranch.setOnItemClickListener((parent, view, position, id) -> selectedBranch = branchesList.get(position));
} }
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
} }
@Override @Override
public void onFailure(@NonNull Call<List<Branch>> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<List<Branch>> call, @NonNull Throwable t) {
} }
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void disableProcessButton() { private void disableProcessButton() {
createNewTag.setEnabled(false); createNewTag.setEnabled(false);
createNewRelease.setEnabled(false); createNewRelease.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
createNewTag.setEnabled(true); createNewTag.setEnabled(true);
createNewRelease.setEnabled(true); createNewRelease.setEnabled(true);
} }
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -7,12 +7,7 @@ import android.os.Looper;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.CreateRepoOption; import org.gitnex.tea4j.v2.models.CreateRepoOption;
import org.gitnex.tea4j.v2.models.Organization; import org.gitnex.tea4j.v2.models.Organization;
@ -36,262 +31,251 @@ import retrofit2.Callback;
public class CreateRepoActivity extends BaseActivity { public class CreateRepoActivity extends BaseActivity {
public ImageView closeActivity; //https://github.com/go-gitea/gitea/blob/52cfd2743c0e85b36081cf80a850e6a5901f1865/models/repo.go#L964-L967
private View.OnClickListener onClickListener; final List<String> reservedRepoNames = Arrays.asList(".", "..");
private AutoCompleteTextView spinner; final Pattern reservedRepoPatterns = Pattern.compile("\\.(git|wiki)$");
private Button createRepo; public ImageView closeActivity;
private EditText repoName;
private EditText repoDesc;
private CheckBox repoAccess;
private String loginUid;
private String selectedOwner;
List<String> organizationsList = new ArrayList<>(); List<String> organizationsList = new ArrayList<>();
private View.OnClickListener onClickListener;
private AutoCompleteTextView spinner;
private Button createRepo;
private EditText repoName;
private EditText repoDesc;
private CheckBox repoAccess;
private String loginUid;
private String selectedOwner;
private final View.OnClickListener createRepoListener = v -> processNewRepo();
//https://github.com/go-gitea/gitea/blob/52cfd2743c0e85b36081cf80a850e6a5901f1865/models/repo.go#L964-L967 @Override
final List<String> reservedRepoNames = Arrays.asList(".", ".."); public void onCreate(Bundle savedInstanceState) {
final Pattern reservedRepoPatterns = Pattern.compile("\\.(git|wiki)$");
@Override super.onCreate(savedInstanceState);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); ActivityCreateRepoBinding activityCreateRepoBinding = ActivityCreateRepoBinding.inflate(getLayoutInflater());
setContentView(activityCreateRepoBinding.getRoot());
ActivityCreateRepoBinding activityCreateRepoBinding = ActivityCreateRepoBinding.inflate(getLayoutInflater()); boolean connToInternet = AppUtil.hasNetworkConnection(ctx);
setContentView(activityCreateRepoBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(ctx); loginUid = getAccount().getAccount().getUserName();
loginUid = getAccount().getAccount().getUserName(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); closeActivity = activityCreateRepoBinding.close;
repoName = activityCreateRepoBinding.newRepoName;
repoDesc = activityCreateRepoBinding.newRepoDescription;
repoAccess = activityCreateRepoBinding.newRepoPrivate;
closeActivity = activityCreateRepoBinding.close; repoName.requestFocus();
repoName = activityCreateRepoBinding.newRepoName; assert imm != null;
repoDesc = activityCreateRepoBinding.newRepoDescription; imm.showSoftInput(repoName, InputMethodManager.SHOW_IMPLICIT);
repoAccess = activityCreateRepoBinding.newRepoPrivate;
repoName.requestFocus(); initCloseListener();
assert imm != null; closeActivity.setOnClickListener(onClickListener);
imm.showSoftInput(repoName, InputMethodManager.SHOW_IMPLICIT);
initCloseListener(); spinner = activityCreateRepoBinding.ownerSpinner;
closeActivity.setOnClickListener(onClickListener); getOrganizations(loginUid);
spinner = activityCreateRepoBinding.ownerSpinner; createRepo = activityCreateRepoBinding.createNewRepoButton;
getOrganizations(loginUid); disableProcessButton();
createRepo = activityCreateRepoBinding.createNewRepoButton; if(!connToInternet) {
disableProcessButton();
if(!connToInternet) { disableProcessButton();
}
else {
disableProcessButton(); createRepo.setOnClickListener(createRepoListener);
} }
else { }
createRepo.setOnClickListener(createRepoListener); private void processNewRepo() {
}
}
private final View.OnClickListener createRepoListener = v -> processNewRepo(); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
private void processNewRepo() { String newRepoName = repoName.getText().toString();
String newRepoDesc = repoDesc.getText().toString();
boolean newRepoAccess = repoAccess.isChecked();
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); if(!connToInternet) {
String newRepoName = repoName.getText().toString(); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
String newRepoDesc = repoDesc.getText().toString(); return;
boolean newRepoAccess = repoAccess.isChecked(); }
if(!connToInternet) { if(!newRepoDesc.equals("")) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); if(newRepoDesc.length() > 255) {
return;
}
if(!newRepoDesc.equals("")) { Toasty.warning(ctx, getString(R.string.repoDescError));
return;
}
}
if (newRepoDesc.length() > 255) { if(newRepoName.equals("")) {
Toasty.warning(ctx, getString(R.string.repoDescError)); Toasty.error(ctx, getString(R.string.repoNameErrorEmpty));
return; }
} else if(!AppUtil.checkStrings(newRepoName)) {
}
if(newRepoName.equals("")) { Toasty.warning(ctx, getString(R.string.repoNameErrorInvalid));
}
else if(reservedRepoNames.contains(newRepoName)) {
Toasty.error(ctx, getString(R.string.repoNameErrorEmpty)); Toasty.warning(ctx, getString(R.string.repoNameErrorReservedName));
} }
else if(!AppUtil.checkStrings(newRepoName)) { else if(reservedRepoPatterns.matcher(newRepoName).find()) {
Toasty.warning(ctx, getString(R.string.repoNameErrorInvalid)); Toasty.warning(ctx, getString(R.string.repoNameErrorReservedPatterns));
} }
else if (reservedRepoNames.contains(newRepoName)) { else if(selectedOwner == null) {
Toasty.warning(ctx, getString(R.string.repoNameErrorReservedName)); Toasty.error(ctx, getString(R.string.repoOwnerError));
} }
else if (reservedRepoPatterns.matcher(newRepoName).find()) { else {
Toasty.warning(ctx, getString(R.string.repoNameErrorReservedPatterns)); disableProcessButton();
} createNewRepository(loginUid, newRepoName, newRepoDesc, selectedOwner, newRepoAccess);
else if(selectedOwner == null) { }
}
Toasty.error(ctx, getString(R.string.repoOwnerError)); private void createNewRepository(String loginUid, String repoName, String repoDesc, String selectedOwner, boolean isPrivate) {
}
else {
disableProcessButton(); CreateRepoOption createRepository = new CreateRepoOption();
createNewRepository(loginUid, newRepoName, newRepoDesc, selectedOwner, newRepoAccess);
}
}
private void createNewRepository(String loginUid, String repoName, String repoDesc, String selectedOwner, boolean isPrivate) {
CreateRepoOption createRepository = new CreateRepoOption();
createRepository.setAutoInit(true); createRepository.setAutoInit(true);
createRepository.setDescription(repoDesc); createRepository.setDescription(repoDesc);
createRepository.setPrivate(isPrivate); createRepository.setPrivate(isPrivate);
createRepository.setReadme("Default"); createRepository.setReadme("Default");
createRepository.setName(repoName); createRepository.setName(repoName);
Call<Repository> call; Call<Repository> call;
if(selectedOwner.equals(loginUid)) { if(selectedOwner.equals(loginUid)) {
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx).createCurrentUserRepo(createRepository);
.getApiInterface(ctx) }
.createCurrentUserRepo(createRepository); else {
}
else {
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx).createOrgRepo(selectedOwner, createRepository);
.getApiInterface(ctx) }
.createOrgRepo(selectedOwner, createRepository);
}
call.enqueue(new Callback<Repository>() { call.enqueue(new Callback<Repository>() {
@Override @Override
public void onResponse(@NonNull Call<Repository> call, @NonNull retrofit2.Response<Repository> response) { public void onResponse(@NonNull Call<Repository> call, @NonNull retrofit2.Response<Repository> response) {
if(response.code() == 201) { if(response.code() == 201) {
MainActivity.reloadRepos = true; MainActivity.reloadRepos = true;
Toasty.success(ctx, getString(R.string.repoCreated)); Toasty.success(ctx, getString(R.string.repoCreated));
enableProcessButton(); enableProcessButton();
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else if(response.code() == 409) { else if(response.code() == 409) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, getString(R.string.repoExistsError)); Toasty.warning(ctx, getString(R.string.repoExistsError));
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Repository> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Repository> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void getOrganizations(final String userLogin) { private void getOrganizations(final String userLogin) {
Call<List<Organization>> call = RetrofitClient Call<List<Organization>> call = RetrofitClient.getApiInterface(ctx).orgListCurrentUserOrgs(1, 50);
.getApiInterface(ctx)
.orgListCurrentUserOrgs(1, 50);
call.enqueue(new Callback<List<Organization>>() { call.enqueue(new Callback<List<Organization>>() {
@Override @Override
public void onResponse(@NonNull Call<List<Organization>> call, @NonNull retrofit2.Response<List<Organization>> response) { public void onResponse(@NonNull Call<List<Organization>> call, @NonNull retrofit2.Response<List<Organization>> response) {
if(response.code() == 200) { if(response.code() == 200) {
int organizationId = 0; int organizationId = 0;
List<Organization> organizationsList_ = response.body(); List<Organization> organizationsList_ = response.body();
organizationsList.add(userLogin); organizationsList.add(userLogin);
assert organizationsList_ != null; assert organizationsList_ != null;
if(organizationsList_.size() > 0) { if(organizationsList_.size() > 0) {
for(int i = 0; i < organizationsList_.size(); i++) { for(int i = 0; i < organizationsList_.size(); i++) {
if(getIntent().getStringExtra("orgName") != null && !"".equals(getIntent().getStringExtra("orgName"))) { if(getIntent().getStringExtra("orgName") != null && !"".equals(getIntent().getStringExtra("orgName"))) {
if(getIntent().getStringExtra("orgName").equals(organizationsList_.get(i).getUsername())) { if(getIntent().getStringExtra("orgName").equals(organizationsList_.get(i).getUsername())) {
organizationId = i + 1; organizationId = i + 1;
} }
} }
organizationsList.add(organizationsList_.get(i).getUsername()); organizationsList.add(organizationsList_.get(i).getUsername());
} }
} }
ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateRepoActivity.this, R.layout.list_spinner_items, organizationsList); ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateRepoActivity.this, R.layout.list_spinner_items, organizationsList);
spinner.setAdapter(adapter); spinner.setAdapter(adapter);
spinner.setOnItemClickListener ((parent, view, position, id) -> selectedOwner = organizationsList.get(position)); spinner.setOnItemClickListener((parent, view, position, id) -> selectedOwner = organizationsList.get(position));
if(getIntent().getBooleanExtra("organizationAction", false) && organizationId != 0) { if(getIntent().getBooleanExtra("organizationAction", false) && organizationId != 0) {
int selectOwnerById = organizationId; int selectOwnerById = organizationId;
new Handler(Looper.getMainLooper()).postDelayed(() -> { new Handler(Looper.getMainLooper()).postDelayed(() -> {
spinner.setText(organizationsList.get(selectOwnerById), false); spinner.setText(organizationsList.get(selectOwnerById), false);
selectedOwner = organizationsList.get(selectOwnerById); selectedOwner = organizationsList.get(selectOwnerById);
}, 500); }, 500);
getIntent().removeExtra("organizationAction"); getIntent().removeExtra("organizationAction");
} }
enableProcessButton(); enableProcessButton();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
} }
@Override @Override
public void onFailure(@NonNull Call<List<Organization>> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<List<Organization>> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void disableProcessButton() { private void disableProcessButton() {
createRepo.setEnabled(false); createRepo.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
createRepo.setEnabled(true); createRepo.setEnabled(true);
} }
} }

View File

@ -33,250 +33,226 @@ import retrofit2.Callback;
public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClickListener { public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClickListener {
private View.OnClickListener onClickListener; private final String[] permissionList = {"Read", "Write", "Admin"};
private TextView teamName; private final String[] accessControlsList = new String[]{"Code", "Issues", "Pull Request", "Releases", "Wiki", "External Wiki", "External Issues"};
private TextView teamDesc; private final boolean[] selectedAccessControlsTrueFalse = new boolean[]{false, false, false, false, false, false, false};
private TextView teamPermission; public int permissionSelectedChoice = -1;
private TextView teamPermissionDetail; private View.OnClickListener onClickListener;
private TextView teamAccessControls; private TextView teamName;
private TextView teamAccessControlsArray; private TextView teamDesc;
private Button createTeamButton; private TextView teamPermission;
private final String[] permissionList = {"Read", "Write", "Admin"}; private TextView teamPermissionDetail;
public int permissionSelectedChoice = -1; private TextView teamAccessControls;
private TextView teamAccessControlsArray;
private Button createTeamButton;
private List<String> pushAccessList;
private final String[] accessControlsList = new String[] { @Override
"Code", public void onCreate(Bundle savedInstanceState) {
"Issues",
"Pull Request",
"Releases",
"Wiki",
"External Wiki",
"External Issues"
};
private List<String> pushAccessList; super.onCreate(savedInstanceState);
private final boolean[] selectedAccessControlsTrueFalse = new boolean[]{ ActivityCreateTeamByOrgBinding activityCreateTeamByOrgBinding = ActivityCreateTeamByOrgBinding.inflate(getLayoutInflater());
false, setContentView(activityCreateTeamByOrgBinding.getRoot());
false,
false,
false,
false,
false,
false
};
@Override boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
ActivityCreateTeamByOrgBinding activityCreateTeamByOrgBinding = ActivityCreateTeamByOrgBinding.inflate(getLayoutInflater()); ImageView closeActivity = activityCreateTeamByOrgBinding.close;
setContentView(activityCreateTeamByOrgBinding.getRoot()); teamName = activityCreateTeamByOrgBinding.teamName;
teamDesc = activityCreateTeamByOrgBinding.teamDesc;
teamPermission = activityCreateTeamByOrgBinding.teamPermission;
teamPermissionDetail = activityCreateTeamByOrgBinding.teamPermissionDetail;
teamAccessControls = activityCreateTeamByOrgBinding.teamAccessControls;
teamAccessControlsArray = activityCreateTeamByOrgBinding.teamAccessControlsArray;
createTeamButton = activityCreateTeamByOrgBinding.createTeamButton;
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); teamName.requestFocus();
assert imm != null;
imm.showSoftInput(teamName, InputMethodManager.SHOW_IMPLICIT);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); initCloseListener();
closeActivity.setOnClickListener(onClickListener);
ImageView closeActivity = activityCreateTeamByOrgBinding.close; teamPermission.setOnClickListener(view -> {
teamName = activityCreateTeamByOrgBinding.teamName;
teamDesc = activityCreateTeamByOrgBinding.teamDesc;
teamPermission = activityCreateTeamByOrgBinding.teamPermission;
teamPermissionDetail = activityCreateTeamByOrgBinding.teamPermissionDetail;
teamAccessControls = activityCreateTeamByOrgBinding.teamAccessControls;
teamAccessControlsArray = activityCreateTeamByOrgBinding.teamAccessControlsArray;
createTeamButton = activityCreateTeamByOrgBinding.createTeamButton;
teamName.requestFocus();
assert imm != null;
imm.showSoftInput(teamName, InputMethodManager.SHOW_IMPLICIT);
initCloseListener();
closeActivity.setOnClickListener(onClickListener);
teamPermission.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilderPerm = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilderPerm = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.newTeamPermission).setCancelable(permissionSelectedChoice != -1)
.setTitle(R.string.newTeamPermission) .setSingleChoiceItems(permissionList, permissionSelectedChoice, (dialogInterface, i) -> {
.setCancelable(permissionSelectedChoice != -1)
.setSingleChoiceItems(permissionList, permissionSelectedChoice, (dialogInterface, i) -> {
permissionSelectedChoice = i; permissionSelectedChoice = i;
teamPermission.setText(permissionList[i]); teamPermission.setText(permissionList[i]);
switch(permissionList[i]) { switch(permissionList[i]) {
case "Read": case "Read":
teamPermissionDetail.setVisibility(View.VISIBLE); teamPermissionDetail.setVisibility(View.VISIBLE);
teamPermissionDetail.setText(R.string.newTeamPermissionRead); teamPermissionDetail.setText(R.string.newTeamPermissionRead);
break; break;
case "Write": case "Write":
teamPermissionDetail.setVisibility(View.VISIBLE); teamPermissionDetail.setVisibility(View.VISIBLE);
teamPermissionDetail.setText(R.string.newTeamPermissionWrite); teamPermissionDetail.setText(R.string.newTeamPermissionWrite);
break; break;
case "Admin": case "Admin":
teamPermissionDetail.setVisibility(View.VISIBLE); teamPermissionDetail.setVisibility(View.VISIBLE);
teamPermissionDetail.setText(R.string.newTeamPermissionAdmin); teamPermissionDetail.setText(R.string.newTeamPermissionAdmin);
break; break;
default: default:
teamPermissionDetail.setVisibility(View.GONE); teamPermissionDetail.setVisibility(View.GONE);
break; break;
} }
dialogInterface.dismiss(); dialogInterface.dismiss();
}); });
materialAlertDialogBuilderPerm.create().show(); materialAlertDialogBuilderPerm.create().show();
}); });
teamAccessControls.setOnClickListener(v -> { teamAccessControls.setOnClickListener(v -> {
teamAccessControls.setText(""); teamAccessControls.setText("");
teamAccessControlsArray.setText(""); teamAccessControlsArray.setText("");
pushAccessList = Arrays.asList(accessControlsList); pushAccessList = Arrays.asList(accessControlsList);
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setMultiChoiceItems(accessControlsList, selectedAccessControlsTrueFalse, (dialog, which, isChecked) -> {
.setMultiChoiceItems(accessControlsList, selectedAccessControlsTrueFalse, (dialog, which, isChecked) -> {}) }).setTitle(R.string.newTeamAccessControls).setPositiveButton(R.string.okButton, (dialog, which) -> {
.setTitle(R.string.newTeamAccessControls)
.setPositiveButton(R.string.okButton, (dialog, which) -> {
int selectedVal = 0; int selectedVal = 0;
while(selectedVal < selectedAccessControlsTrueFalse.length) while(selectedVal < selectedAccessControlsTrueFalse.length) {
{ boolean value = selectedAccessControlsTrueFalse[selectedVal];
boolean value = selectedAccessControlsTrueFalse[selectedVal];
String repoCode = ""; String repoCode = "";
if(selectedVal == 0) { if(selectedVal == 0) {
repoCode = "repo.code"; repoCode = "repo.code";
} }
if(selectedVal == 1) { if(selectedVal == 1) {
repoCode = "repo.issues"; repoCode = "repo.issues";
} }
if(selectedVal == 2) { if(selectedVal == 2) {
repoCode = "repo.pulls"; repoCode = "repo.pulls";
} }
if(selectedVal == 3) { if(selectedVal == 3) {
repoCode = "repo.releases"; repoCode = "repo.releases";
} }
if(selectedVal == 4) { if(selectedVal == 4) {
repoCode = "repo.wiki"; repoCode = "repo.wiki";
} }
if(selectedVal == 5) { if(selectedVal == 5) {
repoCode = "repo.ext_wiki"; repoCode = "repo.ext_wiki";
} }
if(selectedVal == 6) { if(selectedVal == 6) {
repoCode = "repo.ext_issues"; repoCode = "repo.ext_issues";
} }
if(value){ if(value) {
teamAccessControls.setText(getString(R.string.newTeamPermissionValues, teamAccessControls.getText(), pushAccessList.get(selectedVal))); teamAccessControls.setText(getString(R.string.newTeamPermissionValues, teamAccessControls.getText(), pushAccessList.get(selectedVal)));
teamAccessControlsArray.setText(getString(R.string.newTeamPermissionValuesFinal, teamAccessControlsArray.getText(), repoCode)); teamAccessControlsArray.setText(getString(R.string.newTeamPermissionValuesFinal, teamAccessControlsArray.getText(), repoCode));
} }
selectedVal++; selectedVal++;
} }
String data = String.valueOf(teamAccessControls.getText()); String data = String.valueOf(teamAccessControls.getText());
if(!data.equals("")) { if(!data.equals("")) {
teamAccessControls.setText(data.substring(0, data.length() - 2)); teamAccessControls.setText(data.substring(0, data.length() - 2));
} }
String dataArray = String.valueOf(teamAccessControlsArray.getText()); String dataArray = String.valueOf(teamAccessControlsArray.getText());
if(!dataArray.equals("")) { if(!dataArray.equals("")) {
teamAccessControlsArray.setText(dataArray.substring(0, dataArray.length() - 2)); teamAccessControlsArray.setText(dataArray.substring(0, dataArray.length() - 2));
} }
}); });
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
}); });
createTeamButton.setEnabled(false); createTeamButton.setEnabled(false);
if(!connToInternet) { if(!connToInternet) {
createTeamButton.setEnabled(false); createTeamButton.setEnabled(false);
GradientDrawable shape = new GradientDrawable(); GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(8); shape.setCornerRadius(8);
shape.setColor(ResourcesCompat.getColor(getResources(), R.color.hintColor, null)); shape.setColor(ResourcesCompat.getColor(getResources(), R.color.hintColor, null));
createTeamButton.setBackground(shape); createTeamButton.setBackground(shape);
} }
else { else {
createTeamButton.setEnabled(true); createTeamButton.setEnabled(true);
createTeamButton.setOnClickListener(this); createTeamButton.setOnClickListener(this);
} }
} }
private void processCreateTeam() { private void processCreateTeam() {
final String orgName = getIntent().getStringExtra("orgName"); final String orgName = getIntent().getStringExtra("orgName");
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
String newTeamName = teamName.getText().toString(); String newTeamName = teamName.getText().toString();
String newTeamDesc = teamDesc.getText().toString(); String newTeamDesc = teamDesc.getText().toString();
String newTeamPermission = teamPermission.getText().toString().toLowerCase(); String newTeamPermission = teamPermission.getText().toString().toLowerCase();
String newTeamAccessControls = teamAccessControlsArray.getText().toString(); String newTeamAccessControls = teamAccessControlsArray.getText().toString();
if(!connToInternet) { if(!connToInternet) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return; return;
} }
if (newTeamName.equals("")) { if(newTeamName.equals("")) {
Toasty.error(ctx, getString(R.string.teamNameEmpty)); Toasty.error(ctx, getString(R.string.teamNameEmpty));
return; return;
} }
if(!AppUtil.checkStringsWithAlphaNumericDashDotUnderscore(newTeamName)) { if(!AppUtil.checkStringsWithAlphaNumericDashDotUnderscore(newTeamName)) {
Toasty.warning(ctx, getString(R.string.teamNameError)); Toasty.warning(ctx, getString(R.string.teamNameError));
return; return;
} }
if(!newTeamDesc.equals("")) { if(!newTeamDesc.equals("")) {
if(!AppUtil.checkStrings(newTeamDesc)) { if(!AppUtil.checkStrings(newTeamDesc)) {
Toasty.warning(ctx, getString(R.string.teamDescError)); Toasty.warning(ctx, getString(R.string.teamDescError));
return; return;
} }
if(newTeamDesc.length() > 100) { if(newTeamDesc.length() > 100) {
Toasty.warning(ctx, getString(R.string.teamDescLimit)); Toasty.warning(ctx, getString(R.string.teamDescLimit));
return; return;
} }
} }
if (newTeamPermission.equals("")) { if(newTeamPermission.equals("")) {
Toasty.error(ctx, getString(R.string.teamPermissionEmpty)); Toasty.error(ctx, getString(R.string.teamPermissionEmpty));
return; return;
} }
List<String> newTeamAccessControls_ = new ArrayList<>(Arrays.asList(newTeamAccessControls.split(","))); List<String> newTeamAccessControls_ = new ArrayList<>(Arrays.asList(newTeamAccessControls.split(",")));
for (int i = 0; i < newTeamAccessControls_.size(); i++) { for(int i = 0; i < newTeamAccessControls_.size(); i++) {
newTeamAccessControls_.set(i, newTeamAccessControls_.get(i).trim()); newTeamAccessControls_.set(i, newTeamAccessControls_.get(i).trim());
} }
createNewTeamCall(orgName, newTeamName, newTeamDesc, newTeamPermission, newTeamAccessControls_); createNewTeamCall(orgName, newTeamName, newTeamDesc, newTeamPermission, newTeamAccessControls_);
} }
private void createNewTeamCall(String orgName, String newTeamName, String newTeamDesc, String newTeamPermission, List<String> newTeamAccessControls) { private void createNewTeamCall(String orgName, String newTeamName, String newTeamDesc, String newTeamPermission, List<String> newTeamAccessControls) {
CreateTeamOption createNewTeamJson = new CreateTeamOption(); CreateTeamOption createNewTeamJson = new CreateTeamOption();
createNewTeamJson.setName(newTeamName); createNewTeamJson.setName(newTeamName);
createNewTeamJson.setDescription(newTeamDesc); createNewTeamJson.setDescription(newTeamDesc);
switch(newTeamPermission) { switch(newTeamPermission) {
@ -292,59 +268,57 @@ public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClic
} }
createNewTeamJson.setUnits(newTeamAccessControls); createNewTeamJson.setUnits(newTeamAccessControls);
Call<Team> call3 = RetrofitClient Call<Team> call3 = RetrofitClient.getApiInterface(ctx).orgCreateTeam(orgName, createNewTeamJson);
.getApiInterface(ctx)
.orgCreateTeam(orgName, createNewTeamJson);
call3.enqueue(new Callback<Team>() { call3.enqueue(new Callback<Team>() {
@Override @Override
public void onResponse(@NonNull Call<Team> call, @NonNull retrofit2.Response<Team> response2) { public void onResponse(@NonNull Call<Team> call, @NonNull retrofit2.Response<Team> response2) {
if(response2.isSuccessful()) { if(response2.isSuccessful()) {
if(response2.code() == 201) { if(response2.code() == 201) {
TeamsByOrgFragment.resumeTeams = true; TeamsByOrgFragment.resumeTeams = true;
Toasty.success(ctx, getString(R.string.teamCreated)); Toasty.success(ctx, getString(R.string.teamCreated));
finish(); finish();
} }
} }
else if(response2.code() == 404) { else if(response2.code() == 404) {
Toasty.warning(ctx, getString(R.string.apiNotFound)); Toasty.warning(ctx, getString(R.string.apiNotFound));
} }
else if(response2.code() == 401) { else if(response2.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Team> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Team> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
} }
}); });
} }
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if(v == createTeamButton) { if(v == createTeamButton) {
processCreateTeam(); processCreateTeam();
} }
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -9,11 +9,7 @@ import android.util.Log;
import android.view.View; import android.view.View;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.gitnex.tea4j.v2.models.ContentsResponse; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Organization;
import org.gitnex.tea4j.v2.models.PullRequest;
import org.gitnex.tea4j.v2.models.Repository;
import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.database.api.BaseApi; import org.mian.gitnex.database.api.BaseApi;
@ -95,7 +91,9 @@ public class DeepLinksActivity extends BaseActivity {
hostUrlExternal = hostExternal; hostUrlExternal = hostExternal;
} }
if (hostUrlExternal == null) hostUrlExternal = ""; if(hostUrlExternal == null) {
hostUrlExternal = "";
}
if(hostUri.toLowerCase().contains(hostUrlExternal.toLowerCase())) { if(hostUri.toLowerCase().contains(hostUrlExternal.toLowerCase())) {
@ -131,8 +129,7 @@ public class DeepLinksActivity extends BaseActivity {
finish(); finish();
} }
else { else {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> getUserOrOrg(data.getLastPathSegment()), 500);
getUserOrOrg(data.getLastPathSegment()), 500);
} }
} }
else if(data.getPathSegments().size() == 2) { else if(data.getPathSegments().size() == 2) {
@ -159,12 +156,11 @@ public class DeepLinksActivity extends BaseActivity {
} }
else if(!data.getPathSegments().get(0).equals("") & !data.getLastPathSegment().equals("")) { // go to repo else if(!data.getPathSegments().get(0).equals("") & !data.getLastPathSegment().equals("")) { // go to repo
String repo = data.getLastPathSegment(); String repo = data.getLastPathSegment();
if (repo.endsWith(".git")) { // Git clone URL if(repo.endsWith(".git")) { // Git clone URL
repo = repo.substring(0, repo.length() - 4); repo = repo.substring(0, repo.length() - 4);
} }
String finalRepo = repo; String finalRepo = repo;
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), finalRepo, "repo"), 500);
goToRepoSection(data.getPathSegments().get(0), finalRepo, "repo"), 500);
} }
else { // no action, show options else { // no action, show options
showNoActionButtons(); showNoActionButtons();
@ -179,15 +175,11 @@ public class DeepLinksActivity extends BaseActivity {
issueIntent.putExtra("openedFromLink", "true"); issueIntent.putExtra("openedFromLink", "true");
String[] urlSplitted = data.toString().split("#"); String[] urlSplitted = data.toString().split("#");
if (urlSplitted.length == 2) { if(urlSplitted.length == 2) {
issueIntent.putExtra("issueComment", urlSplitted[1]); issueIntent.putExtra("issueComment", urlSplitted[1]);
} }
IssueContext issue = new IssueContext( IssueContext issue = new IssueContext(new RepositoryContext(data.getPathSegments().get(0), data.getPathSegments().get(1), ctx), Integer.parseInt(data.getLastPathSegment()), "Issue");
new RepositoryContext(data.getPathSegments().get(0), data.getPathSegments().get(1), ctx),
Integer.parseInt(data.getLastPathSegment()),
"Issue"
);
issue.getRepository().saveToDB(ctx); issue.getRepository().saveToDB(ctx);
@ -197,12 +189,10 @@ public class DeepLinksActivity extends BaseActivity {
finish(); finish();
} }
else if(Objects.requireNonNull(data.getLastPathSegment()).contains("issues")) { else if(Objects.requireNonNull(data.getLastPathSegment()).contains("issues")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issue"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issue"), 500);
} }
else if(data.getLastPathSegment().equals("new")) { else if(data.getLastPathSegment().equals("new")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issueNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issueNew"), 500);
} }
else { else {
ctx.startActivity(mainIntent); ctx.startActivity(mainIntent);
@ -216,7 +206,7 @@ public class DeepLinksActivity extends BaseActivity {
new Handler(Looper.getMainLooper()).postDelayed(() -> { new Handler(Looper.getMainLooper()).postDelayed(() -> {
String[] urlSplitted = data.toString().split("#"); String[] urlSplitted = data.toString().split("#");
if (urlSplitted.length == 2) { if(urlSplitted.length == 2) {
issueIntent.putExtra("issueComment", urlSplitted[1]); issueIntent.putExtra("issueComment", urlSplitted[1]);
} }
@ -225,8 +215,7 @@ public class DeepLinksActivity extends BaseActivity {
} }
else if(Objects.requireNonNull(data.getLastPathSegment()).contains("pulls")) { else if(Objects.requireNonNull(data.getLastPathSegment()).contains("pulls")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pull"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pull"), 500);
} }
else if(data.getLastPathSegment().equals("files")) { // pr diff else if(data.getLastPathSegment().equals("files")) { // pr diff
new Handler(Looper.getMainLooper()).postDelayed(() -> { new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -241,36 +230,29 @@ public class DeepLinksActivity extends BaseActivity {
} }
else if(data.getPathSegments().get(2).equals("compare")) { // new pull request else if(data.getPathSegments().get(2).equals("compare")) { // new pull request
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pullNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pullNew"), 500);
} }
else if(data.getPathSegments().get(2).equals("commit")) { else if(data.getPathSegments().get(2).equals("commit")) {
repoIntent.putExtra("sha", data.getLastPathSegment()); repoIntent.putExtra("sha", data.getLastPathSegment());
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commit"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commit"), 500);
} }
else if(data.getPathSegments().get(2).equals("commits")) { // commits list else if(data.getPathSegments().get(2).equals("commits")) { // commits list
String branch = data.getLastPathSegment(); String branch = data.getLastPathSegment();
repoIntent.putExtra("branchName", branch); repoIntent.putExtra("branchName", branch);
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commitsList"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commitsList"), 500);
} }
else if(data.getPathSegments().get(2).equals("milestones") && data.getLastPathSegment().equals("new")) { // new milestone else if(data.getPathSegments().get(2).equals("milestones") && data.getLastPathSegment().equals("new")) { // new milestone
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestonesNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestonesNew"), 500);
} }
else if(data.getPathSegments().get(2).equals("milestones")) { // milestones else if(data.getPathSegments().get(2).equals("milestones")) { // milestones
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
} }
else if(data.getPathSegments().get(2).equals("milestone")) { // milestone else if(data.getPathSegments().get(2).equals("milestone")) { // milestone
repoIntent.putExtra("milestoneId", data.getLastPathSegment()); repoIntent.putExtra("milestoneId", data.getLastPathSegment());
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
} }
else if(data.getPathSegments().get(2).equals("releases") && data.getLastPathSegment().equals("new")) { // new release else if(data.getPathSegments().get(2).equals("releases") && data.getLastPathSegment().equals("new")) { // new release
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "newRelease"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "newRelease"), 500);
} }
else if(data.getPathSegments().get(2).equals("releases")) { // releases else if(data.getPathSegments().get(2).equals("releases")) { // releases
if(data.getPathSegments().size() == 5) { if(data.getPathSegments().size() == 5) {
@ -278,49 +260,39 @@ public class DeepLinksActivity extends BaseActivity {
repoIntent.putExtra("releaseTagName", data.getLastPathSegment()); repoIntent.putExtra("releaseTagName", data.getLastPathSegment());
} }
} }
new Handler(Looper.getMainLooper()).postDelayed( new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "releases"), 500);
() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1),
"releases"), 500);
} }
else if(data.getPathSegments().get(2).equals("labels")) { // labels else if(data.getPathSegments().get(2).equals("labels")) { // labels
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "labels"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "labels"), 500);
} }
else if(data.getPathSegments().get(2).equals("settings")) { // repo settings else if(data.getPathSegments().get(2).equals("settings")) { // repo settings
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "settings"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "settings"), 500);
} }
else if(data.getLastPathSegment().equals("branches")) { // branches list else if(data.getLastPathSegment().equals("branches")) { // branches list
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branchesList"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branchesList"), 500);
} }
else if(data.getPathSegments().size() == 5 && data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // branch else if(data.getPathSegments().size() == 5 && data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // branch
repoIntent.putExtra("selectedBranch", data.getLastPathSegment()); repoIntent.putExtra("selectedBranch", data.getLastPathSegment());
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branch"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branch"), 500);
} }
else if(data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // file/dir else if(data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // file/dir
StringBuilder filePath = new StringBuilder(); StringBuilder filePath = new StringBuilder();
ArrayList<String> segments = new ArrayList<>(data.getPathSegments()); ArrayList<String> segments = new ArrayList<>(data.getPathSegments());
segments.subList(0, 5).clear(); segments.subList(0, 5).clear();
for (String item : segments) { for(String item : segments) {
filePath.append(item); filePath.append(item);
filePath.append("/"); filePath.append("/");
} }
filePath.deleteCharAt(filePath.toString().length() - 1); filePath.deleteCharAt(filePath.toString().length() - 1);
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> getFile(data.getPathSegments().get(0), data.getPathSegments().get(1), filePath.toString(), data.getPathSegments().get(4)), 500);
getFile(data.getPathSegments().get(0),
data.getPathSegments().get(1), filePath.toString(), data.getPathSegments().get(4)), 500);
} }
else if(data.getPathSegments().get(2).equals("wiki")) { // wiki else if(data.getPathSegments().get(2).equals("wiki")) { // wiki
if(data.getQueryParameter("action") != null && data.getQueryParameter("action").equalsIgnoreCase("_new")) { if(data.getQueryParameter("action") != null && data.getQueryParameter("action").equalsIgnoreCase("_new")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wikiNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wikiNew"), 500);
} }
else { else {
new Handler(Looper.getMainLooper()).postDelayed( new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wiki"), 500);
() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wiki"), 500);
} }
} }
else { // no action, show options else { // no action, show options
@ -352,9 +324,7 @@ public class DeepLinksActivity extends BaseActivity {
Integer port = data.getPort() >= 0 ? data.getPort() : null; Integer port = data.getPort() >= 0 ? data.getPort() : null;
URI host = UrlBuilder.fromString(UrlHelper.fixScheme(data.getHost(), "https")) URI host = UrlBuilder.fromString(UrlHelper.fixScheme(data.getHost(), "https")).withPort(port).toUri();
.withPort(port)
.toUri();
AppUtil.openUrlInBrowser(this, String.valueOf(host)); AppUtil.openUrlInBrowser(this, String.valueOf(host));
finish(); finish();
@ -371,9 +341,7 @@ public class DeepLinksActivity extends BaseActivity {
private void getPullRequest(String repoOwner, String repoName, int index) { private void getPullRequest(String repoOwner, String repoName, int index) {
Call<PullRequest> call = RetrofitClient Call<PullRequest> call = RetrofitClient.getApiInterface(ctx).repoGetPullRequest(repoOwner, repoName, (long) index);
.getApiInterface(ctx)
.repoGetPullRequest(repoOwner, repoName, (long) index);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -417,9 +385,7 @@ public class DeepLinksActivity extends BaseActivity {
private void goToRepoSection(String repoOwner, String repoName, String type) { private void goToRepoSection(String repoOwner, String repoName, String type) {
Call<Repository> call = RetrofitClient Call<Repository> call = RetrofitClient.getApiInterface(ctx).repoGet(repoOwner, repoName);
.getApiInterface(ctx)
.repoGet(repoOwner, repoName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -559,7 +525,7 @@ public class DeepLinksActivity extends BaseActivity {
goToRepoSection(owner, repo, "dir"); goToRepoSection(owner, repo, "dir");
} }
private void showNoActionButtons() { private void showNoActionButtons() {
viewBinding.progressBar.setVisibility(View.GONE); viewBinding.progressBar.setVisibility(View.GONE);
switch(tinyDB.getInt("defaultScreenId")) { switch(tinyDB.getInt("defaultScreenId")) {
@ -627,4 +593,5 @@ public class DeepLinksActivity extends BaseActivity {
}); });
} }
} }
} }

View File

@ -29,20 +29,15 @@ public class DiffActivity extends BaseActivity {
@Override @Override
public void handleOnBackPressed() { public void handleOnBackPressed() {
if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) { if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) {
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction() }
.replace(R.id.fragment_container, fragment) else {
.commit();
} else {
finish(); finish();
} }
} }
}); });
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
} }

View File

@ -11,12 +11,7 @@ import android.util.Log;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.EditIssueOption; import org.gitnex.tea4j.v2.models.EditIssueOption;
import org.gitnex.tea4j.v2.models.Issue; import org.gitnex.tea4j.v2.models.Issue;
@ -33,12 +28,7 @@ import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -48,321 +38,311 @@ import retrofit2.Callback;
public class EditIssueActivity extends BaseActivity implements View.OnClickListener { public class EditIssueActivity extends BaseActivity implements View.OnClickListener {
private View.OnClickListener onClickListener; private final String msState = "open";
private int resultLimit; private final LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private View.OnClickListener onClickListener;
private EditText editIssueTitle; private int resultLimit;
private EditText editIssueDescription; private EditText editIssueTitle;
private TextView editIssueDueDate; private EditText editIssueDescription;
private Button editIssueButton; private TextView editIssueDueDate;
private AutoCompleteTextView editIssueMilestoneSpinner; private Button editIssueButton;
private AutoCompleteTextView editIssueMilestoneSpinner;
private final String msState = "open"; private int milestoneId = 0;
private int milestoneId = 0;
private Date currentDate = null; private Date currentDate = null;
private LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private IssueContext issue; private IssueContext issue;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityEditIssueBinding activityEditIssueBinding = ActivityEditIssueBinding.inflate(getLayoutInflater()); ActivityEditIssueBinding activityEditIssueBinding = ActivityEditIssueBinding.inflate(getLayoutInflater());
setContentView(activityEditIssueBinding.getRoot()); setContentView(activityEditIssueBinding.getRoot());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
resultLimit = Constants.getCurrentResultLimit(ctx); resultLimit = Constants.getCurrentResultLimit(ctx);
issue = IssueContext.fromIntent(getIntent()); issue = IssueContext.fromIntent(getIntent());
ImageView closeActivity = activityEditIssueBinding.close; ImageView closeActivity = activityEditIssueBinding.close;
editIssueButton = activityEditIssueBinding.editIssueButton; editIssueButton = activityEditIssueBinding.editIssueButton;
TextView toolbar_title = activityEditIssueBinding.toolbarTitle; TextView toolbar_title = activityEditIssueBinding.toolbarTitle;
editIssueTitle = activityEditIssueBinding.editIssueTitle; editIssueTitle = activityEditIssueBinding.editIssueTitle;
editIssueDescription = activityEditIssueBinding.editIssueDescription; editIssueDescription = activityEditIssueBinding.editIssueDescription;
editIssueDueDate = activityEditIssueBinding.editIssueDueDate; editIssueDueDate = activityEditIssueBinding.editIssueDueDate;
editIssueTitle.requestFocus(); editIssueTitle.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(editIssueTitle, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(editIssueTitle, InputMethodManager.SHOW_IMPLICIT);
editIssueDescription.setOnTouchListener((touchView, motionEvent) -> { editIssueDescription.setOnTouchListener((touchView, motionEvent) -> {
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) { if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
return false; return false;
}); });
editIssueMilestoneSpinner = findViewById(R.id.editIssueMilestoneSpinner); editIssueMilestoneSpinner = findViewById(R.id.editIssueMilestoneSpinner);
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
editIssueDueDate.setOnClickListener(this); editIssueDueDate.setOnClickListener(this);
editIssueButton.setOnClickListener(this); editIssueButton.setOnClickListener(this);
if(issue.getIssueType().equalsIgnoreCase("Pull")) { if(issue.getIssueType().equalsIgnoreCase("Pull")) {
toolbar_title.setText(getString(R.string.editPrNavHeader, String.valueOf(issue.getIssueIndex()))); toolbar_title.setText(getString(R.string.editPrNavHeader, String.valueOf(issue.getIssueIndex())));
} }
else { else {
toolbar_title.setText(getString(R.string.editIssueNavHeader, String.valueOf(issue.getIssueIndex()))); toolbar_title.setText(getString(R.string.editIssueNavHeader, String.valueOf(issue.getIssueIndex())));
} }
disableProcessButton(); disableProcessButton();
getIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getIssueIndex(), resultLimit); getIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getIssueIndex(), resultLimit);
if(!issue.getRepository().getPermissions().isPush()) { if(!issue.getRepository().getPermissions().isPush()) {
findViewById(R.id.editIssueMilestoneSpinnerLayout).setVisibility(View.GONE); findViewById(R.id.editIssueMilestoneSpinnerLayout).setVisibility(View.GONE);
findViewById(R.id.editIssueDueDateLayout).setVisibility(View.GONE); findViewById(R.id.editIssueDueDateLayout).setVisibility(View.GONE);
} }
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void processEditIssue() { private void processEditIssue() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
String editIssueTitleForm = editIssueTitle.getText().toString(); String editIssueTitleForm = editIssueTitle.getText().toString();
String editIssueDescriptionForm = editIssueDescription.getText().toString(); String editIssueDescriptionForm = editIssueDescription.getText().toString();
if(!connToInternet) { if(!connToInternet) {
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return; return;
} }
if (editIssueTitleForm.equals("")) { if(editIssueTitleForm.equals("")) {
Toasty.error(ctx, getString(R.string.issueTitleEmpty)); Toasty.error(ctx, getString(R.string.issueTitleEmpty));
return; return;
} }
disableProcessButton(); disableProcessButton();
editIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getIssueIndex(), editIssueTitleForm, editIssueDescriptionForm, editIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getIssueIndex(), editIssueTitleForm, editIssueDescriptionForm, milestoneId);
milestoneId); }
}
private void editIssue(String repoOwner, String repoName, int issueIndex, String title, String description, int milestoneId) { private void editIssue(String repoOwner, String repoName, int issueIndex, String title, String description, int milestoneId) {
EditIssueOption issueData = new EditIssueOption(); EditIssueOption issueData = new EditIssueOption();
issueData.setTitle(title); issueData.setTitle(title);
issueData.setBody(description); issueData.setBody(description);
issueData.setDueDate(currentDate); issueData.setDueDate(currentDate);
issueData.setMilestone((long) milestoneId); issueData.setMilestone((long) milestoneId);
Call<Issue> call = RetrofitClient Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueEditIssue(repoOwner, repoName, (long) issueIndex, issueData);
.getApiInterface(ctx)
.issueEditIssue(repoOwner, repoName, (long) issueIndex, issueData);
call.enqueue(new Callback<Issue>() { call.enqueue(new Callback<Issue>() {
@Override @Override
public void onResponse(@NonNull Call<Issue> call, @NonNull retrofit2.Response<Issue> response) { public void onResponse(@NonNull Call<Issue> call, @NonNull retrofit2.Response<Issue> response) {
if(response.code() == 201) { if(response.code() == 201) {
if(issue.getIssueType().equalsIgnoreCase("Pull")) { if(issue.getIssueType().equalsIgnoreCase("Pull")) {
Toasty.success(ctx, getString(R.string.editPrSuccessMessage)); Toasty.success(ctx, getString(R.string.editPrSuccessMessage));
} }
else { else {
Toasty.success(ctx, getString(R.string.editIssueSuccessMessage)); Toasty.success(ctx, getString(R.string.editIssueSuccessMessage));
} }
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("issueEdited", true); result.putExtra("issueEdited", true);
IssuesFragment.resumeIssues = issue.getIssue().getPullRequest() == null; IssuesFragment.resumeIssues = issue.getIssue().getPullRequest() == null;
PullRequestsFragment.resumePullRequests = issue.getIssue().getPullRequest() != null; PullRequestsFragment.resumePullRequests = issue.getIssue().getPullRequest() != null;
setResult(200, result); setResult(200, result);
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Issue> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Issue> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (v == editIssueDueDate) { if(v == editIssueDueDate) {
final Calendar c = Calendar.getInstance(); final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
editIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); editIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
datePickerDialog.show(); datePickerDialog.show();
} }
else if(v == editIssueButton) { else if(v == editIssueButton) {
processEditIssue(); processEditIssue();
} }
} }
private void getIssue(final String repoOwner, final String repoName, int issueIndex, int resultLimit) { private void getIssue(final String repoOwner, final String repoName, int issueIndex, int resultLimit) {
Call<Issue> call = RetrofitClient Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueGetIssue(repoOwner, repoName, (long) issueIndex);
.getApiInterface(ctx)
.issueGetIssue(repoOwner, repoName, (long) issueIndex);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Issue> call, @NonNull retrofit2.Response<Issue> response) { public void onResponse(@NonNull Call<Issue> call, @NonNull retrofit2.Response<Issue> response) {
if(response.code() == 200) { if(response.code() == 200) {
assert response.body() != null; assert response.body() != null;
editIssueTitle.setText(response.body().getTitle()); editIssueTitle.setText(response.body().getTitle());
editIssueDescription.setText(response.body().getBody()); editIssueDescription.setText(response.body().getBody());
Milestone currentMilestone = response.body().getMilestone(); Milestone currentMilestone = response.body().getMilestone();
// get milestones list // get milestones list
if(response.body().getId() > 0) { if(response.body().getId() > 0) {
Call<List<Milestone>> call_ = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit); Call<List<Milestone>> call_ = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
call_.enqueue(new Callback<>() { call_.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<List<Milestone>> call, @NonNull retrofit2.Response<List<Milestone>> response_) { public void onResponse(@NonNull Call<List<Milestone>> call, @NonNull retrofit2.Response<List<Milestone>> response_) {
if(response_.code() == 200) { if(response_.code() == 200) {
List<Milestone> milestonesList_ = response_.body(); List<Milestone> milestonesList_ = response_.body();
assert milestonesList_ != null; assert milestonesList_ != null;
Milestone ms = new Milestone(); Milestone ms = new Milestone();
ms.setId(0L); ms.setId(0L);
ms.setTitle(getString(R.string.issueCreatedNoMilestone)); ms.setTitle(getString(R.string.issueCreatedNoMilestone));
milestonesList.put(ms.getTitle(), ms); milestonesList.put(ms.getTitle(), ms);
if(milestonesList_.size() > 0) { if(milestonesList_.size() > 0) {
for(Milestone milestone : milestonesList_) { for(Milestone milestone : milestonesList_) {
//Don't translate "open" is a enum //Don't translate "open" is a enum
if(milestone.getState().equals("open")) { if(milestone.getState().equals("open")) {
milestonesList.put(milestone.getTitle(), milestone); milestonesList.put(milestone.getTitle(), milestone);
} }
} }
} }
ArrayAdapter<String> adapter = new ArrayAdapter<>(EditIssueActivity.this, R.layout.list_spinner_items, new ArrayList<>(milestonesList.keySet())); ArrayAdapter<String> adapter = new ArrayAdapter<>(EditIssueActivity.this, R.layout.list_spinner_items, new ArrayList<>(milestonesList.keySet()));
editIssueMilestoneSpinner.setAdapter(adapter); editIssueMilestoneSpinner.setAdapter(adapter);
editIssueMilestoneSpinner.setOnItemClickListener((parent, view, position, id) -> { editIssueMilestoneSpinner.setOnItemClickListener((parent, view, position, id) -> {
if(position == 0) { if(position == 0) {
milestoneId = 0; milestoneId = 0;
} }
else if(view instanceof TextView) { else if(view instanceof TextView) {
milestoneId = Math.toIntExact( milestoneId = Math.toIntExact(Objects.requireNonNull(milestonesList.get(((TextView) view).getText().toString())).getId());
Objects.requireNonNull(milestonesList.get(((TextView) view).getText().toString())).getId()); }
} });
});
new Handler(Looper.getMainLooper()).postDelayed(() -> { new Handler(Looper.getMainLooper()).postDelayed(() -> {
if(currentMilestone != null) { if(currentMilestone != null) {
milestoneId = Math.toIntExact(currentMilestone.getId()); milestoneId = Math.toIntExact(currentMilestone.getId());
editIssueMilestoneSpinner.setText(currentMilestone.getTitle(), false); editIssueMilestoneSpinner.setText(currentMilestone.getTitle(), false);
} else { }
else {
milestoneId = 0; milestoneId = 0;
editIssueMilestoneSpinner.setText(getString(R.string.issueCreatedNoMilestone), false); editIssueMilestoneSpinner.setText(getString(R.string.issueCreatedNoMilestone), false);
} }
}, 500); }, 500);
enableProcessButton(); enableProcessButton();
} }
} }
@Override @Override
public void onFailure(@NonNull Call<List<Milestone>> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<List<Milestone>> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
} }
}); });
} }
// get milestones list // get milestones list
if(response.body().getDueDate() != null) { if(response.body().getDueDate() != null) {
@SuppressLint("SimpleDateFormat") DateFormat formatter = new SimpleDateFormat("yyyy-M-dd"); @SuppressLint("SimpleDateFormat") DateFormat formatter = new SimpleDateFormat("yyyy-M-dd");
String dueDate = formatter.format(response.body().getDueDate()); String dueDate = formatter.format(response.body().getDueDate());
editIssueDueDate.setText(dueDate); editIssueDueDate.setText(dueDate);
} }
//enableProcessButton(); //enableProcessButton();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else { else {
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<Issue> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Issue> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
} }
}); });
} }
private void disableProcessButton() { private void disableProcessButton() {
editIssueButton.setEnabled(false); editIssueButton.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
editIssueButton.setEnabled(true); editIssueButton.setEnabled(true);
} }
@Override @Override
public void onResume() { public void onResume() {

View File

@ -8,11 +8,7 @@ import android.graphics.Bitmap;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.text.method.ScrollingMovementMethod; import android.text.method.ScrollingMovementMethod;
import android.view.Gravity; import android.view.*;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts; import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
@ -23,12 +19,7 @@ import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.ActivityFileViewBinding; import org.mian.gitnex.databinding.ActivityFileViewBinding;
import org.mian.gitnex.fragments.BottomSheetFileViewerFragment; import org.mian.gitnex.fragments.BottomSheetFileViewerFragment;
import org.mian.gitnex.helpers.AlertDialogs; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Constants;
import org.mian.gitnex.helpers.Images;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.mian.gitnex.notifications.Notifications; import org.mian.gitnex.notifications.Notifications;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
@ -48,25 +39,82 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
private ActivityFileViewBinding binding; private ActivityFileViewBinding binding;
private ContentsResponse file; private ContentsResponse file;
private RepositoryContext repository; private RepositoryContext repository;
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
assert result.getData() != null;
try {
OutputStream outputStream = getContentResolver().openOutputStream(result.getData().getData());
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, ctx.getPackageName()).setContentTitle(getString(R.string.fileViewerNotificationTitleStarted))
.setContentText(getString(R.string.fileViewerNotificationDescriptionStarted, file.getName())).setSmallIcon(R.drawable.gitnex_transparent).setPriority(NotificationCompat.PRIORITY_LOW)
.setChannelId(Constants.downloadNotificationChannelId).setProgress(100, 0, false).setOngoing(true);
int notificationId = Notifications.uniqueNotificationId(ctx);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
Thread thread = new Thread(() -> {
try {
Call<ResponseBody> call = RetrofitClient.getWebInterface(ctx).getFileContents(repository.getOwner(), repository.getName(), repository.getBranchRef(), file.getPath());
Response<ResponseBody> response = call.execute();
assert response.body() != null;
AppUtil.copyProgress(response.body().byteStream(), outputStream, file.getSize(), progress -> {
builder.setProgress(100, progress, false);
notificationManager.notify(notificationId, builder.build());
});
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFinished)).setContentText(getString(R.string.fileViewerNotificationDescriptionFinished, file.getName()));
}
catch(IOException ignored) {
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFailed)).setContentText(getString(R.string.fileViewerNotificationDescriptionFailed, file.getName()));
}
finally {
builder.setProgress(0, 0, false).setOngoing(false);
notificationManager.notify(notificationId, builder.build());
}
});
thread.start();
}
catch(IOException ignored) {
}
}
});
private boolean renderMd = false; private boolean renderMd = false;
private boolean processable = false; private boolean processable = false;
public ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
public ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), if(result.getResultCode() == 200) {
result -> { assert result.getData() != null;
if(result.getResultCode() == 200) { if(result.getData().getBooleanExtra("fileModified", false)) {
assert result.getData() != null; switch(result.getData().getIntExtra("fileAction", CreateFileActivity.FILE_ACTION_EDIT)) {
if(result.getData().getBooleanExtra("fileModified", false)) { case CreateFileActivity.FILE_ACTION_CREATE:
switch(result.getData().getIntExtra("fileAction", CreateFileActivity.FILE_ACTION_EDIT)) { case CreateFileActivity.FILE_ACTION_EDIT:
case CreateFileActivity.FILE_ACTION_CREATE: getSingleFileContents(repository.getOwner(), repository.getName(), file.getPath(), repository.getBranchRef());
case CreateFileActivity.FILE_ACTION_EDIT: break;
getSingleFileContents(repository.getOwner(), repository.getName(), file.getPath(), repository.getBranchRef()); default:
break; finish();
default:
finish();
}
} }
} }
}); }
});
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -93,9 +141,7 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
Thread thread = new Thread(() -> { Thread thread = new Thread(() -> {
Call<ResponseBody> call = RetrofitClient Call<ResponseBody> call = RetrofitClient.getWebInterface(ctx).getFileContents(owner, repo, ref, filename);
.getWebInterface(ctx)
.getFileContents(owner, repo, ref, filename);
try { try {
@ -153,7 +199,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
binding.contents.setVisibility(View.GONE); binding.contents.setVisibility(View.GONE);
binding.markdownFrame.setVisibility(View.VISIBLE); binding.markdownFrame.setVisibility(View.VISIBLE);
} else { }
else {
binding.markdownFrame.setVisibility(View.GONE); binding.markdownFrame.setVisibility(View.GONE);
binding.contents.setVisibility(View.VISIBLE); binding.contents.setVisibility(View.VISIBLE);
} }
@ -178,14 +225,16 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
binding.markdownTv.setTypeface(null, Typeface.BOLD); binding.markdownTv.setTypeface(null, Typeface.BOLD);
}); });
} }
} else { }
else {
runOnUiThread(() -> { runOnUiThread(() -> {
binding.markdownTv.setText(""); binding.markdownTv.setText("");
binding.progressBar.setVisibility(View.GONE); binding.progressBar.setVisibility(View.GONE);
}); });
} }
} else { }
else {
switch(response.code()) { switch(response.code()) {
@ -206,7 +255,9 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
} }
} }
} catch(IOException ignored) {} }
catch(IOException ignored) {
}
}); });
@ -221,11 +272,9 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
inflater.inflate(R.menu.generic_nav_dotted_menu, menu); inflater.inflate(R.menu.generic_nav_dotted_menu, menu);
inflater.inflate(R.menu.markdown_switcher, menu); inflater.inflate(R.menu.markdown_switcher, menu);
if(!FilenameUtils.getExtension(file.getName()) if(!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("md")) {
.equalsIgnoreCase("md")) {
menu.getItem(0) menu.getItem(0).setVisible(false);
.setVisible(false);
} }
return true; return true;
@ -241,7 +290,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
finish(); finish();
return true; return true;
} else if(id == R.id.genericMenu) { }
else if(id == R.id.genericMenu) {
BottomSheetFileViewerFragment bottomSheet = new BottomSheetFileViewerFragment(); BottomSheetFileViewerFragment bottomSheet = new BottomSheetFileViewerFragment();
Bundle opts = repository.getBundle(); Bundle opts = repository.getBundle();
@ -250,7 +300,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
bottomSheet.show(getSupportFragmentManager(), "fileViewerBottomSheet"); bottomSheet.show(getSupportFragmentManager(), "fileViewerBottomSheet");
return true; return true;
} else if(id == R.id.markdown) { }
else if(id == R.id.markdown) {
if(!renderMd) { if(!renderMd) {
if(binding.markdown.getAdapter() == null) { if(binding.markdown.getAdapter() == null) {
@ -261,7 +312,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
binding.markdownFrame.setVisibility(View.VISIBLE); binding.markdownFrame.setVisibility(View.VISIBLE);
renderMd = true; renderMd = true;
} else { }
else {
binding.markdownFrame.setVisibility(View.GONE); binding.markdownFrame.setVisibility(View.GONE);
binding.contents.setVisibility(View.VISIBLE); binding.contents.setVisibility(View.VISIBLE);
@ -270,7 +322,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
return true; return true;
} else { }
else {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
@ -293,8 +346,7 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
if("editFile".equals(text)) { if("editFile".equals(text)) {
if(binding.contents.getContent() != null && if(binding.contents.getContent() != null && !binding.contents.getContent().isEmpty()) {
!binding.contents.getContent().isEmpty()) {
Intent intent = repository.getIntent(ctx, CreateFileActivity.class); Intent intent = repository.getIntent(ctx, CreateFileActivity.class);
@ -305,7 +357,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
editFileLauncher.launch(intent); editFileLauncher.launch(intent);
} else { }
else {
Toasty.error(ctx, getString(R.string.fileTypeCannotBeEdited)); Toasty.error(ctx, getString(R.string.fileTypeCannotBeEdited));
} }
} }
@ -323,72 +376,6 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
} }
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
assert result.getData() != null;
try {
OutputStream outputStream = getContentResolver().openOutputStream(result.getData().getData());
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, ctx.getPackageName())
.setContentTitle(getString(R.string.fileViewerNotificationTitleStarted))
.setContentText(getString(R.string.fileViewerNotificationDescriptionStarted, file.getName()))
.setSmallIcon(R.drawable.gitnex_transparent)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setChannelId(Constants.downloadNotificationChannelId)
.setProgress(100, 0, false)
.setOngoing(true);
int notificationId = Notifications.uniqueNotificationId(ctx);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);;
notificationManager.notify(notificationId, builder.build());
Thread thread = new Thread(() -> {
try {
Call<ResponseBody> call = RetrofitClient
.getWebInterface(ctx)
.getFileContents(repository.getOwner(), repository.getName(), repository.getBranchRef(), file.getPath());
Response<ResponseBody> response = call.execute();
assert response.body() != null;
AppUtil.copyProgress(response.body().byteStream(), outputStream, file.getSize(), progress -> {
builder.setProgress(100, progress, false);
notificationManager.notify(notificationId, builder.build());
});
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFinished))
.setContentText(getString(R.string.fileViewerNotificationDescriptionFinished, file.getName()));
} catch(IOException ignored) {
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFailed))
.setContentText(getString(R.string.fileViewerNotificationDescriptionFailed, file.getName()));
} finally {
builder.setProgress(0,0,false)
.setOngoing(false);
notificationManager.notify(notificationId, builder.build());
}
});
thread.start();
} catch(IOException ignored) {}
}
});
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@ -8,12 +8,7 @@ import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.util.Log; import android.util.Log;
import android.view.Gravity; import android.view.*;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
@ -31,14 +26,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable; import com.amulyakhare.textdrawable.TextDrawable;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.vdurmont.emoji.EmojiParser; import com.vdurmont.emoji.EmojiParser;
import org.gitnex.tea4j.v2.models.EditIssueOption; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Issue;
import org.gitnex.tea4j.v2.models.IssueLabelsOption;
import org.gitnex.tea4j.v2.models.Label;
import org.gitnex.tea4j.v2.models.PullRequest;
import org.gitnex.tea4j.v2.models.Repository;
import org.gitnex.tea4j.v2.models.User;
import org.gitnex.tea4j.v2.models.WatchInfo;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.actions.AssigneesActions; import org.mian.gitnex.actions.AssigneesActions;
import org.mian.gitnex.actions.LabelsActions; import org.mian.gitnex.actions.LabelsActions;
@ -54,29 +42,14 @@ import org.mian.gitnex.databinding.CustomPrInfoDialogBinding;
import org.mian.gitnex.fragments.BottomSheetReplyFragment; import org.mian.gitnex.fragments.BottomSheetReplyFragment;
import org.mian.gitnex.fragments.BottomSheetSingleIssueFragment; import org.mian.gitnex.fragments.BottomSheetSingleIssueFragment;
import org.mian.gitnex.fragments.IssuesFragment; import org.mian.gitnex.fragments.IssuesFragment;
import org.mian.gitnex.helpers.AlertDialogs; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.DividerItemDecorator;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
import org.mian.gitnex.viewmodels.IssueCommentsViewModel; import org.mian.gitnex.viewmodels.IssueCommentsViewModel;
import org.mian.gitnex.views.ReactionList; import org.mian.gitnex.views.ReactionList;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
@ -87,49 +60,46 @@ import retrofit2.Response;
public class IssueDetailActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener, BottomSheetListener { public class IssueDetailActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener, BottomSheetListener {
public static boolean singleIssueUpdate = false;
public static boolean commentPosted = false;
private final List<Label> labelsList = new ArrayList<>();
private final List<User> assigneesList = new ArrayList<>();
public boolean commentEdited = false;
private IssueCommentsAdapter adapter; private IssueCommentsAdapter adapter;
private String repoOwner; private String repoOwner;
private String repoName; private String repoName;
private int issueIndex; private int issueIndex;
private String issueCreator; private String issueCreator;
private IssueContext issue; private IssueContext issue;
private LabelsListAdapter labelsAdapter; private LabelsListAdapter labelsAdapter;
private AssigneesListAdapter assigneesAdapter; private AssigneesListAdapter assigneesAdapter;
private List<Integer> currentLabelsIds = new ArrayList<>(); private List<Integer> currentLabelsIds = new ArrayList<>();
private List<Integer> labelsIds = new ArrayList<>(); private List<Integer> labelsIds = new ArrayList<>();
private final List<Label> labelsList = new ArrayList<>();
private final List<User> assigneesList = new ArrayList<>();
private List<String> assigneesListData = new ArrayList<>(); private List<String> assigneesListData = new ArrayList<>();
private List<String> currentAssignees = new ArrayList<>(); private List<String> currentAssignees = new ArrayList<>();
private ActivityIssueDetailBinding viewBinding; private ActivityIssueDetailBinding viewBinding;
private MaterialAlertDialogBuilder materialAlertDialogBuilder; private MaterialAlertDialogBuilder materialAlertDialogBuilder;
public static boolean singleIssueUpdate = false;
public boolean commentEdited = false;
public static boolean commentPosted = false;
private IssueCommentsViewModel issueCommentsModel; private IssueCommentsViewModel issueCommentsModel;
private Runnable showMenu = () -> {
};
private boolean loadingFinishedIssue = false;
private boolean loadingFinishedPr = false;
private boolean loadingFinishedRepo = false;
public ActivityResultLauncher<Intent> editIssueLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("issueEdited", false)) {
new Handler(Looper.getMainLooper()).postDelayed(() -> {
public ActivityResultLauncher<Intent> editIssueLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), viewBinding.frameAssignees.removeAllViews();
result -> { viewBinding.frameLabels.removeAllViews();
if(result.getResultCode() == 200) { issue.setIssue(null);
assert result.getData() != null; getSingleIssue(repoOwner, repoName, issueIndex);
if(result.getData().getBooleanExtra("issueEdited", false)) {
new Handler(Looper.getMainLooper()).postDelayed(() -> {
viewBinding.frameAssignees.removeAllViews(); }, 500);
viewBinding.frameLabels.removeAllViews();
issue.setIssue(null);
getSingleIssue(repoOwner, repoName, issueIndex);
}, 500);
}
} }
}); }
});
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -174,9 +144,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { viewBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
viewBinding.pullToRefresh.setRefreshing(false); viewBinding.pullToRefresh.setRefreshing(false);
issueCommentsModel issueCommentsModel.loadIssueComments(repoOwner, repoName, issueIndex, ctx);
.loadIssueComments(repoOwner, repoName, issueIndex,
ctx);
}, 500)); }, 500));
@ -212,7 +180,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
} }
@Override @Override
public void labelsInterface(List<String> data) { } public void labelsInterface(List<String> data) {
}
@Override @Override
public void labelsIdsInterface(List<Integer> data) { public void labelsIdsInterface(List<Integer> data) {
@ -230,8 +199,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
assigneesAdapter.updateList(currentAssignees); assigneesAdapter.updateList(currentAssignees);
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate( CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = assigneesBinding.getRoot(); View view = assigneesBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
@ -279,9 +247,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
EditIssueOption updateAssigneeJson = new EditIssueOption().assignees(assigneesListData); EditIssueOption updateAssigneeJson = new EditIssueOption().assignees(assigneesListData);
Call<Issue> call3 = RetrofitClient Call<Issue> call3 = RetrofitClient.getApiInterface(ctx).issueEditIssue(repoOwner, repoName, (long) issueIndex, updateAssigneeJson);
.getApiInterface(ctx)
.issueEditIssue(repoOwner, repoName, (long) issueIndex, updateAssigneeJson);
call3.enqueue(new Callback<>() { call3.enqueue(new Callback<>() {
@ -335,9 +301,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
IssueLabelsOption patchIssueLabels = new IssueLabelsOption(); IssueLabelsOption patchIssueLabels = new IssueLabelsOption();
patchIssueLabels.setLabels(labelIds); patchIssueLabels.setLabels(labelIds);
Call<List<Label>> call = RetrofitClient Call<List<Label>> call = RetrofitClient.getApiInterface(ctx).issueReplaceLabels(repoOwner, repoName, (long) issueIndex, patchIssueLabels);
.getApiInterface(ctx)
.issueReplaceLabels(repoOwner, repoName, (long) issueIndex, patchIssueLabels);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -383,12 +347,10 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
}); });
} }
private Runnable showMenu = () -> {};
private boolean loadingFinishedIssue = false;
private boolean loadingFinishedPr = false;
private boolean loadingFinishedRepo = false;
private void updateMenuState() { private void updateMenuState() {
if(loadingFinishedIssue && loadingFinishedPr && loadingFinishedRepo) showMenu.run(); if(loadingFinishedIssue && loadingFinishedPr && loadingFinishedRepo) {
showMenu.run();
}
} }
@Override @Override
@ -402,7 +364,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
inflater.inflate(R.menu.pr_info_menu, menu); inflater.inflate(R.menu.pr_info_menu, menu);
} }
} }
showMenu = () -> {}; // reset Runnable showMenu = () -> {
}; // reset Runnable
}; };
updateMenuState(); updateMenuState();
return true; return true;
@ -415,8 +378,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
if(id == android.R.id.home) { if(id == android.R.id.home) {
if(issue.hasIssue() && getIntent().getStringExtra("openedFromLink") != null && if(issue.hasIssue() && getIntent().getStringExtra("openedFromLink") != null && getIntent().getStringExtra("openedFromLink").equals("true")) {
getIntent().getStringExtra("openedFromLink").equals("true")) {
Intent intent = issue.getRepository().getIntent(ctx, RepoDetailActivity.class); Intent intent = issue.getRepository().getIntent(ctx, RepoDetailActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
@ -466,9 +428,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.scrollViewComments.post(() -> { viewBinding.scrollViewComments.post(() -> {
issueCommentsModel issueCommentsModel.loadIssueComments(repoOwner, repoName, issueIndex, ctx, () -> viewBinding.scrollViewComments.fullScroll(ScrollView.FOCUS_DOWN));
.loadIssueComments(repoOwner, repoName, issueIndex,
ctx, () -> viewBinding.scrollViewComments.fullScroll(ScrollView.FOCUS_DOWN));
commentPosted = false; commentPosted = false;
}); });
@ -478,9 +438,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.scrollViewComments.post(() -> { viewBinding.scrollViewComments.post(() -> {
issueCommentsModel issueCommentsModel.loadIssueComments(repoOwner, repoName, issueIndex, ctx);
.loadIssueComments(repoOwner, repoName, issueIndex,
ctx);
commentEdited = false; commentEdited = false;
}); });
} }
@ -501,26 +459,25 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
private void fetchDataAsync(String owner, String repo, int index) { private void fetchDataAsync(String owner, String repo, int index) {
issueCommentsModel.getIssueCommentList(owner, repo, index, ctx) issueCommentsModel.getIssueCommentList(owner, repo, index, ctx).observe(this, issueCommentsMain -> {
.observe(this, issueCommentsMain -> {
assert issueCommentsMain != null; assert issueCommentsMain != null;
if(issueCommentsMain.size() > 0) { if(issueCommentsMain.size() > 0) {
viewBinding.divider.setVisibility(View.VISIBLE); viewBinding.divider.setVisibility(View.VISIBLE);
} }
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("repoOwner", repoOwner); bundle.putString("repoOwner", repoOwner);
bundle.putString("repoName", repoName); bundle.putString("repoName", repoName);
bundle.putInt("issueNumber", issueIndex); bundle.putInt("issueNumber", issueIndex);
adapter = new IssueCommentsAdapter(ctx, bundle, issueCommentsMain, getSupportFragmentManager(), this::onResume, issue); adapter = new IssueCommentsAdapter(ctx, bundle, issueCommentsMain, getSupportFragmentManager(), this::onResume, issue);
viewBinding.recyclerView.setAdapter(adapter); viewBinding.recyclerView.setAdapter(adapter);
}); });
} }
private void getSingleIssue(String repoOwner, String repoName, int issueIndex) { private void getSingleIssue(String repoOwner, String repoName, int issueIndex) {
@ -531,8 +488,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
return; return;
} }
Call<Issue> call = RetrofitClient.getApiInterface(ctx) Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueGetIssue(repoOwner, repoName, (long) issueIndex);
.issueGetIssue(repoOwner, repoName, (long) issueIndex);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -575,34 +531,33 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
} }
private void getSubscribed() { private void getSubscribed() {
RetrofitClient.getApiInterface(ctx) RetrofitClient.getApiInterface(ctx).issueCheckSubscription(repoOwner, repoName, (long) issueIndex).enqueue(new Callback<>() {
.issueCheckSubscription(repoOwner, repoName, (long) issueIndex)
.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<WatchInfo> call, @NonNull Response<WatchInfo> response) { public void onResponse(@NonNull Call<WatchInfo> call, @NonNull Response<WatchInfo> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
assert response.body() != null; assert response.body() != null;
issue.setSubscribed(response.body().isSubscribed()); issue.setSubscribed(response.body().isSubscribed());
}
else {
issue.setSubscribed(false);
}
} }
else {
@Override
public void onFailure(@NonNull Call<WatchInfo> call, @NonNull Throwable t) {
issue.setSubscribed(false); issue.setSubscribed(false);
} }
}); }
@Override
public void onFailure(@NonNull Call<WatchInfo> call, @NonNull Throwable t) {
issue.setSubscribed(false);
}
});
} }
private void initWithIssue() { private void initWithIssue() {
if(!issue.getRepository().hasRepository()) { if(!issue.getRepository().hasRepository()) {
getRepoInfo(); getRepoInfo();
} else { }
else {
loadingFinishedRepo = true; loadingFinishedRepo = true;
} }
loadingFinishedIssue = true; loadingFinishedIssue = true;
@ -633,7 +588,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
updateMenuState(); updateMenuState();
viewBinding.issuePrState.setImageResource(R.drawable.ic_issue); viewBinding.issuePrState.setImageResource(R.drawable.ic_issue);
ImageViewCompat.setImageTintList(viewBinding.issuePrState, ColorStateList.valueOf(ctx.getResources().getColor(R.color.iconIssuePrClosedColor))); ImageViewCompat.setImageTintList(viewBinding.issuePrState, ColorStateList.valueOf(ctx.getResources().getColor(R.color.iconIssuePrClosedColor)));
} else { }
else {
loadingFinishedPr = true; loadingFinishedPr = true;
updateMenuState(); updateMenuState();
viewBinding.issuePrState.setImageResource(R.drawable.ic_issue); viewBinding.issuePrState.setImageResource(R.drawable.ic_issue);
@ -645,10 +601,9 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
final String timeFormat = tinyDb.getString("dateFormat", "pretty"); final String timeFormat = tinyDb.getString("dateFormat", "pretty");
issueCreator = issue.getIssue().getUser().getLogin(); issueCreator = issue.getIssue().getUser().getLogin();
PicassoService.getInstance(ctx).get().load(issue.getIssue().getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated) PicassoService.getInstance(ctx).get().load(issue.getIssue().getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(8, 0)).resize(120, 120).centerCrop()
.transform(new RoundedTransformation(8, 0)).resize(120, 120).centerCrop().into(viewBinding.assigneeAvatar); .into(viewBinding.assigneeAvatar);
String issueNumber_ = "<font color='" + ResourcesCompat.getColor(getResources(), R.color.lightGray, null) + "'>" + appCtx.getResources() String issueNumber_ = "<font color='" + ResourcesCompat.getColor(getResources(), R.color.lightGray, null) + "'>" + appCtx.getResources().getString(R.string.hash) + issue.getIssue().getNumber() + "</font>";
.getString(R.string.hash) + issue.getIssue().getNumber() + "</font>";
viewBinding.issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + EmojiParser.parseToUnicode(issue.getIssue().getTitle()), HtmlCompat.FROM_HTML_MODE_LEGACY)); viewBinding.issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + EmojiParser.parseToUnicode(issue.getIssue().getTitle()), HtmlCompat.FROM_HTML_MODE_LEGACY));
String cleanIssueDescription = issue.getIssue().getBody().trim(); String cleanIssueDescription = issue.getIssue().getBody().trim();
@ -681,9 +636,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
ImageView assigneesView = new ImageView(ctx); ImageView assigneesView = new ImageView(ctx);
PicassoService.getInstance(ctx).get().load(issue.getIssue().getAssignees().get(i).getAvatarUrl()) PicassoService.getInstance(ctx).get().load(issue.getIssue().getAssignees().get(i).getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(48, 0)).resize(96, 96)
.placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(48, 0)).resize(96, 96).centerCrop() .centerCrop().into(assigneesView);
.into(assigneesView);
viewBinding.frameAssignees.addView(assigneesView); viewBinding.frameAssignees.addView(assigneesView);
assigneesView.setLayoutParams(params1); assigneesView.setLayoutParams(params1);
@ -721,8 +675,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.assigneesScrollView.setVisibility(View.GONE); viewBinding.assigneesScrollView.setVisibility(View.GONE);
} }
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(issue.getIssue().getLabels() != null) { if(issue.getIssue().getLabels() != null) {
@ -743,10 +696,9 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
int height = AppUtil.getPixelsFromDensity(ctx, 20); int height = AppUtil.getPixelsFromDensity(ctx, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(ctx, 12); int textSize = AppUtil.getPixelsFromScaledDensity(ctx, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT) TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
.textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize) .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(ctx, 10))).height(height).endConfig()
.width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(ctx, 10))) .buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(ctx, 18));
.height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(ctx, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
viewBinding.frameLabels.addView(labelsView); viewBinding.frameLabels.addView(labelsView);
@ -765,8 +717,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", locale); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", locale);
String dueDate = formatter.format(issue.getIssue().getDueDate()); String dueDate = formatter.format(issue.getIssue().getDueDate());
viewBinding.issueDueDate.setText(dueDate); viewBinding.issueDueDate.setText(dueDate);
viewBinding.issueDueDate viewBinding.issueDueDate.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getDueDate()), ctx));
.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getDueDate()), ctx));
} }
else if(timeFormat.equals("normal1")) { else if(timeFormat.equals("normal1")) {
@ -787,8 +738,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
edited = getString(R.string.colorfulBulletSpan) + getString(R.string.modifiedText); edited = getString(R.string.colorfulBulletSpan) + getString(R.string.modifiedText);
viewBinding.issueModified.setVisibility(View.VISIBLE); viewBinding.issueModified.setVisibility(View.VISIBLE);
viewBinding.issueModified.setText(edited); viewBinding.issueModified.setText(edited);
viewBinding.issueModified viewBinding.issueModified.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getUpdatedAt()), ctx));
.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getUpdatedAt()), ctx));
} }
else { else {
@ -821,8 +771,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
if(timeFormat.equals("pretty")) { if(timeFormat.equals("pretty")) {
viewBinding.issueCreatedTime viewBinding.issueCreatedTime.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getCreatedAt()), ctx));
.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getCreatedAt()), ctx));
} }
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -909,4 +858,5 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
} }
}); });
} }
} }

View File

@ -3,30 +3,17 @@ package org.mian.gitnex.activities;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import org.gitnex.tea4j.v2.models.AccessToken; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateAccessTokenOption;
import org.gitnex.tea4j.v2.models.GeneralAPISettings;
import org.gitnex.tea4j.v2.models.ServerVersion;
import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.database.api.BaseApi; import org.mian.gitnex.database.api.BaseApi;
import org.mian.gitnex.database.api.UserAccountsApi; import org.mian.gitnex.database.api.UserAccountsApi;
import org.mian.gitnex.database.models.UserAccount; import org.mian.gitnex.database.models.UserAccount;
import org.mian.gitnex.databinding.ActivityLoginBinding; import org.mian.gitnex.databinding.ActivityLoginBinding;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.NetworkStatusObserver;
import org.mian.gitnex.helpers.PathsHelper;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.UrlHelper;
import org.mian.gitnex.helpers.Version;
import org.mian.gitnex.structs.Protocol; import org.mian.gitnex.structs.Protocol;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -43,15 +30,12 @@ import retrofit2.Callback;
public class LoginActivity extends BaseActivity { public class LoginActivity extends BaseActivity {
private enum LoginType {BASIC, TOKEN}
private Button loginButton; private Button loginButton;
private EditText instanceUrlET, loginUidET, loginPassword, otpCode, loginTokenCode; private EditText instanceUrlET, loginUidET, loginPassword, otpCode, loginTokenCode;
private AutoCompleteTextView protocolSpinner; private AutoCompleteTextView protocolSpinner;
private RadioGroup loginMethod; private RadioGroup loginMethod;
private String device_id = "token"; private String device_id = "token";
private String selectedProtocol; private String selectedProtocol;
private URI instanceUrl; private URI instanceUrl;
private Version giteaVersion; private Version giteaVersion;
private int maxResponseItems = 50; private int maxResponseItems = 50;
@ -96,7 +80,8 @@ public class LoginActivity extends BaseActivity {
if(R.id.loginToken == loginMethod.getCheckedRadioButtonId()) { if(R.id.loginToken == loginMethod.getCheckedRadioButtonId()) {
AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE);
} else { }
else {
AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE);
} }
@ -105,7 +90,8 @@ public class LoginActivity extends BaseActivity {
if(checkedId == R.id.loginToken) { if(checkedId == R.id.loginToken) {
AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE);
} else { }
else {
AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE);
} }
@ -114,7 +100,8 @@ public class LoginActivity extends BaseActivity {
networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> { networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> {
if(hasNetworkConnection) { if(hasNetworkConnection) {
enableProcessButton(); enableProcessButton();
} else { }
else {
disableProcessButton(); disableProcessButton();
loginButton.setText(getResources().getString(R.string.btnLogin)); loginButton.setText(getResources().getString(R.string.btnLogin));
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
@ -148,8 +135,7 @@ public class LoginActivity extends BaseActivity {
URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET.getText().toString().replaceAll("[\\uFEFF|#]", "").trim(), "http")).toUri(); URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET.getText().toString().replaceAll("[\\uFEFF|#]", "").trim(), "http")).toUri();
instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(selectedProtocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")) instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(selectedProtocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")).toUri();
.toUri();
// cache values to make them available the next time the user wants to log in // cache values to make them available the next time the user wants to log in
tinyDB.putString("loginType", loginType.name().toLowerCase()); tinyDB.putString("loginType", loginType.name().toLowerCase());
@ -234,8 +220,7 @@ public class LoginActivity extends BaseActivity {
}); });
} }
private void versionCheck(final String loginUid, final String loginPass, final int loginOTP, final String loginToken, private void versionCheck(final String loginUid, final String loginPass, final int loginOTP, final String loginToken, final LoginType loginType) {
final LoginType loginType) {
Call<ServerVersion> callVersion; Call<ServerVersion> callVersion;
@ -247,10 +232,11 @@ public class LoginActivity extends BaseActivity {
String credential = Credentials.basic(loginUid, loginPass, StandardCharsets.UTF_8); String credential = Credentials.basic(loginUid, loginPass, StandardCharsets.UTF_8);
if (loginOTP != 0) { if(loginOTP != 0) {
callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion(loginOTP); callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion(loginOTP);
} else { }
else {
callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion(); callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion();
} }
@ -277,15 +263,12 @@ public class LoginActivity extends BaseActivity {
if(giteaVersion.less(getString(R.string.versionLow))) { if(giteaVersion.less(getString(R.string.versionLow))) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(getString(R.string.versionAlertDialogHeader))
.setTitle(getString(R.string.versionAlertDialogHeader)) .setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion())).setNeutralButton(getString(R.string.cancelButton), (dialog, which) -> {
.setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion()))
.setNeutralButton(getString(R.string.cancelButton), (dialog, which) -> {
dialog.dismiss(); dialog.dismiss();
enableProcessButton(); enableProcessButton();
}) }).setPositiveButton(getString(R.string.textContinue), (dialog, which) -> {
.setPositiveButton(getString(R.string.textContinue), (dialog, which) -> {
dialog.dismiss(); dialog.dismiss();
login(loginType, loginUid, loginPass, loginOTP, loginToken); login(loginType, loginUid, loginPass, loginOTP, loginToken);
@ -432,8 +415,7 @@ public class LoginActivity extends BaseActivity {
Call<Void> delToken; Call<Void> delToken;
if(loginOTP != 0) { if(loginOTP != 0) {
delToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null) delToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).userDeleteAccessToken(loginOTP, loginUid, String.valueOf(t.getId()));
.userDeleteAccessToken(loginOTP, loginUid, String.valueOf(t.getId()));
} }
else { else {
@ -495,13 +477,11 @@ public class LoginActivity extends BaseActivity {
if(loginOTP != 0) { if(loginOTP != 0) {
callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null) callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).userCreateToken(loginOTP, loginUid, createUserToken);
.userCreateToken(loginOTP, loginUid, createUserToken);
} }
else { else {
callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null) callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).userCreateToken(loginUid, createUserToken);
.userCreateToken(loginUid, createUserToken);
} }
callCreateToken.enqueue(new Callback<>() { callCreateToken.enqueue(new Callback<>() {
@ -539,9 +519,8 @@ public class LoginActivity extends BaseActivity {
UserAccount account; UserAccount account;
if(!userAccountExists) { if(!userAccountExists) {
long accountId = userAccountsApi long accountId = userAccountsApi.createNewAccount(accountName, instanceUrl.toString(), userDetails.getLogin(), newToken.getSha1(), giteaVersion.toString(), maxResponseItems,
.createNewAccount(accountName, instanceUrl.toString(), userDetails.getLogin(), newToken.getSha1(), defaultPagingNumber);
giteaVersion.toString(), maxResponseItems, defaultPagingNumber);
account = userAccountsApi.getAccountById((int) accountId); account = userAccountsApi.getAccountById((int) accountId);
} }
else { else {
@ -590,7 +569,6 @@ public class LoginActivity extends BaseActivity {
}); });
} }
private void loadDefaults() { private void loadDefaults() {
if(tinyDB.getString("loginType").equals(LoginType.BASIC.name().toLowerCase())) { if(tinyDB.getString("loginType").equals(LoginType.BASIC.name().toLowerCase())) {
@ -634,4 +612,6 @@ public class LoginActivity extends BaseActivity {
loginButton.setEnabled(true); loginButton.setEnabled(true);
} }
private enum LoginType {BASIC, TOKEN}
} }

View File

@ -34,26 +34,8 @@ import org.mian.gitnex.database.api.BaseApi;
import org.mian.gitnex.database.api.UserAccountsApi; import org.mian.gitnex.database.api.UserAccountsApi;
import org.mian.gitnex.database.models.UserAccount; import org.mian.gitnex.database.models.UserAccount;
import org.mian.gitnex.databinding.ActivityMainBinding; import org.mian.gitnex.databinding.ActivityMainBinding;
import org.mian.gitnex.fragments.AdministrationFragment; import org.mian.gitnex.fragments.*;
import org.mian.gitnex.fragments.BottomSheetDraftsFragment; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.fragments.BottomSheetMyIssuesFilterFragment;
import org.mian.gitnex.fragments.DraftsFragment;
import org.mian.gitnex.fragments.ExploreFragment;
import org.mian.gitnex.fragments.MostVisitedReposFragment;
import org.mian.gitnex.fragments.MyIssuesFragment;
import org.mian.gitnex.fragments.MyProfileFragment;
import org.mian.gitnex.fragments.MyRepositoriesFragment;
import org.mian.gitnex.fragments.NotificationsFragment;
import org.mian.gitnex.fragments.OrganizationsFragment;
import org.mian.gitnex.fragments.RepositoriesFragment;
import org.mian.gitnex.fragments.SettingsFragment;
import org.mian.gitnex.fragments.StarredRepositoriesFragment;
import org.mian.gitnex.helpers.AlertDialogs;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.ChangeLog;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
import org.mian.gitnex.structs.FragmentRefreshListener; import org.mian.gitnex.structs.FragmentRefreshListener;
import java.util.ArrayList; import java.util.ArrayList;
@ -98,9 +80,7 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
Handler handler = new Handler(); Handler handler = new Handler();
// DO NOT MOVE // DO NOT MOVE
if(mainIntent.hasExtra("switchAccountId") && if(mainIntent.hasExtra("switchAccountId") && AppUtil.switchToAccount(ctx, BaseApi.getInstance(ctx, UserAccountsApi.class).getAccountById(mainIntent.getIntExtra("switchAccountId", 0)))) {
AppUtil.switchToAccount(ctx, BaseApi.getInstance(ctx, UserAccountsApi.class)
.getAccountById(mainIntent.getIntExtra("switchAccountId", 0)))) {
mainIntent.removeExtra("switchAccountId"); mainIntent.removeExtra("switchAccountId");
recreate(); recreate();
@ -208,7 +188,7 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
userEmail.setTypeface(myTypeface); userEmail.setTypeface(myTypeface);
userFullName.setTypeface(myTypeface); userFullName.setTypeface(myTypeface);
if (getAccount().getUserInfo() != null) { if(getAccount().getUserInfo() != null) {
String userEmailNav = getAccount().getUserInfo().getEmail(); String userEmailNav = getAccount().getUserInfo().getEmail();
String userFullNameNav = getAccount().getFullName(); String userFullNameNav = getAccount().getFullName();
String userAvatarNav = getAccount().getUserInfo().getAvatarUrl(); String userAvatarNav = getAccount().getUserInfo().getAvatarUrl();
@ -225,25 +205,25 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
int avatarRadius = AppUtil.getPixelsFromDensity(ctx, 3); int avatarRadius = AppUtil.getPixelsFromDensity(ctx, 3);
PicassoService.getInstance(ctx).get().load(userAvatarNav).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(avatarRadius, 0)).resize(160, 160).centerCrop().into(userAvatar); PicassoService.getInstance(ctx).get().load(userAvatarNav).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(avatarRadius, 0)).resize(160, 160).centerCrop()
.into(userAvatar);
PicassoService.getInstance(ctx).get().load(userAvatarNav).transform(new BlurTransformation(ctx)) PicassoService.getInstance(ctx).get().load(userAvatarNav).transform(new BlurTransformation(ctx)).into(userAvatarBackground, new com.squareup.picasso.Callback() {
.into(userAvatarBackground, new com.squareup.picasso.Callback() {
@Override @Override
public void onSuccess() { public void onSuccess() {
int textColor = new ColorInverter().getImageViewContrastColor(userAvatarBackground); int textColor = new ColorInverter().getImageViewContrastColor(userAvatarBackground);
userFullName.setTextColor(textColor); userFullName.setTextColor(textColor);
userEmail.setTextColor(textColor); userEmail.setTextColor(textColor);
} }
@Override @Override
public void onError(Exception e) { public void onError(Exception e) {
} }
}); });
} }
} }
@ -262,9 +242,10 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
@Override @Override
public void onDrawerSlide(@NonNull View drawerView, float slideOffset) { public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
if (getAccount().getUserInfo() != null) { if(getAccount().getUserInfo() != null) {
navigationView.getMenu().findItem(R.id.nav_administration).setVisible(getAccount().getUserInfo().isIsAdmin()); navigationView.getMenu().findItem(R.id.nav_administration).setVisible(getAccount().getUserInfo().isIsAdmin());
} else { }
else {
// hide first // hide first
navigationView.getMenu().findItem(R.id.nav_administration).setVisible(false); navigationView.getMenu().findItem(R.id.nav_administration).setVisible(false);
} }
@ -275,10 +256,12 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
} }
@Override @Override
public void onDrawerClosed(@NonNull View drawerView) {} public void onDrawerClosed(@NonNull View drawerView) {
}
@Override @Override
public void onDrawerStateChanged(int newState) {} public void onDrawerStateChanged(int newState) {
}
}); });
@ -480,17 +463,13 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
if(frag != null) { if(frag != null) {
new MaterialAlertDialogBuilder(ctx) new MaterialAlertDialogBuilder(ctx).setTitle(R.string.deleteAllDrafts).setCancelable(false).setMessage(R.string.deleteAllDraftsDialogMessage)
.setTitle(R.string.deleteAllDrafts)
.setCancelable(false)
.setMessage(R.string.deleteAllDraftsDialogMessage)
.setPositiveButton(R.string.menuDeleteText, (dialog, which) -> { .setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
frag.deleteAllDrafts(currentActiveAccountId); frag.deleteAllDrafts(currentActiveAccountId);
dialog.dismiss(); dialog.dismiss();
}) }).setNeutralButton(R.string.cancelButton, null).show();
.setNeutralButton(R.string.cancelButton, null).show();
} }
else { else {
@ -761,6 +740,12 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
} }
// My issues interface // My issues interface
public FragmentRefreshListener getFragmentRefreshListener() { return fragmentRefreshListenerMyIssues; } public FragmentRefreshListener getFragmentRefreshListener() {
public void setFragmentRefreshListenerMyIssues(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListenerMyIssues = fragmentRefreshListener; } return fragmentRefreshListenerMyIssues;
}
public void setFragmentRefreshListenerMyIssues(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListenerMyIssues = fragmentRefreshListener;
}
} }

View File

@ -34,6 +34,7 @@ public class MergePullRequestActivity extends BaseActivity {
private IssueContext issue; private IssueContext issue;
private ActivityMergePullRequestBinding viewBinding; private ActivityMergePullRequestBinding viewBinding;
private String Do; private String Do;
private final View.OnClickListener mergePullRequest = v -> processMergePullRequest();
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
@Override @Override
@ -121,7 +122,7 @@ public class MergePullRequestActivity extends BaseActivity {
ArrayAdapter<MergePullRequestSpinner> adapter = new ArrayAdapter<>(MergePullRequestActivity.this, R.layout.list_spinner_items, mergeList); ArrayAdapter<MergePullRequestSpinner> adapter = new ArrayAdapter<>(MergePullRequestActivity.this, R.layout.list_spinner_items, mergeList);
viewBinding.mergeSpinner.setAdapter(adapter); viewBinding.mergeSpinner.setAdapter(adapter);
viewBinding.mergeSpinner.setOnItemClickListener ((parent, view, position, id) -> { viewBinding.mergeSpinner.setOnItemClickListener((parent, view, position, id) -> {
Do = mergeList.get(position).getId(); Do = mergeList.get(position).getId();
}); });
@ -132,8 +133,6 @@ public class MergePullRequestActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private final View.OnClickListener mergePullRequest = v -> processMergePullRequest();
private void processMergePullRequest() { private void processMergePullRequest() {
String mergePRDesc = Objects.requireNonNull(viewBinding.mergeDescription.getText()).toString(); String mergePRDesc = Objects.requireNonNull(viewBinding.mergeDescription.getText()).toString();
@ -200,8 +199,7 @@ public class MergePullRequestActivity extends BaseActivity {
PullRequestActions.deleteHeadBranch(ctx, repoOwner, repoName, issue.getPullRequest().getHead().getRef(), false); PullRequestActions.deleteHeadBranch(ctx, repoOwner, repoName, issue.getPullRequest().getHead().getRef(), false);
} }
else { else {
PullRequestActions.deleteHeadBranch(ctx, issue.getRepository().getOwner(), issue.getRepository().getName(), PullRequestActions.deleteHeadBranch(ctx, issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getPullRequest().getHead().getRef(), false);
issue.getPullRequest().getHead().getRef(), false);
} }
} }
@ -259,4 +257,5 @@ public class MergePullRequestActivity extends BaseActivity {
super.onResume(); super.onResume();
issue.getRepository().checkAccountSwitch(this); issue.getRepository().checkAccountSwitch(this);
} }
} }

View File

@ -31,145 +31,143 @@ import retrofit2.Callback;
public class MyProfileEmailActivity extends BaseActivity { public class MyProfileEmailActivity extends BaseActivity {
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private EditText userEmail; private EditText userEmail;
private Button addEmailButton; private Button addEmailButton;
private final View.OnClickListener addEmailListener = v -> processAddNewEmail();
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityProfileEmailBinding activityProfileEmailBinding = ActivityProfileEmailBinding.inflate(getLayoutInflater()); ActivityProfileEmailBinding activityProfileEmailBinding = ActivityProfileEmailBinding.inflate(getLayoutInflater());
setContentView(activityProfileEmailBinding.getRoot()); setContentView(activityProfileEmailBinding.getRoot());
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
ImageView closeActivity = activityProfileEmailBinding.close; ImageView closeActivity = activityProfileEmailBinding.close;
userEmail = activityProfileEmailBinding.userEmail; userEmail = activityProfileEmailBinding.userEmail;
addEmailButton = activityProfileEmailBinding.addEmailButton; addEmailButton = activityProfileEmailBinding.addEmailButton;
userEmail.requestFocus(); userEmail.requestFocus();
assert imm != null; assert imm != null;
imm.showSoftInput(userEmail, InputMethodManager.SHOW_IMPLICIT); imm.showSoftInput(userEmail, InputMethodManager.SHOW_IMPLICIT);
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
if(!connToInternet) { if(!connToInternet) {
disableProcessButton(); disableProcessButton();
} else { }
else {
addEmailButton.setOnClickListener(addEmailListener); addEmailButton.setOnClickListener(addEmailListener);
} }
} }
private final View.OnClickListener addEmailListener = v -> processAddNewEmail(); private void processAddNewEmail() {
private void processAddNewEmail() { boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); String newUserEmail = userEmail.getText().toString().trim();
String newUserEmail = userEmail.getText().toString().trim(); if(!connToInternet) {
if(!connToInternet) { Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
return;
}
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); if(newUserEmail.equals("")) {
return;
}
if(newUserEmail.equals("")) { Toasty.error(ctx, getString(R.string.emailErrorEmpty));
return;
}
else if(!Patterns.EMAIL_ADDRESS.matcher(newUserEmail).matches()) {
Toasty.error(ctx, getString(R.string.emailErrorEmpty)); Toasty.warning(ctx, getString(R.string.emailErrorInvalid));
return; return;
} }
else if(!Patterns.EMAIL_ADDRESS.matcher(newUserEmail).matches()) {
Toasty.warning(ctx, getString(R.string.emailErrorInvalid)); List<String> newEmailList = new ArrayList<>(Arrays.asList(newUserEmail.split(",")));
return;
}
List<String> newEmailList = new ArrayList<>(Arrays.asList(newUserEmail.split(","))); disableProcessButton();
addNewEmail(newEmailList);
}
disableProcessButton(); private void addNewEmail(List<String> newUserEmail) {
addNewEmail(newEmailList);
}
private void addNewEmail(List<String> newUserEmail) { CreateEmailOption addEmailFunc = new CreateEmailOption();
CreateEmailOption addEmailFunc = new CreateEmailOption();
addEmailFunc.setEmails(newUserEmail); addEmailFunc.setEmails(newUserEmail);
Call<List<Email>> call = RetrofitClient Call<List<Email>> call = RetrofitClient.getApiInterface(ctx).userAddEmail(addEmailFunc);
.getApiInterface(ctx)
.userAddEmail(addEmailFunc);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<List<Email>> call, @NonNull retrofit2.Response<List<Email>> response) { public void onResponse(@NonNull Call<List<Email>> call, @NonNull retrofit2.Response<List<Email>> response) {
if(response.code() == 201) { if(response.code() == 201) {
Toasty.success(ctx, getString(R.string.emailAddedText)); Toasty.success(ctx, getString(R.string.emailAddedText));
MyProfileEmailsFragment.refreshEmails = true; MyProfileEmailsFragment.refreshEmails = true;
enableProcessButton(); enableProcessButton();
finish(); finish();
} }
else if(response.code() == 401) { else if(response.code() == 401) {
enableProcessButton(); enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx); AlertDialogs.authorizationTokenRevokedDialog(ctx);
} }
else if(response.code() == 403) { else if(response.code() == 403) {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, ctx.getString(R.string.authorizeError)); Toasty.error(ctx, ctx.getString(R.string.authorizeError));
} }
else if(response.code() == 404) { else if(response.code() == 404) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound)); Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
} }
else if(response.code() == 422) { else if(response.code() == 422) {
enableProcessButton(); enableProcessButton();
Toasty.warning(ctx, ctx.getString(R.string.emailErrorInUse)); Toasty.warning(ctx, ctx.getString(R.string.emailErrorInUse));
} }
else { else {
enableProcessButton(); enableProcessButton();
Toasty.error(ctx, getString(R.string.genericError)); Toasty.error(ctx, getString(R.string.genericError));
} }
} }
@Override @Override
public void onFailure(@NonNull Call<List<Email>> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<List<Email>> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString()); Log.e("onFailure", t.toString());
enableProcessButton(); enableProcessButton();
} }
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private void disableProcessButton() { private void disableProcessButton() {
addEmailButton.setEnabled(false); addEmailButton.setEnabled(false);
} }
private void enableProcessButton() { private void enableProcessButton() {
addEmailButton.setEnabled(true); addEmailButton.setEnabled(true);
} }
} }

View File

@ -3,11 +3,7 @@ package org.mian.gitnex.activities;
import android.content.Intent; import android.content.Intent;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.view.Menu; import android.view.*;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar; import androidx.appcompat.widget.Toolbar;
@ -20,12 +16,7 @@ import org.gitnex.tea4j.v2.models.OrganizationPermissions;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetOrganizationFragment; import org.mian.gitnex.fragments.*;
import org.mian.gitnex.fragments.MembersByOrgFragment;
import org.mian.gitnex.fragments.OrganizationInfoFragment;
import org.mian.gitnex.fragments.OrganizationLabelsFragment;
import org.mian.gitnex.fragments.RepositoriesByOrgFragment;
import org.mian.gitnex.fragments.TeamsByOrgFragment;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
import java.util.Objects; import java.util.Objects;
@ -44,48 +35,48 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
private String orgName; private String orgName;
private boolean isMember = false; private boolean isMember = false;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_org_detail); setContentView(R.layout.activity_org_detail);
orgName = getIntent().getStringExtra("orgName"); orgName = getIntent().getStringExtra("orgName");
Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle(orgName); Objects.requireNonNull(getSupportActionBar()).setTitle(orgName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
checkIsMember(); checkIsMember();
if(getAccount().requiresVersion("1.16.0")) { if(getAccount().requiresVersion("1.16.0")) {
RetrofitClient.getApiInterface(this) RetrofitClient.getApiInterface(this).orgGetUserPermissions(getAccount().getAccount().getUserName(), orgName).enqueue(new Callback<>() {
.orgGetUserPermissions(getAccount().getAccount().getUserName(), orgName).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<OrganizationPermissions> call, @NonNull Response<OrganizationPermissions> response) { public void onResponse(@NonNull Call<OrganizationPermissions> call, @NonNull Response<OrganizationPermissions> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
permissions = response.body(); permissions = response.body();
} }
else { else {
permissions = null; permissions = null;
} }
} }
@Override @Override
public void onFailure(@NonNull Call<OrganizationPermissions> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<OrganizationPermissions> call, @NonNull Throwable t) {
permissions = null; permissions = null;
} }
}); });
} else { }
permissions = null; else {
} permissions = null;
} }
}
public void checkIsMember() { public void checkIsMember() {
RetrofitClient.getApiInterface(this).orgIsMember(orgName, getAccount().getAccount().getUserName()).enqueue(new Callback<>() { RetrofitClient.getApiInterface(this).orgIsMember(orgName, getAccount().getAccount().getUserName()).enqueue(new Callback<>() {
@ -127,16 +118,16 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0); ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
int tabsCount = vg.getChildCount(); int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) { for(int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j); ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildCount = vgTab.getChildCount(); int tabChildCount = vgTab.getChildCount();
for (int i = 0; i < tabChildCount; i++) { for(int i = 0; i < tabChildCount; i++) {
View tabViewChild = vgTab.getChildAt(i); View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) { if(tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(myTypeface); ((TextView) tabViewChild).setTypeface(myTypeface);
} }
@ -147,123 +138,125 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager)); tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
} }
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater(); MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.repo_dotted_menu, menu); inflater.inflate(R.menu.repo_dotted_menu, menu);
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); int id = item.getItemId();
if(id == android.R.id.home) { if(id == android.R.id.home) {
finish(); finish();
return true; return true;
} }
else if(id == R.id.repoMenu) { else if(id == R.id.repoMenu) {
BottomSheetOrganizationFragment bottomSheet = new BottomSheetOrganizationFragment(permissions); BottomSheetOrganizationFragment bottomSheet = new BottomSheetOrganizationFragment(permissions);
bottomSheet.show(getSupportFragmentManager(), "orgBottomSheet"); bottomSheet.show(getSupportFragmentManager(), "orgBottomSheet");
return true; return true;
} }
else { else {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
@Override @Override
public void onButtonClicked(String text) { public void onButtonClicked(String text) {
String url = UrlBuilder.fromString(getAccount().getAccount().getInstanceUrl()) String url = UrlBuilder.fromString(getAccount().getAccount().getInstanceUrl()).withPath("/").toString();
.withPath("/") url = url + getIntent().getStringExtra("orgName");
.toString();
url = url + getIntent().getStringExtra("orgName");
switch (text) { switch(text) {
case "repository": case "repository":
Intent intentRepo = new Intent(this, CreateRepoActivity.class); Intent intentRepo = new Intent(this, CreateRepoActivity.class);
intentRepo.putExtra("organizationAction", true); intentRepo.putExtra("organizationAction", true);
intentRepo.putExtra("orgName", getIntent().getStringExtra("orgName")); intentRepo.putExtra("orgName", getIntent().getStringExtra("orgName"));
intentRepo.putExtras(getIntent().getExtras()); intentRepo.putExtras(getIntent().getExtras());
startActivity(intentRepo); startActivity(intentRepo);
break; break;
case "label": case "label":
Intent intent = new Intent(ctx, CreateLabelActivity.class); Intent intent = new Intent(ctx, CreateLabelActivity.class);
intent.putExtra("orgName", getIntent().getStringExtra("orgName")); intent.putExtra("orgName", getIntent().getStringExtra("orgName"));
intent.putExtra("type", "org"); intent.putExtra("type", "org");
ctx.startActivity(intent); ctx.startActivity(intent);
break; break;
case "team": case "team":
Intent intentTeam = new Intent(OrganizationDetailActivity.this, CreateTeamByOrgActivity.class); Intent intentTeam = new Intent(OrganizationDetailActivity.this, CreateTeamByOrgActivity.class);
intentTeam.putExtras(getIntent().getExtras()); intentTeam.putExtras(getIntent().getExtras());
startActivity(intentTeam); startActivity(intentTeam);
break; break;
case "copyOrgUrl": case "copyOrgUrl":
AppUtil.copyToClipboard(this, url, ctx.getString(R.string.copyIssueUrlToastMsg)); AppUtil.copyToClipboard(this, url, ctx.getString(R.string.copyIssueUrlToastMsg));
break; break;
case "share": case "share":
AppUtil.sharingIntent(this, url); AppUtil.sharingIntent(this, url);
break; break;
case "open": case "open":
AppUtil.openUrlInBrowser(this, url); AppUtil.openUrlInBrowser(this, url);
break; break;
} }
} }
public class SectionsPagerAdapter extends FragmentPagerAdapter { public class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) { SectionsPagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
} }
@NonNull @NonNull
@Override @Override
public Fragment getItem(int position) { public Fragment getItem(int position) {
String orgName = getIntent().getStringExtra("orgName"); String orgName = getIntent().getStringExtra("orgName");
Fragment fragment = null; Fragment fragment = null;
switch (position) { switch(position) {
case 0: // info case 0: // info
return OrganizationInfoFragment.newInstance(orgName); return OrganizationInfoFragment.newInstance(orgName);
case 1: // repos case 1: // repos
return RepositoriesByOrgFragment.newInstance(orgName); return RepositoriesByOrgFragment.newInstance(orgName);
case 2: // labels case 2: // labels
return OrganizationLabelsFragment.newInstance(orgName); return OrganizationLabelsFragment.newInstance(orgName);
case 3: // teams / members case 3: // teams / members
if(isMember) { if(isMember) {
return TeamsByOrgFragment.newInstance(orgName, permissions); return TeamsByOrgFragment.newInstance(orgName, permissions);
} else { }
return MembersByOrgFragment.newInstance(orgName); else {
} return MembersByOrgFragment.newInstance(orgName);
case 4: // members }
case 4: // members
if(isMember) { if(isMember) {
return MembersByOrgFragment.newInstance(orgName); return MembersByOrgFragment.newInstance(orgName);
} }
} }
return fragment; return fragment;
} }
@Override @Override
public int getCount() { public int getCount() {
if(isMember) { if(isMember) {
return 5; return 5;
} else { }
else {
return 4; return 4;
} }
} }
}
}
} }

View File

@ -30,111 +30,114 @@ public class OrganizationTeamInfoActivity extends BaseActivity implements Bottom
private Team team; private Team team;
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
org.mian.gitnex.databinding.ActivityOrgTeamInfoBinding binding = ActivityOrgTeamInfoBinding.inflate(getLayoutInflater()); org.mian.gitnex.databinding.ActivityOrgTeamInfoBinding binding = ActivityOrgTeamInfoBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot()); setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar); setSupportActionBar(binding.toolbar);
team = (Team) getIntent().getSerializableExtra("team"); team = (Team) getIntent().getSerializableExtra("team");
if(team.getName() != null && !team.getName().isEmpty()) { if(team.getName() != null && !team.getName().isEmpty()) {
binding.toolbarTitle.setText(team.getName()); binding.toolbarTitle.setText(team.getName());
} }
else { else {
binding.toolbarTitle.setText(R.string.orgTeamMembers); binding.toolbarTitle.setText(R.string.orgTeamMembers);
} }
binding.close.setOnClickListener(view -> finish()); binding.close.setOnClickListener(view -> finish());
binding.pager.setOffscreenPageLimit(1); binding.pager.setOffscreenPageLimit(1);
binding.pager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) { binding.pager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
@NonNull
@Override
public Fragment createFragment(int position) {
switch(position) {
case 0:
return OrganizationTeamInfoReposFragment.newInstance(team);
case 1:
return OrganizationTeamInfoMembersFragment.newInstance(team);
case 2:
return OrganizationTeamInfoPermissionsFragment.newInstance(team);
}
return null;
}
@Override @NonNull
public int getItemCount() { @Override
return 3; public Fragment createFragment(int position) {
} switch(position) {
}); case 0:
return OrganizationTeamInfoReposFragment.newInstance(team);
case 1:
return OrganizationTeamInfoMembersFragment.newInstance(team);
case 2:
return OrganizationTeamInfoPermissionsFragment.newInstance(team);
}
return null;
}
new TabLayoutMediator(binding.tabs, binding.pager, (tab, position) -> { @Override
TextView textView = (TextView) LayoutInflater.from(ctx).inflate(R.layout.layout_tab_text, findViewById(android.R.id.content), false); public int getItemCount() {
return 3;
}
});
switch(position) { new TabLayoutMediator(binding.tabs, binding.pager, (tab, position) -> {
case 0: TextView textView = (TextView) LayoutInflater.from(ctx).inflate(R.layout.layout_tab_text, findViewById(android.R.id.content), false);
textView.setText(R.string.navRepos);
break; switch(position) {
case 1: case 0:
textView.setText(R.string.orgTabMembers); textView.setText(R.string.navRepos);
break;
case 2:
textView.setText(R.string.teamPermissions);
break; break;
} case 1:
textView.setText(R.string.orgTabMembers);
break;
case 2:
textView.setText(R.string.teamPermissions);
break;
}
tab.setCustomView(textView); tab.setCustomView(textView);
}).attach(); }).attach();
} }
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
OrganizationPermissions permissions = (OrganizationPermissions) getIntent().getSerializableExtra("permissions"); OrganizationPermissions permissions = (OrganizationPermissions) getIntent().getSerializableExtra("permissions");
if(permissions == null || permissions.isIsOwner()) { if(permissions == null || permissions.isIsOwner()) {
MenuInflater inflater = getMenuInflater(); MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.generic_nav_dotted_menu, menu); inflater.inflate(R.menu.generic_nav_dotted_menu, menu);
} }
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); int id = item.getItemId();
if(id == android.R.id.home) { if(id == android.R.id.home) {
finish(); finish();
return true; return true;
} }
else if(id == R.id.genericMenu) { else if(id == R.id.genericMenu) {
BottomSheetOrganizationTeamsFragment bottomSheet = new BottomSheetOrganizationTeamsFragment(); BottomSheetOrganizationTeamsFragment bottomSheet = new BottomSheetOrganizationTeamsFragment();
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putBoolean("showRepo", !team.isIncludesAllRepositories()); args.putBoolean("showRepo", !team.isIncludesAllRepositories());
bottomSheet.setArguments(args); bottomSheet.setArguments(args);
bottomSheet.show(getSupportFragmentManager(), "orgTeamsBottomSheet"); bottomSheet.show(getSupportFragmentManager(), "orgTeamsBottomSheet");
return true; return true;
} }
else { else {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
@Override @Override
public void onButtonClicked(String text) { public void onButtonClicked(String text) {
if("newMember".equals(text)) { if("newMember".equals(text)) {
Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamMemberActivity.class); Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamMemberActivity.class);
intent.putExtra("teamId", team.getId()); intent.putExtra("teamId", team.getId());
startActivity(intent); startActivity(intent);
} else if("newRepo".equals(text)) { }
Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamRepoActivity.class); else if("newRepo".equals(text)) {
intent.putExtra("teamId", team.getId()); Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamRepoActivity.class);
intent.putExtra("teamName", team.getName()); intent.putExtra("teamId", team.getId());
intent.putExtra("teamName", team.getName());
intent.putExtra("orgName", getIntent().getStringExtra("orgName")); intent.putExtra("orgName", getIntent().getStringExtra("orgName"));
startActivity(intent); startActivity(intent);
} }
} }
} }

View File

@ -19,12 +19,7 @@ import com.google.android.material.tabs.TabLayoutMediator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetUserProfileFragment; import org.mian.gitnex.fragments.BottomSheetUserProfileFragment;
import org.mian.gitnex.fragments.profile.DetailFragment; import org.mian.gitnex.fragments.profile.*;
import org.mian.gitnex.fragments.profile.FollowersFragment;
import org.mian.gitnex.fragments.profile.FollowingFragment;
import org.mian.gitnex.fragments.profile.OrganizationsFragment;
import org.mian.gitnex.fragments.profile.RepositoriesFragment;
import org.mian.gitnex.fragments.profile.StarredRepositoriesFragment;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
@ -74,20 +69,21 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
viewPager.setAdapter(new ViewPagerAdapter(this)); viewPager.setAdapter(new ViewPagerAdapter(this));
String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.navRepos), ctx.getResources().getString(R.string.navStarredRepos), ctx.getResources().getString(R.string.navOrg), ctx.getResources().getString(R.string.profileTabFollowers), ctx.getResources().getString(R.string.profileTabFollowing)}; String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.navRepos), ctx.getResources().getString(R.string.navStarredRepos),
ctx.getResources().getString(R.string.navOrg), ctx.getResources().getString(R.string.profileTabFollowers), ctx.getResources().getString(R.string.profileTabFollowing)};
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach(); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach();
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0); ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
int tabsCount = vg.getChildCount(); int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) { for(int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j); ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildCount = vgTab.getChildCount(); int tabChildCount = vgTab.getChildCount();
for (int i = 0; i < tabChildCount; i++) { for(int i = 0; i < tabChildCount; i++) {
View tabViewChild = vgTab.getChildAt(i); View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) { if(tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(myTypeface); ((TextView) tabViewChild).setTypeface(myTypeface);
} }
} }
@ -130,7 +126,7 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
private void followUnfollow() { private void followUnfollow() {
Call<Void> call; Call<Void> call;
if (following) { if(following) {
call = RetrofitClient.getApiInterface(this).userCurrentDeleteFollow(username); call = RetrofitClient.getApiInterface(this).userCurrentDeleteFollow(username);
} }
else { else {
@ -141,16 +137,17 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if (response.isSuccessful()) { if(response.isSuccessful()) {
following = !following; following = !following;
if (following) { if(following) {
Toasty.success(ProfileActivity.this, String.format(getString(R.string.nowFollowUser), username)); Toasty.success(ProfileActivity.this, String.format(getString(R.string.nowFollowUser), username));
} }
else { else {
Toasty.success(ProfileActivity.this, String.format(getString(R.string.unfollowedUser), username)); Toasty.success(ProfileActivity.this, String.format(getString(R.string.unfollowedUser), username));
} }
} else { }
if (following) { else {
if(following) {
Toasty.error(ProfileActivity.this, getString(R.string.unfollowingFailed)); Toasty.error(ProfileActivity.this, getString(R.string.unfollowingFailed));
} }
else { else {
@ -161,7 +158,7 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
@Override @Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
if (following) { if(following) {
Toasty.error(ProfileActivity.this, getString(R.string.unfollowingFailed)); Toasty.error(ProfileActivity.this, getString(R.string.unfollowingFailed));
} }
else { else {
@ -171,36 +168,6 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
}); });
} }
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) { super(fa); }
@NonNull
@Override
public Fragment createFragment(int position) {
switch(position) {
case 0: // detail
return DetailFragment.newInstance(username);
case 1: // repos
return RepositoriesFragment.newInstance(username);
case 2: // starred repos
return StarredRepositoriesFragment.newInstance(username);
case 3: // organizations
return OrganizationsFragment.newInstance(username);
case 4: // followers
return FollowersFragment.newInstance(username);
case 5: // following
return FollowingFragment.newInstance(username);
}
return null;
}
@Override
public int getItemCount() {
return 6;
}
}
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
@ -227,4 +194,37 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) {
super(fa);
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch(position) {
case 0: // detail
return DetailFragment.newInstance(username);
case 1: // repos
return RepositoriesFragment.newInstance(username);
case 2: // starred repos
return StarredRepositoriesFragment.newInstance(username);
case 3: // organizations
return OrganizationsFragment.newInstance(username);
case 4: // followers
return FollowersFragment.newInstance(username);
case 5: // following
return FollowingFragment.newInstance(username);
}
return null;
}
@Override
public int getItemCount() {
return 6;
}
}
} }

View File

@ -6,12 +6,7 @@ import android.content.Intent;
import android.content.res.ColorStateList; import android.content.res.ColorStateList;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.*;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.ActivityResultLauncher;
@ -26,27 +21,10 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.progressindicator.LinearProgressIndicator; import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator; import com.google.android.material.tabs.TabLayoutMediator;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Milestone;
import org.gitnex.tea4j.v2.models.Organization;
import org.gitnex.tea4j.v2.models.Repository;
import org.gitnex.tea4j.v2.models.WatchInfo;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetIssuesFilterFragment; import org.mian.gitnex.fragments.*;
import org.mian.gitnex.fragments.BottomSheetMilestonesFilterFragment;
import org.mian.gitnex.fragments.BottomSheetPullRequestFilterFragment;
import org.mian.gitnex.fragments.BottomSheetReleasesTagsFragment;
import org.mian.gitnex.fragments.BottomSheetRepoFragment;
import org.mian.gitnex.fragments.CollaboratorsFragment;
import org.mian.gitnex.fragments.FilesFragment;
import org.mian.gitnex.fragments.IssuesFragment;
import org.mian.gitnex.fragments.LabelsFragment;
import org.mian.gitnex.fragments.MilestonesFragment;
import org.mian.gitnex.fragments.PullRequestsFragment;
import org.mian.gitnex.fragments.ReleasesFragment;
import org.mian.gitnex.fragments.RepoInfoFragment;
import org.mian.gitnex.fragments.WikiFragment;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
@ -65,71 +43,63 @@ import retrofit2.Response;
public class RepoDetailActivity extends BaseActivity implements BottomSheetListener { public class RepoDetailActivity extends BaseActivity implements BottomSheetListener {
public static boolean updateRepo = false;
private final ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("nameChanged", false)) {
recreate();
}
}
});
public ViewPager2 viewPager;
public RepositoryContext repository;
private TextView textViewBadgeIssue; private TextView textViewBadgeIssue;
private TextView textViewBadgePull; private TextView textViewBadgePull;
private TextView textViewBadgeRelease; private TextView textViewBadgeRelease;
private Typeface myTypeface; private Typeface myTypeface;
private FragmentRefreshListener fragmentRefreshListener; private FragmentRefreshListener fragmentRefreshListener;
private FragmentRefreshListener fragmentRefreshListenerPr; private FragmentRefreshListener fragmentRefreshListenerPr;
private FragmentRefreshListener fragmentRefreshListenerMilestone; private FragmentRefreshListener fragmentRefreshListenerMilestone;
private final ActivityResultLauncher<Intent> createMilestoneLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("milestoneCreated", false)) {
if(fragmentRefreshListenerMilestone != null) {
fragmentRefreshListenerMilestone.onRefresh(repository.getMilestoneState().toString());
}
}
}
});
private FragmentRefreshListener fragmentRefreshListenerFiles; private FragmentRefreshListener fragmentRefreshListenerFiles;
private final ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("fileModified", false)) {
if(fragmentRefreshListenerFiles != null) {
fragmentRefreshListenerFiles.onRefresh(repository.getBranchRef());
}
}
}
});
private FragmentRefreshListener fragmentRefreshListenerFilterIssuesByMilestone; private FragmentRefreshListener fragmentRefreshListenerFilterIssuesByMilestone;
private FragmentRefreshListener fragmentRefreshListenerReleases; private FragmentRefreshListener fragmentRefreshListenerReleases;
public ViewPager2 viewPager;
public RepositoryContext repository;
public static boolean updateRepo = false;
private Dialog progressDialog; private Dialog progressDialog;
private final ActivityResultLauncher<Intent> createReleaseLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("updateReleases", false)) {
if(fragmentRefreshListenerReleases != null) {
fragmentRefreshListenerReleases.onRefresh(null);
}
repository.removeRepository();
getRepoInfo(repository.getOwner(), repository.getName());
}
}
});
private MaterialAlertDialogBuilder materialAlertDialogBuilder; private MaterialAlertDialogBuilder materialAlertDialogBuilder;
private Intent intentWiki; private Intent intentWiki;
private final ActivityResultLauncher<Intent> createReleaseLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("updateReleases", false)) {
if(fragmentRefreshListenerReleases != null) fragmentRefreshListenerReleases.onRefresh(null);
repository.removeRepository();
getRepoInfo(repository.getOwner(), repository.getName());
}
}
});
private final ActivityResultLauncher<Intent> createMilestoneLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("milestoneCreated", false)) {
if(fragmentRefreshListenerMilestone != null) fragmentRefreshListenerMilestone.onRefresh(repository.getMilestoneState().toString());
}
}
});
private final ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("fileModified", false)) {
if(fragmentRefreshListenerFiles != null) fragmentRefreshListenerFiles.onRefresh(repository.getBranchRef());
}
}
});
private final ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("nameChanged", false)) {
recreate();
}
}
});
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -204,7 +174,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
finish(); finish();
} }
}); });
} else { }
else {
finish(); finish();
} }
return true; return true;
@ -389,9 +360,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
progressDialog.setContentView(R.layout.custom_progress_loader); progressDialog.setContentView(R.layout.custom_progress_loader);
progressDialog.show(); progressDialog.show();
Call<List<Milestone>> call = RetrofitClient Call<List<Milestone>> call = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repository.getOwner(), repository.getName(), "open", null, 1, 50);
.getApiInterface(ctx)
.issueGetMilestonesList(repository.getOwner(), repository.getName(), "open", null, 1, 50);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -419,17 +388,15 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
} }
materialAlertDialogBuilder.setTitle(R.string.selectMilestone) materialAlertDialogBuilder.setTitle(R.string.selectMilestone).setSingleChoiceItems(milestonesList.toArray(new String[0]), selectedMilestone, (dialogInterface, i) -> {
.setSingleChoiceItems(milestonesList.toArray(new String[0]), selectedMilestone, (dialogInterface, i) -> {
repository.setIssueMilestoneFilterName(milestonesList.get(i)); repository.setIssueMilestoneFilterName(milestonesList.get(i));
if(getFragmentRefreshListenerFilterIssuesByMilestone() != null) { if(getFragmentRefreshListenerFilterIssuesByMilestone() != null) {
getFragmentRefreshListenerFilterIssuesByMilestone().onRefresh(milestonesList.get(i)); getFragmentRefreshListenerFilterIssuesByMilestone().onRefresh(milestonesList.get(i));
} }
dialogInterface.dismiss(); dialogInterface.dismiss();
}) }).setNeutralButton(R.string.cancelButton, null);
.setNeutralButton(R.string.cancelButton, null);
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
} }
@ -457,9 +424,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
progressDialog.setContentView(R.layout.custom_progress_loader); progressDialog.setContentView(R.layout.custom_progress_loader);
progressDialog.show(); progressDialog.show();
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repository.getOwner(), repository.getName(), null, null);
.getApiInterface(ctx)
.repoListBranches(repository.getOwner(), repository.getName(), null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -483,17 +448,15 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
} }
materialAlertDialogBuilder.setTitle(R.string.pageTitleChooseBranch) materialAlertDialogBuilder.setTitle(R.string.pageTitleChooseBranch).setSingleChoiceItems(branchesList.toArray(new String[0]), selectedBranch, (dialogInterface, i) -> {
.setSingleChoiceItems(branchesList.toArray(new String[0]), selectedBranch, (dialogInterface, i) -> {
repository.setBranchRef(branchesList.get(i)); repository.setBranchRef(branchesList.get(i));
if(getFragmentRefreshListenerFiles() != null) { if(getFragmentRefreshListenerFiles() != null) {
getFragmentRefreshListenerFiles().onRefresh(branchesList.get(i)); getFragmentRefreshListenerFiles().onRefresh(branchesList.get(i));
} }
dialogInterface.dismiss(); dialogInterface.dismiss();
}) }).setNeutralButton(R.string.cancelButton, null);
.setNeutralButton(R.string.cancelButton, null);
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
} }
@ -505,49 +468,6 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
}); });
} }
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) { super(fa); }
@NonNull
@Override
public Fragment createFragment(int position) {
Fragment fragment = null;
switch(position) {
case 0: // Repository details
return RepoInfoFragment.newInstance(repository);
case 1: // Files
return FilesFragment.newInstance(repository);
case 2: // Issues
fragment = IssuesFragment.newInstance(repository);
break;
case 3: // Pull requests
fragment = PullRequestsFragment.newInstance(repository);
break;
case 4: // Releases
return ReleasesFragment.newInstance(repository);
case 5: // Wiki
return WikiFragment.newInstance(repository);
case 6: // Milestones
fragment = MilestonesFragment.newInstance(repository);
break;
case 7: // Labels
return LabelsFragment.newInstance(repository);
case 8: // Collaborators
return CollaboratorsFragment.newInstance(repository);
}
assert fragment != null;
return fragment;
}
@Override
public int getItemCount() {
return 9;
}
}
private void getRepoInfo(final String owner, String repo) { private void getRepoInfo(final String owner, String repo) {
LinearProgressIndicator loading = findViewById(R.id.loadingIndicator); LinearProgressIndicator loading = findViewById(R.id.loadingIndicator);
@ -592,7 +512,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
ImageView repoTypeToolbar = findViewById(R.id.repoTypeToolbar); ImageView repoTypeToolbar = findViewById(R.id.repoTypeToolbar);
if(repository.getRepository().isPrivate()) { if(repository.getRepository().isPrivate()) {
repoTypeToolbar.setVisibility(View.VISIBLE); repoTypeToolbar.setVisibility(View.VISIBLE);
} else { }
else {
repoTypeToolbar.setVisibility(View.GONE); repoTypeToolbar.setVisibility(View.GONE);
} }
@ -605,7 +526,9 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
viewPager.setAdapter(new ViewPagerAdapter(this)); viewPager.setAdapter(new ViewPagerAdapter(this));
String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.tabTextFiles), ctx.getResources().getString(R.string.pageTitleIssues), ctx.getResources().getString(R.string.tabPullRequests), ctx.getResources().getString(R.string.tabTextReleases), ctx.getResources().getString(R.string.wiki), ctx.getResources().getString(R.string.tabTextMl), ctx.getResources().getString(R.string.newIssueLabelsTitle), ctx.getResources().getString(R.string.tabTextCollaborators)}; String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.tabTextFiles), ctx.getResources().getString(R.string.pageTitleIssues),
ctx.getResources().getString(R.string.tabPullRequests), ctx.getResources().getString(R.string.tabTextReleases), ctx.getResources().getString(R.string.wiki),
ctx.getResources().getString(R.string.tabTextMl), ctx.getResources().getString(R.string.newIssueLabelsTitle), ctx.getResources().getString(R.string.tabTextCollaborators)};
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach(); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach();
ViewGroup viewGroup = (ViewGroup) tabLayout.getChildAt(0); ViewGroup viewGroup = (ViewGroup) tabLayout.getChildAt(0);
@ -658,7 +581,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
TextView openIssueTabView = Objects.requireNonNull(tabOpenIssues.getCustomView()).findViewById(R.id.counterBadgeIssueText); TextView openIssueTabView = Objects.requireNonNull(tabOpenIssues.getCustomView()).findViewById(R.id.counterBadgeIssueText);
openIssueTabView.setTextColor(textColor); openIssueTabView.setTextColor(textColor);
} else { }
else {
textViewBadgeIssue.setVisibility(View.GONE); textViewBadgeIssue.setVisibility(View.GONE);
} }
@ -674,7 +598,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
TextView openPullTabView = Objects.requireNonNull(tabOpenPulls.getCustomView()).findViewById(R.id.counterBadgePullText); TextView openPullTabView = Objects.requireNonNull(tabOpenPulls.getCustomView()).findViewById(R.id.counterBadgePullText);
openPullTabView.setTextColor(textColor); openPullTabView.setTextColor(textColor);
} else { }
else {
textViewBadgePull.setVisibility(View.GONE); textViewBadgePull.setVisibility(View.GONE);
} }
@ -690,7 +615,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
TextView openReleaseTabView = Objects.requireNonNull(tabOpenRelease.getCustomView()).findViewById(R.id.counterBadgeReleaseText); TextView openReleaseTabView = Objects.requireNonNull(tabOpenRelease.getCustomView()).findViewById(R.id.counterBadgeReleaseText);
openReleaseTabView.setTextColor(textColor); openReleaseTabView.setTextColor(textColor);
} else { }
else {
textViewBadgeRelease.setVisibility(View.GONE); textViewBadgeRelease.setVisibility(View.GONE);
} }
} }
@ -833,33 +759,104 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
// Issues milestone filter interface // Issues milestone filter interface
public FragmentRefreshListener getFragmentRefreshListenerFilterIssuesByMilestone() { return fragmentRefreshListenerFilterIssuesByMilestone; } public FragmentRefreshListener getFragmentRefreshListenerFilterIssuesByMilestone() {
return fragmentRefreshListenerFilterIssuesByMilestone;
}
public void setFragmentRefreshListenerFilterIssuesByMilestone(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListenerFilterIssuesByMilestone = fragmentRefreshListener; } public void setFragmentRefreshListenerFilterIssuesByMilestone(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListenerFilterIssuesByMilestone = fragmentRefreshListener;
}
// Issues interface // Issues interface
public FragmentRefreshListener getFragmentRefreshListener() { return fragmentRefreshListener; } public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListener = fragmentRefreshListener; } public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
// Pull request interface // Pull request interface
public FragmentRefreshListener getFragmentRefreshListenerPr() { return fragmentRefreshListenerPr; } public FragmentRefreshListener getFragmentRefreshListenerPr() {
return fragmentRefreshListenerPr;
}
public void setFragmentRefreshListenerPr(FragmentRefreshListener fragmentRefreshListenerPr) { this.fragmentRefreshListenerPr = fragmentRefreshListenerPr; } public void setFragmentRefreshListenerPr(FragmentRefreshListener fragmentRefreshListenerPr) {
this.fragmentRefreshListenerPr = fragmentRefreshListenerPr;
}
// Milestones interface // Milestones interface
public FragmentRefreshListener getFragmentRefreshListenerMilestone() { return fragmentRefreshListenerMilestone; } public FragmentRefreshListener getFragmentRefreshListenerMilestone() {
return fragmentRefreshListenerMilestone;
}
public void setFragmentRefreshListenerMilestone(FragmentRefreshListener fragmentRefreshListenerMilestone) { this.fragmentRefreshListenerMilestone = fragmentRefreshListenerMilestone; } public void setFragmentRefreshListenerMilestone(FragmentRefreshListener fragmentRefreshListenerMilestone) {
this.fragmentRefreshListenerMilestone = fragmentRefreshListenerMilestone;
}
// Files interface // Files interface
public FragmentRefreshListener getFragmentRefreshListenerFiles() { return fragmentRefreshListenerFiles; } public FragmentRefreshListener getFragmentRefreshListenerFiles() {
return fragmentRefreshListenerFiles;
}
public void setFragmentRefreshListenerFiles(FragmentRefreshListener fragmentRefreshListenerFiles) { this.fragmentRefreshListenerFiles = fragmentRefreshListenerFiles; } public void setFragmentRefreshListenerFiles(FragmentRefreshListener fragmentRefreshListenerFiles) {
this.fragmentRefreshListenerFiles = fragmentRefreshListenerFiles;
}
//Releases interface //Releases interface
public FragmentRefreshListener getFragmentRefreshListenerReleases() { return fragmentRefreshListenerReleases; } public FragmentRefreshListener getFragmentRefreshListenerReleases() {
return fragmentRefreshListenerReleases;
}
public void setFragmentRefreshListenerReleases(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListenerReleases = fragmentRefreshListener;
}
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) {
super(fa);
}
@NonNull
@Override
public Fragment createFragment(int position) {
Fragment fragment = null;
switch(position) {
case 0: // Repository details
return RepoInfoFragment.newInstance(repository);
case 1: // Files
return FilesFragment.newInstance(repository);
case 2: // Issues
fragment = IssuesFragment.newInstance(repository);
break;
case 3: // Pull requests
fragment = PullRequestsFragment.newInstance(repository);
break;
case 4: // Releases
return ReleasesFragment.newInstance(repository);
case 5: // Wiki
return WikiFragment.newInstance(repository);
case 6: // Milestones
fragment = MilestonesFragment.newInstance(repository);
break;
case 7: // Labels
return LabelsFragment.newInstance(repository);
case 8: // Collaborators
return CollaboratorsFragment.newInstance(repository);
}
assert fragment != null;
return fragment;
}
@Override
public int getItemCount() {
return 9;
}
}
public void setFragmentRefreshListenerReleases(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListenerReleases = fragmentRefreshListener; }
} }

View File

@ -39,9 +39,9 @@ import retrofit2.Response;
public class RepoForksActivity extends BaseActivity { public class RepoForksActivity extends BaseActivity {
private final String TAG = "RepositoryForks";
private TextView noData; private TextView noData;
private ProgressBar progressBar; private ProgressBar progressBar;
private final String TAG = "RepositoryForks";
private int resultLimit; private int resultLimit;
private int pageSize = 1; private int pageSize = 1;
@ -113,9 +113,7 @@ public class RepoForksActivity extends BaseActivity {
private void loadInitial(String repoOwner, String repoName, int pageSize, int resultLimit) { private void loadInitial(String repoOwner, String repoName, int pageSize, int resultLimit) {
Call<List<Repository>> call = RetrofitClient Call<List<Repository>> call = RetrofitClient.getApiInterface(ctx).listForks(repoOwner, repoName, pageSize, resultLimit);
.getApiInterface(ctx)
.listForks(repoOwner, repoName, pageSize, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -157,9 +155,7 @@ public class RepoForksActivity extends BaseActivity {
progressLoadMore.setVisibility(View.VISIBLE); progressLoadMore.setVisibility(View.VISIBLE);
Call<List<Repository>> call = RetrofitClient Call<List<Repository>> call = RetrofitClient.getApiInterface(ctx).listForks(repoOwner, repoName, page, resultLimit);
.getApiInterface(ctx)
.listForks(repoOwner, repoName, page, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -230,8 +226,7 @@ public class RepoForksActivity extends BaseActivity {
List<Repository> userRepositories = new ArrayList<>(); List<Repository> userRepositories = new ArrayList<>();
for(Repository d : forksList) { for(Repository d : forksList) {
if(d.getOwner().getLogin().contains(text) || d.getName().toLowerCase().contains(text) || if(d.getOwner().getLogin().contains(text) || d.getName().toLowerCase().contains(text) || d.getDescription().toLowerCase().contains(text)) {
d.getDescription().toLowerCase().contains(text)) {
userRepositories.add(d); userRepositories.add(d);
} }
@ -245,4 +240,5 @@ public class RepoForksActivity extends BaseActivity {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -19,69 +19,69 @@ import org.mian.gitnex.viewmodels.RepoStargazersViewModel;
public class RepoStargazersActivity extends BaseActivity { public class RepoStargazersActivity extends BaseActivity {
private TextView noDataStargazers; private TextView noDataStargazers;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private UserGridAdapter adapter; private UserGridAdapter adapter;
private GridView mGridView; private GridView mGridView;
private ProgressBar mProgressBar; private ProgressBar mProgressBar;
private RepositoryContext repository; private RepositoryContext repository;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityRepoStargazersBinding activityRepoStargazersBinding = ActivityRepoStargazersBinding.inflate(getLayoutInflater()); ActivityRepoStargazersBinding activityRepoStargazersBinding = ActivityRepoStargazersBinding.inflate(getLayoutInflater());
setContentView(activityRepoStargazersBinding.getRoot()); setContentView(activityRepoStargazersBinding.getRoot());
ImageView closeActivity = activityRepoStargazersBinding.close; ImageView closeActivity = activityRepoStargazersBinding.close;
TextView toolbarTitle = activityRepoStargazersBinding.toolbarTitle; TextView toolbarTitle = activityRepoStargazersBinding.toolbarTitle;
noDataStargazers = activityRepoStargazersBinding.noDataStargazers; noDataStargazers = activityRepoStargazersBinding.noDataStargazers;
mGridView = activityRepoStargazersBinding.gridView; mGridView = activityRepoStargazersBinding.gridView;
mProgressBar = activityRepoStargazersBinding.progressBar; mProgressBar = activityRepoStargazersBinding.progressBar;
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
final String repoOwner = repository.getOwner(); final String repoOwner = repository.getOwner();
final String repoName = repository.getName(); final String repoName = repository.getName();
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
toolbarTitle.setText(R.string.repoStargazersInMenu); toolbarTitle.setText(R.string.repoStargazersInMenu);
fetchDataAsync(repoOwner, repoName); fetchDataAsync(repoOwner, repoName);
} }
private void fetchDataAsync(String repoOwner, String repoName) { private void fetchDataAsync(String repoOwner, String repoName) {
RepoStargazersViewModel repoStargazersModel = new ViewModelProvider(this).get(RepoStargazersViewModel.class); RepoStargazersViewModel repoStargazersModel = new ViewModelProvider(this).get(RepoStargazersViewModel.class);
repoStargazersModel.getRepoStargazers(repoOwner, repoName, ctx).observe(this, stargazersListMain -> { repoStargazersModel.getRepoStargazers(repoOwner, repoName, ctx).observe(this, stargazersListMain -> {
adapter = new UserGridAdapter(ctx, stargazersListMain); adapter = new UserGridAdapter(ctx, stargazersListMain);
if(adapter.getCount() > 0) { if(adapter.getCount() > 0) {
mGridView.setAdapter(adapter); mGridView.setAdapter(adapter);
noDataStargazers.setVisibility(View.GONE); noDataStargazers.setVisibility(View.GONE);
} }
else { else {
adapter.notifyDataSetChanged(); adapter.notifyDataSetChanged();
mGridView.setAdapter(adapter); mGridView.setAdapter(adapter);
noDataStargazers.setVisibility(View.VISIBLE); noDataStargazers.setVisibility(View.VISIBLE);
} }
mProgressBar.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE);
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
@Override @Override
public void onResume() { public void onResume() {

View File

@ -19,69 +19,69 @@ import org.mian.gitnex.viewmodels.RepoWatchersViewModel;
public class RepoWatchersActivity extends BaseActivity { public class RepoWatchersActivity extends BaseActivity {
private TextView noDataWatchers; private TextView noDataWatchers;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private UserGridAdapter adapter; private UserGridAdapter adapter;
private GridView mGridView; private GridView mGridView;
private ProgressBar mProgressBar; private ProgressBar mProgressBar;
private RepositoryContext repository; private RepositoryContext repository;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ActivityRepoWatchersBinding activityRepoWatchersBinding = ActivityRepoWatchersBinding.inflate(getLayoutInflater()); ActivityRepoWatchersBinding activityRepoWatchersBinding = ActivityRepoWatchersBinding.inflate(getLayoutInflater());
setContentView(activityRepoWatchersBinding.getRoot()); setContentView(activityRepoWatchersBinding.getRoot());
ImageView closeActivity = activityRepoWatchersBinding.close; ImageView closeActivity = activityRepoWatchersBinding.close;
TextView toolbarTitle = activityRepoWatchersBinding.toolbarTitle; TextView toolbarTitle = activityRepoWatchersBinding.toolbarTitle;
noDataWatchers = activityRepoWatchersBinding.noDataWatchers; noDataWatchers = activityRepoWatchersBinding.noDataWatchers;
mGridView = activityRepoWatchersBinding.gridView; mGridView = activityRepoWatchersBinding.gridView;
mProgressBar = activityRepoWatchersBinding.progressBar; mProgressBar = activityRepoWatchersBinding.progressBar;
repository = RepositoryContext.fromIntent(getIntent()); repository = RepositoryContext.fromIntent(getIntent());
final String repoOwner = repository.getOwner(); final String repoOwner = repository.getOwner();
final String repoName = repository.getName(); final String repoName = repository.getName();
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
toolbarTitle.setText(R.string.repoWatchersInMenu); toolbarTitle.setText(R.string.repoWatchersInMenu);
fetchDataAsync(repoOwner, repoName); fetchDataAsync(repoOwner, repoName);
} }
private void fetchDataAsync(String repoOwner, String repoName) { private void fetchDataAsync(String repoOwner, String repoName) {
RepoWatchersViewModel repoWatchersModel = new ViewModelProvider(this).get(RepoWatchersViewModel.class); RepoWatchersViewModel repoWatchersModel = new ViewModelProvider(this).get(RepoWatchersViewModel.class);
repoWatchersModel.getRepoWatchers(repoOwner, repoName, ctx).observe(this, watchersListMain -> { repoWatchersModel.getRepoWatchers(repoOwner, repoName, ctx).observe(this, watchersListMain -> {
adapter = new UserGridAdapter(ctx, watchersListMain); adapter = new UserGridAdapter(ctx, watchersListMain);
if(adapter.getCount() > 0) { if(adapter.getCount() > 0) {
mGridView.setAdapter(adapter); mGridView.setAdapter(adapter);
noDataWatchers.setVisibility(View.GONE); noDataWatchers.setVisibility(View.GONE);
} }
else { else {
adapter.notifyDataSetChanged(); adapter.notifyDataSetChanged();
mGridView.setAdapter(adapter); mGridView.setAdapter(adapter);
noDataWatchers.setVisibility(View.VISIBLE); noDataWatchers.setVisibility(View.VISIBLE);
} }
mProgressBar.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE);
}); });
} }
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
@Override @Override
public void onResume() { public void onResume() {

View File

@ -116,9 +116,7 @@ public class RepositorySettingsActivity extends BaseActivity {
TransferRepoOption repositoryTransfer = new TransferRepoOption(); TransferRepoOption repositoryTransfer = new TransferRepoOption();
repositoryTransfer.setNewOwner(newOwner); repositoryTransfer.setNewOwner(newOwner);
Call<Repository> transferCall = RetrofitClient Call<Repository> transferCall = RetrofitClient.getApiInterface(ctx).repoTransfer(repositoryTransfer, repository.getOwner(), repository.getName());
.getApiInterface(ctx)
.repoTransfer(repositoryTransfer, repository.getOwner(), repository.getName());
transferCall.enqueue(new Callback<Repository>() { transferCall.enqueue(new Callback<Repository>() {
@ -128,7 +126,7 @@ public class RepositorySettingsActivity extends BaseActivity {
transferRepoBinding.transfer.setVisibility(View.GONE); transferRepoBinding.transfer.setVisibility(View.GONE);
transferRepoBinding.processingRequest.setVisibility(View.VISIBLE); transferRepoBinding.processingRequest.setVisibility(View.VISIBLE);
if (response.code() == 202) { if(response.code() == 202) {
dialogRepo.dismiss(); dialogRepo.dismiss();
Toasty.success(ctx, getString(R.string.repoTransferSuccess)); Toasty.success(ctx, getString(R.string.repoTransferSuccess));
@ -138,7 +136,7 @@ public class RepositorySettingsActivity extends BaseActivity {
Intent intent = new Intent(RepositorySettingsActivity.this, MainActivity.class); Intent intent = new Intent(RepositorySettingsActivity.this, MainActivity.class);
RepositorySettingsActivity.this.startActivity(intent); RepositorySettingsActivity.this.startActivity(intent);
} }
else if (response.code() == 404) { else if(response.code() == 404) {
transferRepoBinding.transfer.setVisibility(View.VISIBLE); transferRepoBinding.transfer.setVisibility(View.VISIBLE);
transferRepoBinding.processingRequest.setVisibility(View.GONE); transferRepoBinding.processingRequest.setVisibility(View.GONE);
@ -187,9 +185,7 @@ public class RepositorySettingsActivity extends BaseActivity {
private void deleteRepository() { private void deleteRepository() {
Call<Void> deleteCall = RetrofitClient Call<Void> deleteCall = RetrofitClient.getApiInterface(ctx).repoDelete(repository.getOwner(), repository.getName());
.getApiInterface(ctx)
.repoDelete(repository.getOwner(), repository.getName());
deleteCall.enqueue(new Callback<Void>() { deleteCall.enqueue(new Callback<Void>() {
@ -199,7 +195,7 @@ public class RepositorySettingsActivity extends BaseActivity {
deleteRepoBinding.delete.setVisibility(View.GONE); deleteRepoBinding.delete.setVisibility(View.GONE);
deleteRepoBinding.processingRequest.setVisibility(View.VISIBLE); deleteRepoBinding.processingRequest.setVisibility(View.VISIBLE);
if (response.code() == 204) { if(response.code() == 204) {
dialogRepo.dismiss(); dialogRepo.dismiss();
Toasty.success(ctx, getString(R.string.repoDeletionSuccess)); Toasty.success(ctx, getString(R.string.repoDeletionSuccess));
@ -251,7 +247,7 @@ public class RepositorySettingsActivity extends BaseActivity {
propBinding.repoEnableIssues.setOnCheckedChangeListener((buttonView, isChecked) -> { propBinding.repoEnableIssues.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) { if(isChecked) {
propBinding.repoEnableTimer.setVisibility(View.VISIBLE); propBinding.repoEnableTimer.setVisibility(View.VISIBLE);
} }
else { else {
@ -275,22 +271,17 @@ public class RepositorySettingsActivity extends BaseActivity {
propBinding.repoEnableSquash.setChecked(repoInfo.isAllowSquashMerge()); propBinding.repoEnableSquash.setChecked(repoInfo.isAllowSquashMerge());
propBinding.repoEnableForceMerge.setChecked(repoInfo.isAllowRebaseExplicit()); propBinding.repoEnableForceMerge.setChecked(repoInfo.isAllowRebaseExplicit());
propBinding.save.setOnClickListener(saveProperties -> saveRepositoryProperties(String.valueOf(propBinding.repoName.getText()), propBinding.save.setOnClickListener(
String.valueOf(propBinding.repoWebsite.getText()), saveProperties -> saveRepositoryProperties(String.valueOf(propBinding.repoName.getText()), String.valueOf(propBinding.repoWebsite.getText()), String.valueOf(propBinding.repoDescription.getText()),
String.valueOf(propBinding.repoDescription.getText()), propBinding.repoPrivate.isChecked(), propBinding.repoAsTemplate.isChecked(), propBinding.repoEnableIssues.isChecked(), propBinding.repoEnableWiki.isChecked(), propBinding.repoEnablePr.isChecked(),
propBinding.repoPrivate.isChecked(), propBinding.repoAsTemplate.isChecked(), propBinding.repoEnableTimer.isChecked(), propBinding.repoEnableMerge.isChecked(), propBinding.repoEnableRebase.isChecked(), propBinding.repoEnableSquash.isChecked(),
propBinding.repoEnableIssues.isChecked(), propBinding.repoEnableWiki.isChecked(), propBinding.repoEnableForceMerge.isChecked()));
propBinding.repoEnablePr.isChecked(), propBinding.repoEnableTimer.isChecked(),
propBinding.repoEnableMerge.isChecked(), propBinding.repoEnableRebase.isChecked(),
propBinding.repoEnableSquash.isChecked(), propBinding.repoEnableForceMerge.isChecked()));
dialogRepo = materialAlertDialogBuilder.show(); dialogRepo = materialAlertDialogBuilder.show();
} }
private void saveRepositoryProperties(String repoName, String repoWebsite, String repoDescription, private void saveRepositoryProperties(String repoName, String repoWebsite, String repoDescription, boolean repoPrivate, boolean repoAsTemplate, boolean repoEnableIssues, boolean repoEnableWiki, boolean repoEnablePr,
boolean repoPrivate, boolean repoAsTemplate, boolean repoEnableIssues, boolean repoEnableWiki, boolean repoEnableTimer, boolean repoEnableMerge, boolean repoEnableRebase, boolean repoEnableSquash, boolean repoEnableForceMerge) {
boolean repoEnablePr, boolean repoEnableTimer, boolean repoEnableMerge, boolean repoEnableRebase,
boolean repoEnableSquash, boolean repoEnableForceMerge) {
EditRepoOption repoProps = new EditRepoOption(); EditRepoOption repoProps = new EditRepoOption();
repoProps.setName(repoName); repoProps.setName(repoName);
@ -307,9 +298,7 @@ public class RepositorySettingsActivity extends BaseActivity {
repoProps.setAllowSquashMerge(repoEnableSquash); repoProps.setAllowSquashMerge(repoEnableSquash);
repoProps.setAllowRebaseExplicit(repoEnableForceMerge); repoProps.setAllowRebaseExplicit(repoEnableForceMerge);
Call<Repository> propsCall = RetrofitClient Call<Repository> propsCall = RetrofitClient.getApiInterface(ctx).repoEdit(repository.getOwner(), repository.getName(), repoProps);
.getApiInterface(ctx)
.repoEdit(repository.getOwner(), repository.getName(), repoProps);
propsCall.enqueue(new Callback<Repository>() { propsCall.enqueue(new Callback<Repository>() {
@ -319,7 +308,7 @@ public class RepositorySettingsActivity extends BaseActivity {
propBinding.save.setVisibility(View.GONE); propBinding.save.setVisibility(View.GONE);
propBinding.processingRequest.setVisibility(View.VISIBLE); propBinding.processingRequest.setVisibility(View.VISIBLE);
if (response.code() == 200) { if(response.code() == 200) {
dialogRepo.dismiss(); dialogRepo.dismiss();
Toasty.success(ctx, getString(R.string.repoPropertiesSaveSuccess)); Toasty.success(ctx, getString(R.string.repoPropertiesSaveSuccess));
@ -327,8 +316,7 @@ public class RepositorySettingsActivity extends BaseActivity {
repository.setRepository(response.body()); repository.setRepository(response.body());
if(!repository.getName().equals(repoName)) { if(!repository.getName().equals(repoName)) {
Objects.requireNonNull(BaseApi.getInstance(ctx, RepositoriesApi.class)) Objects.requireNonNull(BaseApi.getInstance(ctx, RepositoriesApi.class)).updateRepositoryOwnerAndName(repository.getOwner(), repoName, repository.getRepositoryId());
.updateRepositoryOwnerAndName(repository.getOwner(), repoName, repository.getRepositoryId());
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("nameChanged", true); result.putExtra("nameChanged", true);
setResult(200, result); setResult(200, result);

View File

@ -25,16 +25,13 @@ import org.mian.gitnex.helpers.Toasty;
public class SettingsAppearanceActivity extends BaseActivity { public class SettingsAppearanceActivity extends BaseActivity {
private View.OnClickListener onClickListener;
private static String[] timeList; private static String[] timeList;
private static int timeSelectedChoice = 0; private static int timeSelectedChoice = 0;
private static String[] customFontList; private static String[] customFontList;
private static int customFontSelectedChoice = 0; private static int customFontSelectedChoice = 0;
private static String[] themeList; private static String[] themeList;
private static int themeSelectedChoice = 0; private static int themeSelectedChoice = 0;
private View.OnClickListener onClickListener;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -63,22 +60,28 @@ public class SettingsAppearanceActivity extends BaseActivity {
String lightMinute = String.valueOf(tinyDB.getInt("lightThemeTimeMinute")); String lightMinute = String.valueOf(tinyDB.getInt("lightThemeTimeMinute"));
String lightHour = String.valueOf(tinyDB.getInt("lightThemeTimeHour")); String lightHour = String.valueOf(tinyDB.getInt("lightThemeTimeHour"));
if(lightMinute.length() == 1) lightMinute = "0" + lightMinute; if(lightMinute.length() == 1) {
if(lightHour.length() == 1) lightHour = "0" + lightHour; lightMinute = "0" + lightMinute;
}
if(lightHour.length() == 1) {
lightHour = "0" + lightHour;
}
String darkMinute = String.valueOf(tinyDB.getInt("darkThemeTimeMinute")); String darkMinute = String.valueOf(tinyDB.getInt("darkThemeTimeMinute"));
String darkHour = String.valueOf(tinyDB.getInt("darkThemeTimeHour")); String darkHour = String.valueOf(tinyDB.getInt("darkThemeTimeHour"));
if(darkMinute.length() == 1) darkMinute = "0" + darkMinute; if(darkMinute.length() == 1) {
if(darkHour.length() == 1) darkHour = "0" + darkHour; darkMinute = "0" + darkMinute;
}
if(darkHour.length() == 1) {
darkHour = "0" + darkHour;
}
timeSelectedChoice = tinyDB.getInt("timeId"); timeSelectedChoice = tinyDB.getInt("timeId");
customFontSelectedChoice = tinyDB.getInt("customFontId", 1); customFontSelectedChoice = tinyDB.getInt("customFontId", 1);
themeSelectedChoice = tinyDB.getInt("themeId", 6); // use system theme as default themeSelectedChoice = tinyDB.getInt("themeId", 6); // use system theme as default
activitySettingsAppearanceBinding.lightThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, lightHour, activitySettingsAppearanceBinding.lightThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, lightHour, lightMinute));
lightMinute)); activitySettingsAppearanceBinding.darkThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, darkHour, darkMinute));
activitySettingsAppearanceBinding.darkThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, darkHour,
darkMinute));
activitySettingsAppearanceBinding.tvDateTimeSelected.setText(timeList[timeSelectedChoice]); activitySettingsAppearanceBinding.tvDateTimeSelected.setText(timeList[timeSelectedChoice]);
activitySettingsAppearanceBinding.customFontSelected.setText(customFontList[customFontSelectedChoice]); activitySettingsAppearanceBinding.customFontSelected.setText(customFontList[customFontSelectedChoice]);
activitySettingsAppearanceBinding.themeSelected.setText(themeList[themeSelectedChoice]); activitySettingsAppearanceBinding.themeSelected.setText(themeList[themeSelectedChoice]);
@ -110,13 +113,13 @@ public class SettingsAppearanceActivity extends BaseActivity {
tinyDB.putBoolean("showLabelsInList", isChecked); tinyDB.putBoolean("showLabelsInList", isChecked);
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
activitySettingsAppearanceBinding.labelsInListFrame.setOnClickListener(v -> activitySettingsAppearanceBinding.switchLabelsInListBadge.setChecked(!activitySettingsAppearanceBinding.switchLabelsInListBadge.isChecked())); activitySettingsAppearanceBinding.labelsInListFrame.setOnClickListener(
v -> activitySettingsAppearanceBinding.switchLabelsInListBadge.setChecked(!activitySettingsAppearanceBinding.switchLabelsInListBadge.isChecked()));
// theme selection dialog // theme selection dialog
themeFrame.setOnClickListener(view -> { themeFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.themeSelectorDialogTitle)
.setTitle(R.string.themeSelectorDialogTitle)
.setSingleChoiceItems(themeList, themeSelectedChoice, (dialogInterfaceTheme, i) -> { .setSingleChoiceItems(themeList, themeSelectedChoice, (dialogInterfaceTheme, i) -> {
themeSelectedChoice = i; themeSelectedChoice = i;
@ -135,20 +138,18 @@ public class SettingsAppearanceActivity extends BaseActivity {
lightTimeFrame.setOnClickListener(view -> { lightTimeFrame.setOnClickListener(view -> {
LightTimePicker timePicker = new LightTimePicker(); LightTimePicker timePicker = new LightTimePicker();
timePicker.show(getSupportFragmentManager(), "timePicker"); timePicker.show(getSupportFragmentManager(), "timePicker");
}); });
darkTimeFrame.setOnClickListener(view -> { darkTimeFrame.setOnClickListener(view -> {
DarkTimePicker timePicker = new DarkTimePicker(); DarkTimePicker timePicker = new DarkTimePicker();
timePicker.show(getSupportFragmentManager(), "timePicker"); timePicker.show(getSupportFragmentManager(), "timePicker");
}); });
// custom font dialog // custom font dialog
customFontFrame.setOnClickListener(view -> { customFontFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsCustomFontSelectorDialogTitle).setCancelable(customFontSelectedChoice != -1)
.setTitle(R.string.settingsCustomFontSelectorDialogTitle)
.setCancelable(customFontSelectedChoice != -1)
.setSingleChoiceItems(customFontList, customFontSelectedChoice, (dialogInterfaceCustomFont, i) -> { .setSingleChoiceItems(customFontList, customFontSelectedChoice, (dialogInterfaceCustomFont, i) -> {
customFontSelectedChoice = i; customFontSelectedChoice = i;
@ -170,9 +171,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
// time and date dialog // time and date dialog
timeFrame.setOnClickListener(view -> { timeFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsTimeSelectorDialogTitle).setCancelable(timeSelectedChoice != -1)
.setTitle(R.string.settingsTimeSelectorDialogTitle)
.setCancelable(timeSelectedChoice != -1)
.setSingleChoiceItems(timeList, timeSelectedChoice, (dialogInterfaceTime, i) -> { .setSingleChoiceItems(timeList, timeSelectedChoice, (dialogInterfaceTime, i) -> {
timeSelectedChoice = i; timeSelectedChoice = i;
@ -224,6 +223,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave)); Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave));
requireActivity().recreate(); requireActivity().recreate();
} }
} }
public static class DarkTimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener { public static class DarkTimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@ -249,6 +249,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave)); Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave));
requireActivity().recreate(); requireActivity().recreate();
} }
} }
} }

View File

@ -41,6 +41,8 @@ public class SettingsDraftsActivity extends BaseActivity {
} }
private void initCloseListener() { onClickListener = view -> finish(); } private void initCloseListener() {
onClickListener = view -> finish();
}
} }

View File

@ -16,14 +16,12 @@ import java.util.List;
public class SettingsGeneralActivity extends BaseActivity { public class SettingsGeneralActivity extends BaseActivity {
private static int homeScreenSelectedChoice = 0;
private static int defaultLinkHandlerScreenSelectedChoice = 0;
private ActivitySettingsGeneralBinding viewBinding; private ActivitySettingsGeneralBinding viewBinding;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private List<String> homeScreenList; private List<String> homeScreenList;
private static int homeScreenSelectedChoice = 0;
private List<String> linkHandlerDefaultScreen; private List<String> linkHandlerDefaultScreen;
private static int defaultLinkHandlerScreenSelectedChoice = 0;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -100,18 +98,16 @@ public class SettingsGeneralActivity extends BaseActivity {
viewBinding.homeScreenFrame.setOnClickListener(setDefaultHomeScreen -> { viewBinding.homeScreenFrame.setOnClickListener(setDefaultHomeScreen -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsHomeScreenSelectorDialogTitle).setCancelable(homeScreenSelectedChoice != -1)
.setTitle(R.string.settingsHomeScreenSelectorDialogTitle)
.setCancelable(homeScreenSelectedChoice != -1)
.setSingleChoiceItems(homeScreenArray, homeScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> { .setSingleChoiceItems(homeScreenArray, homeScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> {
homeScreenSelectedChoice = i; homeScreenSelectedChoice = i;
viewBinding.homeScreenSelected.setText(homeScreenArray[i]); viewBinding.homeScreenSelected.setText(homeScreenArray[i]);
tinyDB.putInt("homeScreenId", i); tinyDB.putInt("homeScreenId", i);
dialogInterfaceHomeScreen.dismiss(); dialogInterfaceHomeScreen.dismiss();
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
}); });
@ -129,9 +125,7 @@ public class SettingsGeneralActivity extends BaseActivity {
viewBinding.setDefaultLinkHandler.setOnClickListener(setDefaultLinkHandler -> { viewBinding.setDefaultLinkHandler.setOnClickListener(setDefaultLinkHandler -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.linkSelectorDialogTitle).setCancelable(defaultLinkHandlerScreenSelectedChoice != -1)
.setTitle(R.string.linkSelectorDialogTitle)
.setCancelable(defaultLinkHandlerScreenSelectedChoice != -1)
.setSingleChoiceItems(linksArray, defaultLinkHandlerScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> { .setSingleChoiceItems(linksArray, defaultLinkHandlerScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> {
defaultLinkHandlerScreenSelectedChoice = i; defaultLinkHandlerScreenSelectedChoice = i;
@ -156,5 +150,8 @@ public class SettingsGeneralActivity extends BaseActivity {
// custom tabs // custom tabs
} }
private void initCloseListener() { onClickListener = view -> finish(); } private void initCloseListener() {
onClickListener = view -> finish();
}
} }

View File

@ -42,12 +42,7 @@ public class SettingsNotificationsActivity extends BaseActivity {
viewBinding.enableVibrationMode.setChecked(tinyDB.getBoolean("notificationsEnableVibration", true)); viewBinding.enableVibrationMode.setChecked(tinyDB.getBoolean("notificationsEnableVibration", true));
if(!viewBinding.enableNotificationsMode.isChecked()) { if(!viewBinding.enableNotificationsMode.isChecked()) {
AppUtil.setMultiVisibility(View.GONE, AppUtil.setMultiVisibility(View.GONE, viewBinding.chooseColorFrame, viewBinding.enableLightsFrame, viewBinding.enableVibrationFrame, viewBinding.pollingDelayFrame);
viewBinding.chooseColorFrame,
viewBinding.enableLightsFrame,
viewBinding.enableVibrationFrame,
viewBinding.pollingDelayFrame
);
} }
if(!viewBinding.enableLightsMode.isChecked()) { if(!viewBinding.enableLightsMode.isChecked()) {
@ -60,27 +55,17 @@ public class SettingsNotificationsActivity extends BaseActivity {
if(isChecked) { if(isChecked) {
Notifications.startWorker(ctx); Notifications.startWorker(ctx);
AppUtil.setMultiVisibility(View.VISIBLE, AppUtil.setMultiVisibility(View.VISIBLE, viewBinding.chooseColorFrame, viewBinding.enableLightsFrame, viewBinding.enableVibrationFrame, viewBinding.pollingDelayFrame);
viewBinding.chooseColorFrame, }
viewBinding.enableLightsFrame, else {
viewBinding.enableVibrationFrame,
viewBinding.pollingDelayFrame
);
} else {
Notifications.stopWorker(ctx); Notifications.stopWorker(ctx);
AppUtil.setMultiVisibility(View.GONE, AppUtil.setMultiVisibility(View.GONE, viewBinding.chooseColorFrame, viewBinding.enableLightsFrame, viewBinding.enableVibrationFrame, viewBinding.pollingDelayFrame);
viewBinding.chooseColorFrame,
viewBinding.enableLightsFrame,
viewBinding.enableVibrationFrame,
viewBinding.pollingDelayFrame
);
} }
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
viewBinding.enableNotificationsFrame.setOnClickListener( viewBinding.enableNotificationsFrame.setOnClickListener(v -> viewBinding.enableNotificationsMode.setChecked(!viewBinding.enableNotificationsMode.isChecked()));
v -> viewBinding.enableNotificationsMode.setChecked(!viewBinding.enableNotificationsMode.isChecked()));
// polling delay // polling delay
viewBinding.pollingDelayFrame.setOnClickListener(v -> { viewBinding.pollingDelayFrame.setOnClickListener(v -> {
@ -91,12 +76,8 @@ public class SettingsNotificationsActivity extends BaseActivity {
numberPicker.setValue(tinyDB.getInt("pollingDelayMinutes", Constants.defaultPollingDelay)); numberPicker.setValue(tinyDB.getInt("pollingDelayMinutes", Constants.defaultPollingDelay));
numberPicker.setWrapSelectorWheel(true); numberPicker.setWrapSelectorWheel(true);
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.pollingDelayDialogHeaderText).setMessage(getString(R.string.pollingDelayDialogDescriptionText))
.setTitle(R.string.pollingDelayDialogHeaderText) .setCancelable(true).setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss()).setPositiveButton(getString(R.string.okButton), (dialog, which) -> {
.setMessage(getString(R.string.pollingDelayDialogDescriptionText))
.setCancelable(true)
.setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss())
.setPositiveButton(getString(R.string.okButton), (dialog, which) -> {
tinyDB.putInt("pollingDelayMinutes", numberPicker.getValue()); tinyDB.putInt("pollingDelayMinutes", numberPicker.getValue());
@ -116,7 +97,8 @@ public class SettingsNotificationsActivity extends BaseActivity {
if(!isChecked) { if(!isChecked) {
viewBinding.chooseColorFrame.setVisibility(View.GONE); viewBinding.chooseColorFrame.setVisibility(View.GONE);
} else { }
else {
viewBinding.chooseColorFrame.setVisibility(View.VISIBLE); viewBinding.chooseColorFrame.setVisibility(View.VISIBLE);
} }
@ -150,8 +132,7 @@ public class SettingsNotificationsActivity extends BaseActivity {
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
viewBinding.enableVibrationFrame.setOnClickListener( viewBinding.enableVibrationFrame.setOnClickListener(v -> viewBinding.enableVibrationMode.setChecked(!viewBinding.enableVibrationMode.isChecked()));
v -> viewBinding.enableVibrationMode.setChecked(!viewBinding.enableVibrationMode.isChecked()));
} }

View File

@ -36,8 +36,7 @@ public class SettingsReportsActivity extends BaseActivity {
tinyDB.putBoolean("crashReportingEnabled", isChecked); tinyDB.putBoolean("crashReportingEnabled", isChecked);
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
activitySettingsReportsBinding.enableSendReports.setOnClickListener( activitySettingsReportsBinding.enableSendReports.setOnClickListener(v -> activitySettingsReportsBinding.crashReportsSwitch.setChecked(!activitySettingsReportsBinding.crashReportsSwitch.isChecked()));
v -> activitySettingsReportsBinding.crashReportsSwitch.setChecked(!activitySettingsReportsBinding.crashReportsSwitch.isChecked()));
} }
private void initCloseListener() { private void initCloseListener() {

View File

@ -28,13 +28,11 @@ import static androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTI
public class SettingsSecurityActivity extends BaseActivity { public class SettingsSecurityActivity extends BaseActivity {
private View.OnClickListener onClickListener;
private static String[] cacheSizeDataList; private static String[] cacheSizeDataList;
private static int cacheSizeDataSelectedChoice = 0; private static int cacheSizeDataSelectedChoice = 0;
private static String[] cacheSizeImagesList; private static String[] cacheSizeImagesList;
private static int cacheSizeImagesSelectedChoice = 0; private static int cacheSizeImagesSelectedChoice = 0;
private View.OnClickListener onClickListener;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -86,7 +84,7 @@ public class SettingsSecurityActivity extends BaseActivity {
BiometricManager biometricManager = BiometricManager.from(ctx); BiometricManager biometricManager = BiometricManager.from(ctx);
KeyguardManager keyguardManager = (KeyguardManager) ctx.getSystemService(Context.KEYGUARD_SERVICE); KeyguardManager keyguardManager = (KeyguardManager) ctx.getSystemService(Context.KEYGUARD_SERVICE);
if (!keyguardManager.isDeviceSecure()) { if(!keyguardManager.isDeviceSecure()) {
switch(biometricManager.canAuthenticate(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)) { switch(biometricManager.canAuthenticate(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)) {
@ -141,11 +139,8 @@ public class SettingsSecurityActivity extends BaseActivity {
// clear cache // clear cache
clearCacheFrame.setOnClickListener(v1 -> { clearCacheFrame.setOnClickListener(v1 -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.clearCacheDialogHeader).setMessage(getResources().getString(R.string.clearCacheDialogMessage))
.setTitle(R.string.clearCacheDialogHeader) .setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss()).setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
.setMessage(getResources().getString(R.string.clearCacheDialogMessage))
.setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss())
.setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
try { try {
@ -154,7 +149,7 @@ public class SettingsSecurityActivity extends BaseActivity {
this.recreate(); this.recreate();
this.overridePendingTransition(0, 0); this.overridePendingTransition(0, 0);
} }
catch (IOException e) { catch(IOException e) {
Log.e("SettingsSecurity", e.toString()); Log.e("SettingsSecurity", e.toString());
} }
@ -166,9 +161,7 @@ public class SettingsSecurityActivity extends BaseActivity {
// cache size images selection dialog // cache size images selection dialog
cacheSizeImagesFrame.setOnClickListener(view -> { cacheSizeImagesFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.cacheSizeImagesDialogHeader).setCancelable(cacheSizeImagesSelectedChoice != -1)
.setTitle(R.string.cacheSizeImagesDialogHeader)
.setCancelable(cacheSizeImagesSelectedChoice != -1)
.setSingleChoiceItems(cacheSizeImagesList, cacheSizeImagesSelectedChoice, (dialogInterfaceTheme, i) -> { .setSingleChoiceItems(cacheSizeImagesList, cacheSizeImagesSelectedChoice, (dialogInterfaceTheme, i) -> {
cacheSizeImagesSelectedChoice = i; cacheSizeImagesSelectedChoice = i;
@ -186,9 +179,7 @@ public class SettingsSecurityActivity extends BaseActivity {
// cache size data selection dialog // cache size data selection dialog
cacheSizeDataFrame.setOnClickListener(view -> { cacheSizeDataFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.cacheSizeDataDialogHeader).setCancelable(cacheSizeDataSelectedChoice != -1)
.setTitle(R.string.cacheSizeDataDialogHeader)
.setCancelable(cacheSizeDataSelectedChoice != -1)
.setSingleChoiceItems(cacheSizeDataList, cacheSizeDataSelectedChoice, (dialogInterfaceTheme, i) -> { .setSingleChoiceItems(cacheSizeDataList, cacheSizeDataSelectedChoice, (dialogInterfaceTheme, i) -> {
cacheSizeDataSelectedChoice = i; cacheSizeDataSelectedChoice = i;
@ -206,11 +197,8 @@ public class SettingsSecurityActivity extends BaseActivity {
// certs deletion // certs deletion
certsFrame.setOnClickListener(v1 -> { certsFrame.setOnClickListener(v1 -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsCertsPopupTitle).setMessage(getResources().getString(R.string.settingsCertsPopupMessage))
.setTitle(R.string.settingsCertsPopupTitle) .setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss()).setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
.setMessage(getResources().getString(R.string.settingsCertsPopupMessage))
.setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss())
.setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
appCtx.getSharedPreferences(MemorizingTrustManager.KEYSTORE_NAME, Context.MODE_PRIVATE).edit().remove(MemorizingTrustManager.KEYSTORE_KEY).apply(); appCtx.getSharedPreferences(MemorizingTrustManager.KEYSTORE_NAME, Context.MODE_PRIVATE).edit().remove(MemorizingTrustManager.KEYSTORE_KEY).apply();
AppUtil.logout(this); AppUtil.logout(this);
@ -224,4 +212,5 @@ public class SettingsSecurityActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -20,9 +20,14 @@ import java.util.Locale;
public class SettingsTranslationActivity extends BaseActivity { public class SettingsTranslationActivity extends BaseActivity {
private static int langSelectedChoice = 0;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private static int langSelectedChoice = 0; private static String getLanguageDisplayName(String langCode) {
Locale english = new Locale("en");
Locale translated = new Locale(langCode);
return String.format("%s (%s)", translated.getDisplayName(translated), translated.getDisplayName(english));
}
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -58,11 +63,8 @@ public class SettingsTranslationActivity extends BaseActivity {
// language dialog // language dialog
langFrame.setOnClickListener(view -> { langFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsLanguageSelectorDialogTitle).setCancelable(langSelectedChoice != -1)
.setTitle(R.string.settingsLanguageSelectorDialogTitle) .setNeutralButton(getString(R.string.cancelButton), null).setSingleChoiceItems(langs.values().toArray(new String[0]), langSelectedChoice, (dialogInterface, i) -> {
.setCancelable(langSelectedChoice != -1)
.setNeutralButton(getString(R.string.cancelButton), null)
.setSingleChoiceItems(langs.values().toArray(new String[0]), langSelectedChoice, (dialogInterface, i) -> {
String selectedLanguage = langs.keySet().toArray(new String[0])[i]; String selectedLanguage = langs.keySet().toArray(new String[0])[i];
tinyDB.putInt("langId", i); tinyDB.putInt("langId", i);
@ -84,10 +86,4 @@ public class SettingsTranslationActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private static String getLanguageDisplayName(String langCode) {
Locale english = new Locale("en");
Locale translated = new Locale(langCode);
return String.format("%s (%s)", translated.getDisplayName(translated), translated.getDisplayName(english));
}
} }

View File

@ -105,9 +105,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
createWikiPageOptions.setTitle(wikiTitle); createWikiPageOptions.setTitle(wikiTitle);
createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent)); createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent));
Call<WikiPage> call = RetrofitClient Call<WikiPage> call = RetrofitClient.getApiInterface(ctx).repoCreateWikiPage(repository.getOwner(), repository.getName(), createWikiPageOptions);
.getApiInterface(ctx)
.repoCreateWikiPage(repository.getOwner(), repository.getName(), createWikiPageOptions);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -155,9 +153,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
createWikiPageOptions.setTitle(wikiTitle); createWikiPageOptions.setTitle(wikiTitle);
createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent)); createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent));
Call<WikiPage> call = RetrofitClient Call<WikiPage> call = RetrofitClient.getApiInterface(ctx).repoEditWikiPage(repository.getOwner(), repository.getName(), pageName, createWikiPageOptions);
.getApiInterface(ctx)
.repoEditWikiPage(repository.getOwner(), repository.getName(), pageName, createWikiPageOptions);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -201,9 +197,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
private void getWikiPageContents() { private void getWikiPageContents() {
Call<WikiPage> call = RetrofitClient Call<WikiPage> call = RetrofitClient.getApiInterface(ctx).repoGetWikiPage(repository.getOwner(), repository.getName(), pageName);
.getApiInterface(ctx)
.repoGetWikiPage(repository.getOwner(), repository.getName(), pageName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -269,35 +263,32 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
private void deleteWiki(final String owner, final String repo, final String pageName) { private void deleteWiki(final String owner, final String repo, final String pageName) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(String.format(ctx.getString(R.string.deleteGenericTitle), pageName))
.setTitle(String.format(ctx.getString(R.string.deleteGenericTitle), pageName)) .setMessage(ctx.getString(R.string.deleteWikiPageMessage, pageName)).setNeutralButton(R.string.cancelButton, null)
.setMessage(ctx.getString(R.string.deleteWikiPageMessage, pageName)) .setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient.getApiInterface(ctx).repoDeleteWikiPage(owner, repo, pageName).enqueue(new Callback<>() {
.setNeutralButton(R.string.cancelButton, null)
.setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient
.getApiInterface(ctx).repoDeleteWikiPage(owner, repo, pageName).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
Toasty.success(ctx, getString(R.string.wikiPageDeleted)); Toasty.success(ctx, getString(R.string.wikiPageDeleted));
WikiFragment.resumeWiki = true; WikiFragment.resumeWiki = true;
finish(); finish();
}
else if(response.code() == 403) {
Toasty.error(ctx, ctx.getString(R.string.authorizeError));
}
else {
Toasty.error(ctx, ctx.getString(R.string.genericError));
}
} }
else if(response.code() == 403) {
@Override Toasty.error(ctx, ctx.getString(R.string.authorizeError));
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { }
else {
Toasty.error(ctx, ctx.getString(R.string.genericError)); Toasty.error(ctx, ctx.getString(R.string.genericError));
} }
})); }
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(ctx, ctx.getString(R.string.genericError));
}
}));
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
@ -362,8 +353,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
if(action.equalsIgnoreCase("edit") || action.equalsIgnoreCase("add")) { if(action.equalsIgnoreCase("edit") || action.equalsIgnoreCase("add")) {
if(renderMd) { if(renderMd) {
Markdown.render(ctx, EmojiParser.parseToUnicode(String.valueOf( Markdown.render(ctx, EmojiParser.parseToUnicode(String.valueOf(Objects.requireNonNull(binding.contentLayout.getEditText()).getText())), binding.markdownPreview, repository);
Objects.requireNonNull(binding.contentLayout.getEditText()).getText())), binding.markdownPreview, repository);
binding.markdownPreview.setVisibility(View.VISIBLE); binding.markdownPreview.setVisibility(View.VISIBLE);
binding.contentLayout.setVisibility(View.GONE); binding.contentLayout.setVisibility(View.GONE);
@ -402,4 +392,5 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
} }

View File

@ -31,90 +31,13 @@ public class AdminCronTasksAdapter extends RecyclerView.Adapter<AdminCronTasksAd
private final List<Cron> tasksList; private final List<Cron> tasksList;
static class CronTasksViewHolder extends RecyclerView.ViewHolder {
private Cron cronTasks;
private final TextView taskName;
private CronTasksViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
final Locale locale = ctx.getResources().getConfiguration().locale;
final String timeFormat = TinyDB.getInstance(ctx).getString("dateFormat", "pretty");
ImageView runTask = itemView.findViewById(R.id.runTask);
taskName = itemView.findViewById(R.id.taskName);
LinearLayout cronTasksInfo = itemView.findViewById(R.id.cronTasksInfo);
LinearLayout cronTasksRun = itemView.findViewById(R.id.cronTasksRun);
cronTasksInfo.setOnClickListener(taskInfo -> {
String nextRun = "";
String lastRun = "";
if(cronTasks.getNext() != null) {
nextRun = TimeHelper.formatTime(cronTasks.getNext(), locale, timeFormat, ctx);
}
if(cronTasks.getPrev() != null) {
lastRun = TimeHelper.formatTime(cronTasks.getPrev(), locale, timeFormat, ctx);
}
View view = LayoutInflater.from(ctx).inflate(R.layout.layout_cron_task_info, null);
TextView taskScheduleContent = view.findViewById(R.id.taskScheduleContent);
TextView nextRunContent = view.findViewById(R.id.nextRunContent);
TextView lastRunContent = view.findViewById(R.id.lastRunContent);
TextView execTimeContent = view.findViewById(R.id.execTimeContent);
taskScheduleContent.setText(cronTasks.getSchedule());
nextRunContent.setText(nextRun);
lastRunContent.setText(lastRun);
execTimeContent.setText(String.valueOf(cronTasks.getExecTimes()));
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx)
.setTitle(StringUtils.capitalize(cronTasks.getName().replace("_", " ")))
.setView(view)
.setPositiveButton(ctx.getString(R.string.close), null);
materialAlertDialogBuilder.create().show();
});
cronTasksRun.setOnClickListener(taskInfo -> {
runCronTask(ctx, cronTasks.getName());
});
}
}
public AdminCronTasksAdapter(List<Cron> tasksListMain) { public AdminCronTasksAdapter(List<Cron> tasksListMain) {
this.tasksList = tasksListMain; this.tasksList = tasksListMain;
} }
@NonNull
@Override
public AdminCronTasksAdapter.CronTasksViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_admin_cron_tasks, parent, false);
return new AdminCronTasksAdapter.CronTasksViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull AdminCronTasksAdapter.CronTasksViewHolder holder, int position) {
Cron currentItem = tasksList.get(position);
holder.cronTasks = currentItem;
holder.taskName.setText(StringUtils.capitalize(currentItem.getName().replace("_", " ")));
}
private static void runCronTask(final Context ctx, final String taskName) { private static void runCronTask(final Context ctx, final String taskName) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(ctx).adminCronRun(taskName);
.getApiInterface(ctx)
.adminCronRun(taskName);
call.enqueue(new Callback<Void>() { call.enqueue(new Callback<Void>() {
@ -153,8 +76,82 @@ public class AdminCronTasksAdapter extends RecyclerView.Adapter<AdminCronTasksAd
}); });
} }
@NonNull
@Override
public AdminCronTasksAdapter.CronTasksViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_admin_cron_tasks, parent, false);
return new AdminCronTasksAdapter.CronTasksViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull AdminCronTasksAdapter.CronTasksViewHolder holder, int position) {
Cron currentItem = tasksList.get(position);
holder.cronTasks = currentItem;
holder.taskName.setText(StringUtils.capitalize(currentItem.getName().replace("_", " ")));
}
@Override @Override
public int getItemCount() { public int getItemCount() {
return tasksList.size(); return tasksList.size();
} }
static class CronTasksViewHolder extends RecyclerView.ViewHolder {
private final TextView taskName;
private Cron cronTasks;
private CronTasksViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
final Locale locale = ctx.getResources().getConfiguration().locale;
final String timeFormat = TinyDB.getInstance(ctx).getString("dateFormat", "pretty");
ImageView runTask = itemView.findViewById(R.id.runTask);
taskName = itemView.findViewById(R.id.taskName);
LinearLayout cronTasksInfo = itemView.findViewById(R.id.cronTasksInfo);
LinearLayout cronTasksRun = itemView.findViewById(R.id.cronTasksRun);
cronTasksInfo.setOnClickListener(taskInfo -> {
String nextRun = "";
String lastRun = "";
if(cronTasks.getNext() != null) {
nextRun = TimeHelper.formatTime(cronTasks.getNext(), locale, timeFormat, ctx);
}
if(cronTasks.getPrev() != null) {
lastRun = TimeHelper.formatTime(cronTasks.getPrev(), locale, timeFormat, ctx);
}
View view = LayoutInflater.from(ctx).inflate(R.layout.layout_cron_task_info, null);
TextView taskScheduleContent = view.findViewById(R.id.taskScheduleContent);
TextView nextRunContent = view.findViewById(R.id.nextRunContent);
TextView lastRunContent = view.findViewById(R.id.lastRunContent);
TextView execTimeContent = view.findViewById(R.id.execTimeContent);
taskScheduleContent.setText(cronTasks.getSchedule());
nextRunContent.setText(nextRun);
lastRunContent.setText(lastRun);
execTimeContent.setText(String.valueOf(cronTasks.getExecTimes()));
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(StringUtils.capitalize(cronTasks.getName().replace("_", " "))).setView(view)
.setPositiveButton(ctx.getString(R.string.close), null);
materialAlertDialogBuilder.create().show();
});
cronTasksRun.setOnClickListener(taskInfo -> {
runCronTask(ctx, cronTasks.getName());
});
}
}
} }

View File

@ -30,11 +30,43 @@ import java.util.List;
public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private List<User> usersList;
private final List<User> usersListFull; private final List<User> usersListFull;
private final Context context; private final Context context;
private List<User> usersList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final Filter usersFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(usersListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(User item : usersListFull) {
if(item.getEmail().toLowerCase().contains(filterPattern) || item.getFullName().toLowerCase().contains(filterPattern) || item.getLogin().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
usersList.clear();
usersList.addAll((List) results.values);
notifyDataChanged();
}
};
public AdminGetUsersAdapter(List<User> usersListMain, Context ctx) { public AdminGetUsersAdapter(List<User> usersListMain, Context ctx) {
this.context = ctx; this.context = ctx;
@ -69,14 +101,50 @@ public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.View
return usersList.size(); return usersList.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<User> list) {
usersList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return usersFilter;
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class ReposHolder extends RecyclerView.ViewHolder { class ReposHolder extends RecyclerView.ViewHolder {
private String userLoginId;
private final ImageView userAvatar; private final ImageView userAvatar;
private final TextView userFullName; private final TextView userFullName;
private final TextView userEmail; private final TextView userEmail;
private final ImageView userRole; private final ImageView userRole;
private final TextView userName; private final TextView userName;
private String userLoginId;
ReposHolder(View itemView) { ReposHolder(View itemView) {
@ -126,9 +194,8 @@ public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.View
if(users.isIsAdmin()) { if(users.isIsAdmin()) {
userRole.setVisibility(View.VISIBLE); userRole.setVisibility(View.VISIBLE);
TextDrawable drawable = TextDrawable.builder().beginConfig() TextDrawable drawable = TextDrawable.builder().beginConfig().textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null)).fontSize(60).width(200).height(80).endConfig()
.textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null)).fontSize(60).width(200).height(80) .buildRoundRect(context.getResources().getString(R.string.userRoleAdmin).toLowerCase(), ResourcesCompat.getColor(context.getResources(), R.color.releasePre, null), 8);
.endConfig().buildRoundRect(context.getResources().getString(R.string.userRoleAdmin).toLowerCase(), ResourcesCompat.getColor(context.getResources(), R.color.releasePre, null), 8);
userRole.setImageDrawable(drawable); userRole.setImageDrawable(drawable);
} }
else { else {
@ -138,71 +205,7 @@ public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.View
PicassoService.getInstance(context).get().load(users.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(userAvatar); PicassoService.getInstance(context).get().load(users.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(userAvatar);
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<User> list) {
usersList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return usersFilter;
}
private final Filter usersFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(usersListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (User item : usersListFull) {
if (item.getEmail().toLowerCase().contains(filterPattern) || item.getFullName().toLowerCase().contains(filterPattern) || item.getLogin().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
usersList.clear();
usersList.addAll((List) results.values);
notifyDataChanged();
}
};
} }

View File

@ -25,37 +25,11 @@ import retrofit2.Callback;
public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadoptedReposAdapter.UnadoptedViewHolder> { public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadoptedReposAdapter.UnadoptedViewHolder> {
private List<String> repos;
private final Runnable updateList; private final Runnable updateList;
private final Runnable loadMoreListener; private final Runnable loadMoreListener;
private boolean isLoading = false, hasMore = true;
private final ActivityAdminCronTasksBinding activityAdminCronTasksBinding; private final ActivityAdminCronTasksBinding activityAdminCronTasksBinding;
private List<String> repos;
class UnadoptedViewHolder extends RecyclerView.ViewHolder { private boolean isLoading = false, hasMore = true;
private String repoName;
private final TextView name;
private UnadoptedViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
name = itemView.findViewById(R.id.repo_name);
itemView.setOnClickListener(taskInfo -> {
String[] repoSplit = repoName.split("/");
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx)
.setTitle(repoName).setMessage(ctx.getString(R.string.unadoptedReposMessage, repoSplit[1], repoSplit[0]))
.setNeutralButton(R.string.close, null)
.setPositiveButton(R.string.menuDeleteText, ((dialog, which) -> delete(ctx, repoName)))
.setNegativeButton(R.string.adoptRepo, ((dialog, which) -> adopt(ctx, repoName, getBindingAdapterPosition())));
materialAlertDialogBuilder.create().show();
});
}
}
public AdminUnadoptedReposAdapter(List<String> list, Runnable updateList, Runnable loadMore, ActivityAdminCronTasksBinding activityAdminCronTasksBinding) { public AdminUnadoptedReposAdapter(List<String> list, Runnable updateList, Runnable loadMore, ActivityAdminCronTasksBinding activityAdminCronTasksBinding) {
this.repos = list; this.repos = list;
@ -95,9 +69,7 @@ public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadop
String[] repoSplit = name.split("/"); String[] repoSplit = name.split("/");
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(ctx).adminDeleteUnadoptedRepository(repoSplit[0], repoSplit[1]);
.getApiInterface(ctx)
.adminDeleteUnadoptedRepository(repoSplit[0], repoSplit[1]);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -141,9 +113,7 @@ public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadop
String[] repoSplit = name.split("/"); String[] repoSplit = name.split("/");
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(ctx).adminAdoptRepository(repoSplit[0], repoSplit[1]);
.getApiInterface(ctx)
.adminAdoptRepository(repoSplit[0], repoSplit[1]);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -201,4 +171,30 @@ public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadop
this.hasMore = hasMore; this.hasMore = hasMore;
isLoading = false; isLoading = false;
} }
class UnadoptedViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private String repoName;
private UnadoptedViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
name = itemView.findViewById(R.id.repo_name);
itemView.setOnClickListener(taskInfo -> {
String[] repoSplit = repoName.split("/");
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(repoName).setMessage(ctx.getString(R.string.unadoptedReposMessage, repoSplit[1], repoSplit[0]))
.setNeutralButton(R.string.close, null).setPositiveButton(R.string.menuDeleteText, ((dialog, which) -> delete(ctx, repoName)))
.setNegativeButton(R.string.adoptRepo, ((dialog, which) -> adopt(ctx, repoName, getBindingAdapterPosition())));
materialAlertDialogBuilder.create().show();
});
}
}
} }

View File

@ -28,16 +28,10 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
private final Context context; private final Context context;
private final List<User> assigneesList; private final List<User> assigneesList;
private final AssigneesListAdapterListener assigneesListener;
private List<String> assigneesStrings = new ArrayList<>(); private List<String> assigneesStrings = new ArrayList<>();
private List<String> currentAssignees; private List<String> currentAssignees;
private final AssigneesListAdapterListener assigneesListener;
public interface AssigneesListAdapterListener {
void assigneesInterface(List<String> data);
}
public AssigneesListAdapter(Context ctx, List<User> dataMain, AssigneesListAdapterListener assigneesListener, List<String> currentAssignees) { public AssigneesListAdapter(Context ctx, List<User> dataMain, AssigneesListAdapterListener assigneesListener, List<String> currentAssignees) {
this.context = ctx; this.context = ctx;
@ -46,23 +40,6 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
this.currentAssignees = currentAssignees; this.currentAssignees = currentAssignees;
} }
static class AssigneesViewHolder extends RecyclerView.ViewHolder {
private final CheckBox assigneesSelection;
private final TextView assigneesName;
private final ImageView assigneesAvatar;
private AssigneesViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
assigneesSelection = itemView.findViewById(R.id.assigneesSelection);
assigneesName = itemView.findViewById(R.id.assigneesName);
assigneesAvatar = itemView.findViewById(R.id.assigneesAvatar);
}
}
@NonNull @NonNull
@Override @Override
public AssigneesListAdapter.AssigneesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public AssigneesListAdapter.AssigneesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -85,8 +62,8 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
holder.assigneesName.setText(Html.fromHtml(currentItem.getFullName())); holder.assigneesName.setText(Html.fromHtml(currentItem.getFullName()));
} }
PicassoService PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop()
.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop().into(holder.assigneesAvatar); .into(holder.assigneesAvatar);
for(int i = 0; i < assigneesList.size(); i++) { for(int i = 0; i < assigneesList.size(); i++) {
@ -138,4 +115,29 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
currentAssignees = list; currentAssignees = list;
notifyDataSetChanged(); notifyDataSetChanged();
} }
public interface AssigneesListAdapterListener {
void assigneesInterface(List<String> data);
}
static class AssigneesViewHolder extends RecyclerView.ViewHolder {
private final CheckBox assigneesSelection;
private final TextView assigneesName;
private final ImageView assigneesAvatar;
private AssigneesViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
assigneesSelection = itemView.findViewById(R.id.assigneesSelection);
assigneesName = itemView.findViewById(R.id.assigneesName);
assigneesAvatar = itemView.findViewById(R.id.assigneesAvatar);
}
}
} }

View File

@ -37,150 +37,145 @@ import retrofit2.Response;
public class CollaboratorSearchAdapter extends RecyclerView.Adapter<CollaboratorSearchAdapter.CollaboratorSearchViewHolder> { public class CollaboratorSearchAdapter extends RecyclerView.Adapter<CollaboratorSearchAdapter.CollaboratorSearchViewHolder> {
private final List<User> usersSearchList; private final List<User> usersSearchList;
private final Context context; private final Context context;
private final RepositoryContext repository; private final RepositoryContext repository;
public CollaboratorSearchAdapter(List<User> dataList, Context ctx, RepositoryContext repository) { public CollaboratorSearchAdapter(List<User> dataList, Context ctx, RepositoryContext repository) {
this.context = ctx; this.context = ctx;
this.usersSearchList = dataList; this.usersSearchList = dataList;
this.repository = repository; this.repository = repository;
} }
class CollaboratorSearchViewHolder extends RecyclerView.ViewHolder { @NonNull
@Override
public CollaboratorSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_collaborators_search, parent, false);
return new CollaboratorSearchAdapter.CollaboratorSearchViewHolder(v);
}
private User userInfo; @Override
public void onBindViewHolder(@NonNull final CollaboratorSearchViewHolder holder, int position) {
private final ImageView userAvatar; User currentItem = usersSearchList.get(position);
private final TextView userFullName; int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
private final TextView userName; holder.userInfo = currentItem;
private final ImageView addCollaboratorButtonAdd;
private final ImageView addCollaboratorButtonRemove;
private final String[] permissionList = {"Read", "Write", "Admin"}; if(!currentItem.getFullName().equals("")) {
final private int permissionSelectedChoice = 0;
private CollaboratorSearchViewHolder(View itemView) { holder.userFullName.setText(Html.fromHtml(currentItem.getFullName()));
}
else {
super(itemView); holder.userFullName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin()));
userAvatar = itemView.findViewById(R.id.userAvatar); }
userFullName = itemView.findViewById(R.id.userFullName);
userName = itemView.findViewById(R.id.userName);
addCollaboratorButtonAdd = itemView.findViewById(R.id.addCollaboratorButtonAdd);
addCollaboratorButtonRemove = itemView.findViewById(R.id.addCollaboratorButtonRemove);
addCollaboratorButtonAdd.setOnClickListener(v -> { holder.userName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin()));
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context) if(!currentItem.getAvatarUrl().equals("")) {
.setTitle(R.string.newTeamPermission) PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.setSingleChoiceItems(permissionList, permissionSelectedChoice, null) .into(holder.userAvatar);
.setNeutralButton(R.string.cancelButton, null) }
.setPositiveButton(R.string.addButton, (dialog, which) -> {
ListView lw = ((AlertDialog)dialog).getListView(); if(getItemCount() > 0) {
Object checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition());
CollaboratorActions.addCollaborator(context, String.valueOf(checkedItem).toLowerCase(), userInfo.getLogin(), repository); final String loginUid = ((BaseActivity) context).getAccount().getAccount().getUserName();
});
materialAlertDialogBuilder.create().show(); Call<Void> call = RetrofitClient.getApiInterface(context).repoCheckCollaborator(repository.getOwner(), repository.getName(), currentItem.getLogin());
});
addCollaboratorButtonRemove.setOnClickListener(v -> AlertDialogs.collaboratorRemoveDialog(context, userInfo.getLogin(), repository)); call.enqueue(new Callback<Void>() {
new Handler().postDelayed(() -> { @Override
if(!AppUtil.checkGhostUsers(userInfo.getLogin())) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
userAvatar.setOnClickListener(loginId -> { if(response.code() == 204) {
Intent intent = new Intent(context, ProfileActivity.class); if(!currentItem.getLogin().equals(loginUid) && !currentItem.getLogin().equals(repository.getOwner())) {
intent.putExtra("username", userInfo.getLogin()); holder.addCollaboratorButtonRemove.setVisibility(View.VISIBLE);
context.startActivity(intent); }
}); else {
holder.addCollaboratorButtonRemove.setVisibility(View.GONE);
}
}
else if(response.code() == 404) {
if(!currentItem.getLogin().equals(loginUid) && !currentItem.getLogin().equals(repository.getOwner())) {
holder.addCollaboratorButtonAdd.setVisibility(View.VISIBLE);
}
else {
holder.addCollaboratorButtonAdd.setVisibility(View.GONE);
}
}
else {
holder.addCollaboratorButtonRemove.setVisibility(View.GONE);
holder.addCollaboratorButtonAdd.setVisibility(View.GONE);
}
}
userAvatar.setOnLongClickListener(loginId -> { @Override
AppUtil.copyToClipboard(context, userInfo.getLogin(), context.getString(R.string.copyLoginIdToClipBoard, userInfo.getLogin())); public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
return true; Log.i("onFailure", t.toString());
}); }
} });
}, 500); }
} }
} @Override
public int getItemCount() {
return usersSearchList.size();
}
@NonNull class CollaboratorSearchViewHolder extends RecyclerView.ViewHolder {
@Override
public CollaboratorSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_collaborators_search, parent, false);
return new CollaboratorSearchAdapter.CollaboratorSearchViewHolder(v);
}
@Override private final ImageView userAvatar;
public void onBindViewHolder(@NonNull final CollaboratorSearchViewHolder holder, int position) { private final TextView userFullName;
private final TextView userName;
private final ImageView addCollaboratorButtonAdd;
private final ImageView addCollaboratorButtonRemove;
private final String[] permissionList = {"Read", "Write", "Admin"};
final private int permissionSelectedChoice = 0;
private User userInfo;
User currentItem = usersSearchList.get(position); private CollaboratorSearchViewHolder(View itemView) {
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
holder.userInfo = currentItem;
if (!currentItem.getFullName().equals("")) { super(itemView);
userAvatar = itemView.findViewById(R.id.userAvatar);
userFullName = itemView.findViewById(R.id.userFullName);
userName = itemView.findViewById(R.id.userName);
addCollaboratorButtonAdd = itemView.findViewById(R.id.addCollaboratorButtonAdd);
addCollaboratorButtonRemove = itemView.findViewById(R.id.addCollaboratorButtonRemove);
holder.userFullName.setText(Html.fromHtml(currentItem.getFullName())); addCollaboratorButtonAdd.setOnClickListener(v -> {
}
else {
holder.userFullName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin())); MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context).setTitle(R.string.newTeamPermission).setSingleChoiceItems(permissionList, permissionSelectedChoice, null)
} .setNeutralButton(R.string.cancelButton, null).setPositiveButton(R.string.addButton, (dialog, which) -> {
holder.userName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin())); ListView lw = ((AlertDialog) dialog).getListView();
Object checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition());
if (!currentItem.getAvatarUrl().equals("")) { CollaboratorActions.addCollaborator(context, String.valueOf(checkedItem).toLowerCase(), userInfo.getLogin(), repository);
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.userAvatar); });
}
if(getItemCount() > 0) { materialAlertDialogBuilder.create().show();
});
final String loginUid = ((BaseActivity) context).getAccount().getAccount().getUserName(); addCollaboratorButtonRemove.setOnClickListener(v -> AlertDialogs.collaboratorRemoveDialog(context, userInfo.getLogin(), repository));
Call<Void> call = RetrofitClient new Handler().postDelayed(() -> {
.getApiInterface(context) if(!AppUtil.checkGhostUsers(userInfo.getLogin())) {
.repoCheckCollaborator(repository.getOwner(), repository.getName(), currentItem.getLogin());
call.enqueue(new Callback<Void>() { userAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userInfo.getLogin());
context.startActivity(intent);
});
@Override userAvatar.setOnLongClickListener(loginId -> {
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { AppUtil.copyToClipboard(context, userInfo.getLogin(), context.getString(R.string.copyLoginIdToClipBoard, userInfo.getLogin()));
return true;
});
}
}, 500);
}
if(response.code() == 204) { }
if(!currentItem.getLogin().equals(loginUid) && !currentItem.getLogin().equals(repository.getOwner())) {
holder.addCollaboratorButtonRemove.setVisibility(View.VISIBLE);
}
else {
holder.addCollaboratorButtonRemove.setVisibility(View.GONE);
}
}
else if(response.code() == 404) {
if(!currentItem.getLogin().equals(loginUid) && !currentItem.getLogin().equals(repository.getOwner())) {
holder.addCollaboratorButtonAdd.setVisibility(View.VISIBLE);
}
else {
holder.addCollaboratorButtonAdd.setVisibility(View.GONE);
}
}
else {
holder.addCollaboratorButtonRemove.setVisibility(View.GONE);
holder.addCollaboratorButtonAdd.setVisibility(View.GONE);
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Log.i("onFailure", t.toString());
}
});
}
}
@Override
public int getItemCount() {
return usersSearchList.size();
}
} }

View File

@ -22,96 +22,97 @@ import java.util.List;
* @author M M Arif * @author M M Arif
*/ */
public class CollaboratorsAdapter extends BaseAdapter { public class CollaboratorsAdapter extends BaseAdapter {
private final List<User> collaboratorsList; private final List<User> collaboratorsList;
private final Context context; private final Context context;
private class ViewHolder { public CollaboratorsAdapter(Context ctx, List<User> collaboratorsListMain) {
private String userLoginId; this.context = ctx;
this.collaboratorsList = collaboratorsListMain;
}
private final ImageView collaboratorAvatar; @Override
private final TextView collaboratorName; public int getCount() {
return collaboratorsList.size();
}
ViewHolder(View v) { @Override
public Object getItem(int position) {
return null;
}
collaboratorAvatar = v.findViewById(R.id.collaboratorAvatar); @Override
collaboratorName = v.findViewById(R.id.collaboratorName); public long getItemId(int position) {
return 0;
}
collaboratorAvatar.setOnClickListener(loginId -> { @SuppressLint("InflateParams")
Intent intent = new Intent(context, ProfileActivity.class); @Override
intent.putExtra("username", userLoginId); public View getView(int position, View finalView, ViewGroup parent) {
context.startActivity(intent);
});
collaboratorAvatar.setOnLongClickListener(loginId -> { ViewHolder viewHolder;
AppUtil.copyToClipboard(context, userLoginId, context.getString(R.string.copyLoginIdToClipBoard, userLoginId));
return true;
});
}
}
public CollaboratorsAdapter(Context ctx, List<User> collaboratorsListMain) { if(finalView == null) {
this.context = ctx; finalView = LayoutInflater.from(context).inflate(R.layout.list_collaborators, null);
this.collaboratorsList = collaboratorsListMain; viewHolder = new ViewHolder(finalView);
} finalView.setTag(viewHolder);
}
else {
@Override viewHolder = (ViewHolder) finalView.getTag();
public int getCount() { }
return collaboratorsList.size();
}
@Override initData(viewHolder, position);
public Object getItem(int position) { return finalView;
return null; }
}
@Override private void initData(ViewHolder viewHolder, int position) {
public long getItemId(int position) {
return 0;
}
@SuppressLint("InflateParams") int imgRadius = AppUtil.getPixelsFromDensity(context, 90);
@Override
public View getView(int position, View finalView, ViewGroup parent) {
ViewHolder viewHolder; User currentItem = collaboratorsList.get(position);
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop()
.into(viewHolder.collaboratorAvatar);
if (finalView == null) { viewHolder.userLoginId = currentItem.getLogin();
finalView = LayoutInflater.from(context).inflate(R.layout.list_collaborators, null); if(!currentItem.getFullName().equals("")) {
viewHolder = new ViewHolder(finalView);
finalView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) finalView.getTag(); viewHolder.collaboratorName.setText(Html.fromHtml(currentItem.getFullName()));
} }
else {
initData(viewHolder, position); viewHolder.collaboratorName.setText(currentItem.getLogin());
return finalView; }
}
private void initData(ViewHolder viewHolder, int position) { }
int imgRadius = AppUtil.getPixelsFromDensity(context, 90); private class ViewHolder {
User currentItem = collaboratorsList.get(position); private final ImageView collaboratorAvatar;
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop().into(viewHolder.collaboratorAvatar); private final TextView collaboratorName;
private String userLoginId;
viewHolder.userLoginId = currentItem.getLogin(); ViewHolder(View v) {
if(!currentItem.getFullName().equals("")) { collaboratorAvatar = v.findViewById(R.id.collaboratorAvatar);
collaboratorName = v.findViewById(R.id.collaboratorName);
viewHolder.collaboratorName.setText(Html.fromHtml(currentItem.getFullName())); collaboratorAvatar.setOnClickListener(loginId -> {
} Intent intent = new Intent(context, ProfileActivity.class);
else { intent.putExtra("username", userLoginId);
context.startActivity(intent);
});
viewHolder.collaboratorName.setText(currentItem.getLogin()); collaboratorAvatar.setOnLongClickListener(loginId -> {
} AppUtil.copyToClipboard(context, userLoginId, context.getString(R.string.copyLoginIdToClipBoard, userLoginId));
return true;
});
}
} }
} }

View File

@ -31,163 +31,154 @@ import java.util.Objects;
public class CommitsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class CommitsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private List<Commit> commitsList; private List<Commit> commitsList;
private Runnable loadMoreListener; private Runnable loadMoreListener;
private boolean isLoading = false; private boolean isLoading = false;
private boolean isMoreDataAvailable = true; private boolean isMoreDataAvailable = true;
public CommitsAdapter(Context ctx, List<Commit> commitsListMain) { public CommitsAdapter(Context ctx, List<Commit> commitsListMain) {
this.context = ctx; this.context = ctx;
this.commitsList = commitsListMain; this.commitsList = commitsListMain;
} }
@NonNull @NonNull
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context); LayoutInflater inflater = LayoutInflater.from(context);
return new CommitsHolder(inflater.inflate(R.layout.list_commits, parent, false)); return new CommitsHolder(inflater.inflate(R.layout.list_commits, parent, false));
} }
@Override @Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) { if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true; isLoading = true;
loadMoreListener.run(); loadMoreListener.run();
} }
((CommitsHolder) holder).bindData(commitsList.get(position)); ((CommitsHolder) holder).bindData(commitsList.get(position));
} }
@Override @Override
public int getItemViewType(int position) { public int getItemViewType(int position) {
return position; return position;
} }
@Override @Override
public int getItemCount() { public int getItemCount() {
return commitsList.size(); return commitsList.size();
} }
class CommitsHolder extends RecyclerView.ViewHolder {
View rootView;
TextView commitSubject;
TextView commitAuthorAndCommitter;
ImageView commitAuthorAvatar;
ImageView commitCommitterAvatar;
TextView commitSha;
CommitsHolder(View itemView) {
super(itemView);
rootView = itemView;
commitSubject = itemView.findViewById(R.id.commitSubject);
commitAuthorAndCommitter = itemView.findViewById(R.id.commitAuthorAndCommitter);
commitAuthorAvatar = itemView.findViewById(R.id.commitAuthorAvatar);
commitCommitterAvatar = itemView.findViewById(R.id.commitCommitterAvatar);
commitSha = itemView.findViewById(R.id.commitSha);
}
void bindData(Commit commitsModel) {
String[] commitMessageParts = commitsModel.getCommit().getMessage().split("(\r\n|\n)", 2);
commitSubject.setText(EmojiParser.parseToUnicode(commitMessageParts[0].trim()));
if(!Objects.equals(commitsModel.getCommit().getCommitter().getEmail(), commitsModel.getCommit().getAuthor().getEmail())) {
commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(context
.getString(R.string.commitAuthoredByAndCommittedByWhen, commitsModel.getCommit().getAuthor().getName(), commitsModel.getCommit().getCommitter().getName(),
TimeHelper
.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty",
context)), HtmlCompat.FROM_HTML_MODE_COMPACT));
} else {
commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(context
.getString(R.string.commitCommittedByWhen, commitsModel.getCommit().getCommitter().getName(),
TimeHelper
.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty",
context)), HtmlCompat.FROM_HTML_MODE_COMPACT));
}
if(commitsModel.getAuthor() != null && commitsModel.getAuthor().getAvatarUrl() != null &&
!commitsModel.getAuthor().getAvatarUrl().isEmpty()) {
commitAuthorAvatar.setVisibility(View.VISIBLE);
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
PicassoService.getInstance(context).get()
.load(commitsModel.getAuthor().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop().into(commitAuthorAvatar);
} else {
commitAuthorAvatar.setImageDrawable(null);
commitAuthorAvatar.setVisibility(View.GONE);
}
if(commitsModel.getCommitter() != null &&
(commitsModel.getAuthor() == null || !commitsModel.getAuthor().getLogin().equals(commitsModel.getCommitter().getLogin())) &&
commitsModel.getCommitter().getAvatarUrl() != null &&
!commitsModel.getCommitter().getAvatarUrl().isEmpty()) {
commitCommitterAvatar.setVisibility(View.VISIBLE);
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
PicassoService.getInstance(context).get()
.load(commitsModel.getCommitter().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop().into(commitCommitterAvatar);
} else {
commitCommitterAvatar.setImageDrawable(null);
commitCommitterAvatar.setVisibility(View.GONE);
}
commitSha.setText(commitsModel.getSha().substring(0, Math.min(commitsModel.getSha().length(), 10)));
rootView.setOnClickListener(v -> {
Intent intent;
if(context instanceof CommitsActivity) {
intent = ((CommitsActivity) context).repository.getIntent(context, CommitDetailActivity.class);
} else {
intent = IssueContext.fromIntent(((DiffActivity) context).getIntent()).getRepository()
.getIntent(context, CommitDetailActivity.class);
}
intent.putExtra("sha", commitsModel.getSha());
context.startActivity(intent);
});
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable; isMoreDataAvailable = moreDataAvailable;
} }
@SuppressLint("NotifyDataSetChanged") @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() { public void notifyDataChanged() {
notifyDataSetChanged(); notifyDataSetChanged();
isLoading = false; isLoading = false;
} }
public void setLoadMoreListener(Runnable loadMoreListener) { public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener; this.loadMoreListener = loadMoreListener;
} }
public void updateList(List<Commit> list) {
commitsList = list;
notifyDataChanged();
}
class CommitsHolder extends RecyclerView.ViewHolder {
View rootView;
TextView commitSubject;
TextView commitAuthorAndCommitter;
ImageView commitAuthorAvatar;
ImageView commitCommitterAvatar;
TextView commitSha;
CommitsHolder(View itemView) {
super(itemView);
rootView = itemView;
commitSubject = itemView.findViewById(R.id.commitSubject);
commitAuthorAndCommitter = itemView.findViewById(R.id.commitAuthorAndCommitter);
commitAuthorAvatar = itemView.findViewById(R.id.commitAuthorAvatar);
commitCommitterAvatar = itemView.findViewById(R.id.commitCommitterAvatar);
commitSha = itemView.findViewById(R.id.commitSha);
}
void bindData(Commit commitsModel) {
String[] commitMessageParts = commitsModel.getCommit().getMessage().split("(\r\n|\n)", 2);
commitSubject.setText(EmojiParser.parseToUnicode(commitMessageParts[0].trim()));
if(!Objects.equals(commitsModel.getCommit().getCommitter().getEmail(), commitsModel.getCommit().getAuthor().getEmail())) {
commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(
context.getString(R.string.commitAuthoredByAndCommittedByWhen, commitsModel.getCommit().getAuthor().getName(), commitsModel.getCommit().getCommitter().getName(),
TimeHelper.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty", context)),
HtmlCompat.FROM_HTML_MODE_COMPACT));
}
else {
commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(context.getString(R.string.commitCommittedByWhen, commitsModel.getCommit().getCommitter().getName(),
TimeHelper.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty", context)),
HtmlCompat.FROM_HTML_MODE_COMPACT));
}
if(commitsModel.getAuthor() != null && commitsModel.getAuthor().getAvatarUrl() != null && !commitsModel.getAuthor().getAvatarUrl().isEmpty()) {
commitAuthorAvatar.setVisibility(View.VISIBLE);
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
PicassoService.getInstance(context).get().load(commitsModel.getAuthor().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120)
.centerCrop().into(commitAuthorAvatar);
}
else {
commitAuthorAvatar.setImageDrawable(null);
commitAuthorAvatar.setVisibility(View.GONE);
}
if(commitsModel.getCommitter() != null && (commitsModel.getAuthor() == null || !commitsModel.getAuthor().getLogin().equals(commitsModel.getCommitter().getLogin())) && commitsModel.getCommitter()
.getAvatarUrl() != null && !commitsModel.getCommitter().getAvatarUrl().isEmpty()) {
commitCommitterAvatar.setVisibility(View.VISIBLE);
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
PicassoService.getInstance(context).get().load(commitsModel.getCommitter().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120)
.centerCrop().into(commitCommitterAvatar);
}
else {
commitCommitterAvatar.setImageDrawable(null);
commitCommitterAvatar.setVisibility(View.GONE);
}
commitSha.setText(commitsModel.getSha().substring(0, Math.min(commitsModel.getSha().length(), 10)));
rootView.setOnClickListener(v -> {
Intent intent;
if(context instanceof CommitsActivity) {
intent = ((CommitsActivity) context).repository.getIntent(context, CommitDetailActivity.class);
}
else {
intent = IssueContext.fromIntent(((DiffActivity) context).getIntent()).getRepository().getIntent(context, CommitDetailActivity.class);
}
intent.putExtra("sha", commitsModel.getSha());
context.startActivity(intent);
});
}
}
public void updateList(List<Commit> list) {
commitsList = list;
notifyDataChanged();
}
} }

View File

@ -23,20 +23,18 @@ import java.util.stream.Collectors;
public class DiffAdapter extends BaseAdapter { public class DiffAdapter extends BaseAdapter {
private final Context context;
private final FragmentManager fragmentManager;
private final List<String> lines;
private final IssueContext issue;
private final List<Integer> selectedLines;
private final Typeface typeface;
private final String type;
private static int COLOR_ADDED; private static int COLOR_ADDED;
private static int COLOR_REMOVED; private static int COLOR_REMOVED;
private static int COLOR_NORMAL; private static int COLOR_NORMAL;
private static int COLOR_SELECTED; private static int COLOR_SELECTED;
private static int COLOR_FONT; private static int COLOR_FONT;
private final Context context;
private final FragmentManager fragmentManager;
private final List<String> lines;
private final IssueContext issue;
private final List<Integer> selectedLines;
private final Typeface typeface;
private final String type;
public DiffAdapter(Context context, FragmentManager fragmentManager, List<String> lines, IssueContext issue, String type) { public DiffAdapter(Context context, FragmentManager fragmentManager, List<String> lines, IssueContext issue, String type) {
@ -123,8 +121,8 @@ public class DiffAdapter extends BaseAdapter {
bundle.putString("commentBody", stringBuilder.toString()); bundle.putString("commentBody", stringBuilder.toString());
bundle.putBoolean("cursorToEnd", true); bundle.putBoolean("cursorToEnd", true);
BottomSheetReplyFragment.newInstance(bundle, issue).show(fragmentManager, "replyBottomSheet"); BottomSheetReplyFragment.newInstance(bundle, issue).show(fragmentManager, "replyBottomSheet");
} }
return true; return true;
@ -149,10 +147,13 @@ public class DiffAdapter extends BaseAdapter {
} }
switch(line.charAt(0)) { switch(line.charAt(0)) {
case '+': return COLOR_ADDED; case '+':
case '-': return COLOR_REMOVED; return COLOR_ADDED;
case '-':
return COLOR_REMOVED;
default: return COLOR_NORMAL; default:
return COLOR_NORMAL;
} }
} }

View File

@ -28,9 +28,9 @@ public class DiffFilesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
private static final Pattern statisticsPattern = Pattern.compile("(\\d+).*?,.*?(\\d+)"); private static final Pattern statisticsPattern = Pattern.compile("(\\d+).*?,.*?(\\d+)");
private final Context context; private final Context context;
private List<FileDiffView> fileDiffViews;
private final IssueContext issue; private final IssueContext issue;
private final String fragmentType; private final String fragmentType;
private List<FileDiffView> fileDiffViews;
public DiffFilesAdapter(Context context, List<FileDiffView> fileDiffViews, IssueContext issue, String fragmentType) { public DiffFilesAdapter(Context context, List<FileDiffView> fileDiffViews, IssueContext issue, String fragmentType) {
@ -53,53 +53,6 @@ public class DiffFilesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
((DiffFilesAdapter.FilesHolder) holder).bindData(fileDiffViews.get(position)); ((DiffFilesAdapter.FilesHolder) holder).bindData(fileDiffViews.get(position));
} }
class FilesHolder extends RecyclerView.ViewHolder {
FileDiffView diffFilesObject;
TextView fileName;
TextView fileStatistics;
LinearLayout main_frame;
FilesHolder(View itemView) {
super(itemView);
fileName = itemView.findViewById(R.id.fileName);
fileStatistics = itemView.findViewById(R.id.fileStatistics);
main_frame = itemView.findViewById(R.id.main_frame);
main_frame.setOnClickListener(v -> {
if(fragmentType.equalsIgnoreCase("commit")){
((CommitDetailActivity) context).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, fragmentType))
.commit();
}
else {
((DiffActivity) context).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, issue))
.commit();
}
});
}
void bindData(FileDiffView fileDiffView) {
this.diffFilesObject = fileDiffView;
fileName.setText(fileDiffView.getFileName());
Matcher matcher = statisticsPattern.matcher(fileDiffView.getFileInfo());
if(matcher.find() && matcher.groupCount() == 2) {
fileStatistics.setText(context.getString(R.string.diffStatistics, matcher.group(1), matcher.group(2)));
} else {
fileStatistics.setText(fileDiffView.getFileInfo());
}
}
}
@Override @Override
public int getItemViewType(int position) { public int getItemViewType(int position) {
return position; return position;
@ -118,4 +71,48 @@ public class DiffFilesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
public void notifyDataChanged() { public void notifyDataChanged() {
notifyDataSetChanged(); notifyDataSetChanged();
} }
class FilesHolder extends RecyclerView.ViewHolder {
FileDiffView diffFilesObject;
TextView fileName;
TextView fileStatistics;
LinearLayout main_frame;
FilesHolder(View itemView) {
super(itemView);
fileName = itemView.findViewById(R.id.fileName);
fileStatistics = itemView.findViewById(R.id.fileStatistics);
main_frame = itemView.findViewById(R.id.main_frame);
main_frame.setOnClickListener(v -> {
if(fragmentType.equalsIgnoreCase("commit")) {
((CommitDetailActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, fragmentType)).commit();
}
else {
((DiffActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, issue)).commit();
}
});
}
void bindData(FileDiffView fileDiffView) {
this.diffFilesObject = fileDiffView;
fileName.setText(fileDiffView.getFileName());
Matcher matcher = statisticsPattern.matcher(fileDiffView.getFileInfo());
if(matcher.find() && matcher.groupCount() == 2) {
fileStatistics.setText(context.getString(R.string.diffStatistics, matcher.group(1), matcher.group(2)));
}
else {
fileStatistics.setText(fileDiffView.getFileInfo());
}
}
}
} }

View File

@ -33,121 +33,57 @@ import java.util.List;
public class DraftsAdapter extends RecyclerView.Adapter<DraftsAdapter.DraftsViewHolder> { public class DraftsAdapter extends RecyclerView.Adapter<DraftsAdapter.DraftsViewHolder> {
private List<DraftWithRepository> draftsList; private final FragmentManager fragmentManager;
private final FragmentManager fragmentManager; private final Context context;
private final Context context; private List<DraftWithRepository> draftsList;
class DraftsViewHolder extends RecyclerView.ViewHolder { public DraftsAdapter(Context ctx, FragmentManager fragmentManager, List<DraftWithRepository> draftsListMain) {
this.context = ctx;
this.fragmentManager = fragmentManager;
this.draftsList = draftsListMain;
}
private DraftWithRepository draftWithRepository; private void deleteDraft(int position) {
private final TextView draftText; draftsList.remove(position);
private final TextView repoInfo; notifyItemRemoved(position);
private final ImageView editCommentStatus; notifyItemRangeChanged(position, draftsList.size());
Toasty.success(context, context.getResources().getString(R.string.draftsSingleDeleteSuccess));
}
private DraftsViewHolder(View itemView) { @NonNull
@Override
public DraftsAdapter.DraftsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_drafts, parent, false);
return new DraftsViewHolder(v);
}
super(itemView); @SuppressLint("DefaultLocale")
@Override
public void onBindViewHolder(@NonNull DraftsAdapter.DraftsViewHolder holder, int position) {
draftText = itemView.findViewById(R.id.draftText); DraftWithRepository currentItem = draftsList.get(position);
repoInfo = itemView.findViewById(R.id.repoInfo);
ImageView deleteDraft = itemView.findViewById(R.id.deleteDraft);
editCommentStatus = itemView.findViewById(R.id.editCommentStatus);
deleteDraft.setOnClickListener(itemDelete -> { String issueNumber = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + currentItem.getIssueId() + "</font>";
Spanned headTitle = HtmlCompat.fromHtml(issueNumber + " " + currentItem.getRepositoryOwner() + " / " + currentItem.getRepositoryName(), HtmlCompat.FROM_HTML_MODE_LEGACY);
int getDraftId = draftWithRepository.getDraftId(); holder.repoInfo.setText(headTitle);
deleteDraft(getBindingAdapterPosition()); holder.draftWithRepository = currentItem;
DraftsApi draftsApi = BaseApi.getInstance(context, DraftsApi.class); Markdown.render(context, currentItem.getDraftText(), holder.draftText);
assert draftsApi != null;
draftsApi.deleteSingleDraft(getDraftId);
});
itemView.setOnClickListener(itemEdit -> { if(!currentItem.getCommentId().equalsIgnoreCase("new")) {
holder.editCommentStatus.setVisibility(View.VISIBLE);
}
else {
holder.editCommentStatus.setVisibility(View.GONE);
}
}
RepositoryContext repository = new RepositoryContext(draftWithRepository.getRepositoryOwner(), draftWithRepository.getRepositoryName(), context); @Override
repository.setRepositoryId(draftWithRepository.getRepositoryId()); public int getItemCount() {
IssueContext issue = new IssueContext(repository, draftWithRepository.getIssueId(), draftWithRepository.getIssueType()); return draftsList.size();
Bundle bundle = issue.getBundle(); }
bundle.putString("commentBody", draftWithRepository.getDraftText());
bundle.putString("issueNumber", String.valueOf(draftWithRepository.getIssueId()));
bundle.putString("draftTitle", repoInfo.getText().toString());
bundle.putString("commentId", draftWithRepository.getCommentId());
bundle.putString("draftId", String.valueOf(draftWithRepository.getDraftId()));
if(!draftWithRepository.getCommentId().isEmpty()) {
bundle.putString("commentAction", "edit");
}
BottomSheetReplyFragment bottomSheetReplyFragment = BottomSheetReplyFragment.newInstance(bundle, issue);
bottomSheetReplyFragment.setOnInteractedListener(() -> {
Intent i = new IssueContext(
new RepositoryContext(
draftWithRepository.getRepositoryOwner(),
draftWithRepository.getRepositoryName(),
context
),
draftWithRepository.getIssueId(),
draftWithRepository.getIssueType()
).getIntent(context, IssueDetailActivity.class);
i.putExtra("openedFromLink", "true");
context.startActivity(i);
});
bottomSheetReplyFragment.show(fragmentManager, "replyBottomSheet");
});
}
}
public DraftsAdapter(Context ctx, FragmentManager fragmentManager, List<DraftWithRepository> draftsListMain) {
this.context = ctx;
this.fragmentManager = fragmentManager;
this.draftsList = draftsListMain;
}
private void deleteDraft(int position) {
draftsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, draftsList.size());
Toasty.success(context, context.getResources().getString(R.string.draftsSingleDeleteSuccess));
}
@NonNull
@Override
public DraftsAdapter.DraftsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_drafts, parent, false);
return new DraftsViewHolder(v);
}
@SuppressLint("DefaultLocale")
@Override
public void onBindViewHolder(@NonNull DraftsAdapter.DraftsViewHolder holder, int position) {
DraftWithRepository currentItem = draftsList.get(position);
String issueNumber = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + currentItem.getIssueId() + "</font>";
Spanned headTitle = HtmlCompat
.fromHtml(issueNumber + " " + currentItem.getRepositoryOwner() + " / " + currentItem.getRepositoryName(), HtmlCompat.FROM_HTML_MODE_LEGACY);
holder.repoInfo.setText(headTitle);
holder.draftWithRepository = currentItem;
Markdown.render(context, currentItem.getDraftText(), holder.draftText);
if(!currentItem.getCommentId().equalsIgnoreCase("new")) {
holder.editCommentStatus.setVisibility(View.VISIBLE);
}
else {
holder.editCommentStatus.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return draftsList.size();
}
@SuppressLint("NotifyDataSetChanged") @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() { public void notifyDataChanged() {
@ -159,4 +95,61 @@ public class DraftsAdapter extends RecyclerView.Adapter<DraftsAdapter.DraftsView
draftsList = list; draftsList = list;
notifyDataChanged(); notifyDataChanged();
} }
class DraftsViewHolder extends RecyclerView.ViewHolder {
private final TextView draftText;
private final TextView repoInfo;
private final ImageView editCommentStatus;
private DraftWithRepository draftWithRepository;
private DraftsViewHolder(View itemView) {
super(itemView);
draftText = itemView.findViewById(R.id.draftText);
repoInfo = itemView.findViewById(R.id.repoInfo);
ImageView deleteDraft = itemView.findViewById(R.id.deleteDraft);
editCommentStatus = itemView.findViewById(R.id.editCommentStatus);
deleteDraft.setOnClickListener(itemDelete -> {
int getDraftId = draftWithRepository.getDraftId();
deleteDraft(getBindingAdapterPosition());
DraftsApi draftsApi = BaseApi.getInstance(context, DraftsApi.class);
assert draftsApi != null;
draftsApi.deleteSingleDraft(getDraftId);
});
itemView.setOnClickListener(itemEdit -> {
RepositoryContext repository = new RepositoryContext(draftWithRepository.getRepositoryOwner(), draftWithRepository.getRepositoryName(), context);
repository.setRepositoryId(draftWithRepository.getRepositoryId());
IssueContext issue = new IssueContext(repository, draftWithRepository.getIssueId(), draftWithRepository.getIssueType());
Bundle bundle = issue.getBundle();
bundle.putString("commentBody", draftWithRepository.getDraftText());
bundle.putString("issueNumber", String.valueOf(draftWithRepository.getIssueId()));
bundle.putString("draftTitle", repoInfo.getText().toString());
bundle.putString("commentId", draftWithRepository.getCommentId());
bundle.putString("draftId", String.valueOf(draftWithRepository.getDraftId()));
if(!draftWithRepository.getCommentId().isEmpty()) {
bundle.putString("commentAction", "edit");
}
BottomSheetReplyFragment bottomSheetReplyFragment = BottomSheetReplyFragment.newInstance(bundle, issue);
bottomSheetReplyFragment.setOnInteractedListener(() -> {
Intent i = new IssueContext(new RepositoryContext(draftWithRepository.getRepositoryOwner(), draftWithRepository.getRepositoryName(), context), draftWithRepository.getIssueId(),
draftWithRepository.getIssueType()).getIntent(context, IssueDetailActivity.class);
i.putExtra("openedFromLink", "true");
context.startActivity(i);
});
bottomSheetReplyFragment.show(fragmentManager, "replyBottomSheet");
});
}
}
} }

View File

@ -24,13 +24,7 @@ import org.mian.gitnex.R;
import org.mian.gitnex.activities.IssueDetailActivity; import org.mian.gitnex.activities.IssueDetailActivity;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
@ -46,10 +40,10 @@ import java.util.Locale;
public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final TinyDB tinyDb;
private List<Issue> searchedList; private List<Issue> searchedList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final TinyDB tinyDb;
public ExploreIssuesAdapter(List<Issue> dataList, Context ctx) { public ExploreIssuesAdapter(List<Issue> dataList, Context ctx) {
this.context = ctx; this.context = ctx;
@ -84,9 +78,38 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
return searchedList.size(); return searchedList.size();
} }
class IssuesHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
private Issue issue; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
searchedList = list;
notifyDataChanged();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class IssuesHolder extends RecyclerView.ViewHolder {
private final ImageView issueAssigneeAvatar; private final ImageView issueAssigneeAvatar;
private final TextView issueTitle; private final TextView issueTitle;
@ -96,6 +119,7 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
private final LinearLayout frameLabels; private final LinearLayout frameLabels;
private final HorizontalScrollView labelsScrollViewDots; private final HorizontalScrollView labelsScrollViewDots;
private final LinearLayout frameLabelsDots; private final LinearLayout frameLabelsDots;
private Issue issue;
IssuesHolder(View itemView) { IssuesHolder(View itemView) {
@ -154,21 +178,16 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
Locale locale = context.getResources().getConfiguration().locale; Locale locale = context.getResources().getConfiguration().locale;
String timeFormat = tinyDb.getString("dateFormat", "pretty"); String timeFormat = tinyDb.getString("dateFormat", "pretty");
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(issue.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(issue.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(issueAssigneeAvatar); .into(issueAssigneeAvatar);
String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + issue.getRepository().getFullName() + context.getResources().getString(R.string.hash) + issue.getNumber() + "</font>"; String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + issue.getRepository().getFullName() + context.getResources()
.getString(R.string.hash) + issue.getNumber() + "</font>";
issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + issue.getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY)); issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + issue.getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY));
issueCommentsCount.setText(String.valueOf(issue.getComments())); issueCommentsCount.setText(String.valueOf(issue.getComments()));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(issue.getLabels() != null) { if(issue.getLabels() != null) {
@ -215,9 +234,9 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
int height = AppUtil.getPixelsFromDensity(context, 20); int height = AppUtil.getPixelsFromDensity(context, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(context, 12); int textSize = AppUtil.getPixelsFromScaledDensity(context, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize).width( TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
LabelWidthCalculator .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig()
.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18)); .buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
frameLabels.addView(labelsView); frameLabels.addView(labelsView);
@ -252,33 +271,7 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
} }
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
searchedList = list;
notifyDataChanged();
}
} }

View File

@ -17,11 +17,7 @@ import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -36,10 +32,10 @@ import java.util.Locale;
public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final TinyDB tinyDb;
private List<org.gitnex.tea4j.v2.models.Repository> reposList; private List<org.gitnex.tea4j.v2.models.Repository> reposList;
private Runnable loadMoreListener; private Runnable loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final TinyDB tinyDb;
public ExploreRepositoriesAdapter(List<org.gitnex.tea4j.v2.models.Repository> dataList, Context ctx) { public ExploreRepositoriesAdapter(List<org.gitnex.tea4j.v2.models.Repository> dataList, Context ctx) {
this.context = ctx; this.context = ctx;
@ -73,17 +69,36 @@ public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerVie
return reposList.size(); return reposList.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
class RepositoriesHolder extends RecyclerView.ViewHolder { class RepositoriesHolder extends RecyclerView.ViewHolder {
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private final ImageView image; private final ImageView image;
private final TextView repoName; private final TextView repoName;
private final TextView orgName; private final TextView orgName;
private final TextView repoDescription; private final TextView repoDescription;
private CheckBox isRepoAdmin;
private final TextView repoStars; private final TextView repoStars;
private final TextView repoLastUpdated; private final TextView repoLastUpdated;
private final View spacerView; private final View spacerView;
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private CheckBox isRepoAdmin;
RepositoriesHolder(View itemView) { RepositoriesHolder(View itemView) {
super(itemView); super(itemView);
@ -126,7 +141,8 @@ public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerVie
if(userRepositories.getAvatarUrl() != null) { if(userRepositories.getAvatarUrl() != null) {
if(!userRepositories.getAvatarUrl().equals("")) { if(!userRepositories.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(userRepositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image); PicassoService.getInstance(context).get().load(userRepositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(image);
} }
else { else {
image.setImageDrawable(drawable); image.setImageDrawable(drawable);
@ -179,24 +195,7 @@ public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerVie
} }
isRepoAdmin.setChecked(userRepositories.getPermissions().isAdmin()); isRepoAdmin.setChecked(userRepositories.getPermissions().isAdmin());
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
} }

View File

@ -4,11 +4,7 @@ import android.content.Context;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Filter; import android.widget.*;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.content.res.AppCompatResources;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
@ -27,35 +23,145 @@ public class FilesAdapter extends RecyclerView.Adapter<FilesAdapter.FilesViewHol
private final List<ContentsResponse> originalFiles = new ArrayList<>(); private final List<ContentsResponse> originalFiles = new ArrayList<>();
private final List<ContentsResponse> alteredFiles = new ArrayList<>(); private final List<ContentsResponse> alteredFiles = new ArrayList<>();
private final Context context; private final Context context;
private final FilesAdapterListener filesListener; private final FilesAdapterListener filesListener;
private final Filter filesFilter = new Filter() {
public interface FilesAdapterListener { @Override
protected FilterResults performFiltering(CharSequence constraint) {
void onClickFile(ContentsResponse file); List<ContentsResponse> filteredList = new ArrayList<>();
}
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(originalFiles);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(ContentsResponse item : originalFiles) {
if(item.getName().toLowerCase().contains(filterPattern) || item.getPath().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
alteredFiles.clear();
alteredFiles.addAll((List) results.values);
notifyDataSetChanged();
}
};
public FilesAdapter(Context ctx, FilesAdapterListener filesListener) {
this.context = ctx;
this.filesListener = filesListener;
}
public List<ContentsResponse> getOriginalFiles() {
return originalFiles;
}
public void notifyOriginalDataSetChanged() {
alteredFiles.clear();
alteredFiles.addAll(originalFiles);
notifyDataSetChanged();
}
@NonNull
@Override
public FilesAdapter.FilesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_files, parent, false);
return new FilesAdapter.FilesViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull FilesAdapter.FilesViewHolder holder, int position) {
ContentsResponse currentItem = alteredFiles.get(position);
holder.file = currentItem;
holder.fileName.setText(currentItem.getName());
switch(currentItem.getType()) {
case "file":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_file));
holder.fileInfo.setVisibility(View.VISIBLE);
holder.fileInfo.setText(FileUtils.byteCountToDisplaySize(Math.toIntExact(currentItem.getSize())));
break;
case "dir":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_directory));
holder.fileInfo.setVisibility(View.GONE);
break;
case "submodule":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_submodule));
holder.fileInfo.setVisibility(View.GONE);
break;
case "symlink":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_symlink));
holder.fileInfo.setVisibility(View.GONE);
break;
default:
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_question));
}
}
@Override
public int getItemCount() {
return alteredFiles.size();
}
@Override
public Filter getFilter() {
return filesFilter;
}
public interface FilesAdapterListener {
void onClickFile(ContentsResponse file);
}
class FilesViewHolder extends RecyclerView.ViewHolder { class FilesViewHolder extends RecyclerView.ViewHolder {
private ContentsResponse file;
private final ImageView fileTypeIs; private final ImageView fileTypeIs;
private final TextView fileName; private final TextView fileName;
private final TextView fileInfo; private final TextView fileInfo;
private ContentsResponse file;
private FilesViewHolder(View itemView) { private FilesViewHolder(View itemView) {
super(itemView); super(itemView);
LinearLayout fileFrame = itemView.findViewById(R.id.fileFrame); LinearLayout fileFrame = itemView.findViewById(R.id.fileFrame);
fileName = itemView.findViewById(R.id.fileName); fileName = itemView.findViewById(R.id.fileName);
fileTypeIs = itemView.findViewById(R.id.fileTypeIs); fileTypeIs = itemView.findViewById(R.id.fileTypeIs);
fileInfo = itemView.findViewById(R.id.fileInfo); fileInfo = itemView.findViewById(R.id.fileInfo);
fileFrame.setOnClickListener(v -> filesListener.onClickFile(file)); fileFrame.setOnClickListener(v -> filesListener.onClickFile(file));
//ImageView filesDropdownMenu = itemView.findViewById(R.id.filesDropdownMenu); //ImageView filesDropdownMenu = itemView.findViewById(R.id.filesDropdownMenu);
/*filesDropdownMenu.setOnClickListener(new View.OnClickListener() { /*filesDropdownMenu.setOnClickListener(new View.OnClickListener() {
@Override @Override
@ -120,117 +226,8 @@ public class FilesAdapter extends RecyclerView.Adapter<FilesAdapter.FilesViewHol
} }
});*/ });*/
} }
}
public FilesAdapter(Context ctx, FilesAdapterListener filesListener) {
this.context = ctx;
this.filesListener = filesListener;
}
public List<ContentsResponse> getOriginalFiles() {
return originalFiles;
} }
public void notifyOriginalDataSetChanged() {
alteredFiles.clear();
alteredFiles.addAll(originalFiles);
notifyDataSetChanged();
}
@NonNull
@Override
public FilesAdapter.FilesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_files, parent, false);
return new FilesAdapter.FilesViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull FilesAdapter.FilesViewHolder holder, int position) {
ContentsResponse currentItem = alteredFiles.get(position);
holder.file = currentItem;
holder.fileName.setText(currentItem.getName());
switch(currentItem.getType()) {
case "file":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_file));
holder.fileInfo.setVisibility(View.VISIBLE);
holder.fileInfo.setText(FileUtils.byteCountToDisplaySize(Math.toIntExact(currentItem.getSize())));
break;
case "dir":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_directory));
holder.fileInfo.setVisibility(View.GONE);
break;
case "submodule":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_submodule));
holder.fileInfo.setVisibility(View.GONE);
break;
case "symlink":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_symlink));
holder.fileInfo.setVisibility(View.GONE);
break;
default:
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_question));
}
}
@Override
public int getItemCount() {
return alteredFiles.size();
}
@Override
public Filter getFilter() {
return filesFilter;
}
private final Filter filesFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<ContentsResponse> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(originalFiles);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (ContentsResponse item : originalFiles) {
if (item.getName().toLowerCase().contains(filterPattern) || item.getPath().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
alteredFiles.clear();
alteredFiles.addAll((List) results.values);
notifyDataSetChanged();
}
};
} }

View File

@ -27,13 +27,7 @@ import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetReplyFragment; import org.mian.gitnex.fragments.BottomSheetReplyFragment;
import org.mian.gitnex.fragments.IssuesFragment; import org.mian.gitnex.fragments.IssuesFragment;
import org.mian.gitnex.helpers.AlertDialogs; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.mian.gitnex.views.ReactionList; import org.mian.gitnex.views.ReactionList;
import org.mian.gitnex.views.ReactionSpinner; import org.mian.gitnex.views.ReactionSpinner;
@ -70,16 +64,131 @@ public class IssueCommentsAdapter extends RecyclerView.Adapter<IssueCommentsAdap
this.issue = issue; this.issue = issue;
} }
class IssueCommentViewHolder extends RecyclerView.ViewHolder { private void updateAdapter(int position) {
private String userLoginId; issuesComments.remove(position);
private Comment issueComment; notifyItemRemoved(position);
notifyItemRangeChanged(position, issuesComments.size());
}
private void deleteIssueComment(final Context ctx, final int commentId, int position) {
Call<Void> call = RetrofitClient.getApiInterface(ctx).issueDeleteComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) commentId);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
switch(response.code()) {
case 204:
updateAdapter(position);
Toasty.success(ctx, ctx.getResources().getString(R.string.deleteCommentSuccess));
IssuesFragment.resumeIssues = true;
break;
case 401:
AlertDialogs.authorizationTokenRevokedDialog(ctx);
break;
case 403:
Toasty.error(ctx, ctx.getString(R.string.authorizeError));
break;
case 404:
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
break;
default:
Toasty.error(ctx, ctx.getString(R.string.genericError));
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(ctx, ctx.getResources().getString(R.string.genericServerResponseError));
}
});
}
@NonNull
@Override
public IssueCommentsAdapter.IssueCommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_issue_comments, parent, false);
return new IssueCommentsAdapter.IssueCommentViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull IssueCommentsAdapter.IssueCommentViewHolder holder, int position) {
String timeFormat = tinyDB.getString("dateFormat", "pretty");
Comment issueComment = issuesComments.get(position);
int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
holder.userLoginId = issueComment.getUser().getLogin();
holder.issueComment = issueComment;
holder.author.setText(issueComment.getUser().getLogin());
PicassoService.getInstance(context).get().load(issueComment.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0))
.resize(AppUtil.getPixelsFromDensity(context, 35), AppUtil.getPixelsFromDensity(context, 35)).centerCrop().into(holder.avatar);
Markdown.render(context, EmojiParser.parseToUnicode(issueComment.getBody()), holder.comment, issue.getRepository());
StringBuilder informationBuilder = null;
if(issueComment.getCreatedAt() != null) {
if(timeFormat.equals("pretty")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "pretty", context));
holder.information.setOnClickListener(v -> TimeHelper.customDateFormatForToastDateFormat(issueComment.getCreatedAt()));
}
else if(timeFormat.equals("normal")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "normal", context));
}
if(!issueComment.getCreatedAt().equals(issueComment.getUpdatedAt())) {
if(informationBuilder != null) {
informationBuilder.append(context.getString(R.string.colorfulBulletSpan)).append(context.getString(R.string.modifiedText));
}
}
}
holder.information.setText(informationBuilder);
Bundle bundle1 = new Bundle();
bundle1.putAll(bundle);
bundle1.putInt("commentId", Math.toIntExact(issueComment.getId()));
ReactionList reactionList = new ReactionList(context, bundle1);
holder.commentReactionBadges.addView(reactionList);
reactionList.setOnReactionAddedListener(() -> {
if(holder.commentReactionBadges.getVisibility() != View.VISIBLE) {
holder.commentReactionBadges.post(() -> holder.commentReactionBadges.setVisibility(View.VISIBLE));
}
});
}
@Override
public int getItemCount() {
return issuesComments.size();
}
class IssueCommentViewHolder extends RecyclerView.ViewHolder {
private final ImageView avatar; private final ImageView avatar;
private final TextView author; private final TextView author;
private final TextView information; private final TextView information;
private final RecyclerView comment; private final RecyclerView comment;
private final LinearLayout commentReactionBadges; private final LinearLayout commentReactionBadges;
private String userLoginId;
private Comment issueComment;
private IssueCommentViewHolder(View view) { private IssueCommentViewHolder(View view) {
@ -237,128 +346,7 @@ public class IssueCommentsAdapter extends RecyclerView.Adapter<IssueCommentsAdap
} }
}, 500); }, 500);
} }
}
private void updateAdapter(int position) {
issuesComments.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, issuesComments.size());
}
private void deleteIssueComment(final Context ctx, final int commentId, int position) {
Call<Void> call = RetrofitClient
.getApiInterface(ctx)
.issueDeleteComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) commentId);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
switch(response.code()) {
case 204:
updateAdapter(position);
Toasty.success(ctx, ctx.getResources().getString(R.string.deleteCommentSuccess));
IssuesFragment.resumeIssues = true;
break;
case 401:
AlertDialogs.authorizationTokenRevokedDialog(ctx);
break;
case 403:
Toasty.error(ctx, ctx.getString(R.string.authorizeError));
break;
case 404:
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
break;
default:
Toasty.error(ctx, ctx.getString(R.string.genericError));
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(ctx, ctx.getResources().getString(R.string.genericServerResponseError));
}
});
}
@NonNull
@Override
public IssueCommentsAdapter.IssueCommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_issue_comments, parent, false);
return new IssueCommentsAdapter.IssueCommentViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull IssueCommentsAdapter.IssueCommentViewHolder holder, int position) {
String timeFormat = tinyDB.getString("dateFormat", "pretty");
Comment issueComment = issuesComments.get(position);
int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
holder.userLoginId = issueComment.getUser().getLogin();
holder.issueComment = issueComment;
holder.author.setText(issueComment.getUser().getLogin());
PicassoService.getInstance(context).get()
.load(issueComment.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(AppUtil.getPixelsFromDensity(context, 35), AppUtil.getPixelsFromDensity(context, 35))
.centerCrop()
.into(holder.avatar);
Markdown.render(context, EmojiParser.parseToUnicode(issueComment.getBody()), holder.comment, issue.getRepository());
StringBuilder informationBuilder = null;
if(issueComment.getCreatedAt() != null) {
if(timeFormat.equals("pretty")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "pretty", context));
holder.information.setOnClickListener(v -> TimeHelper.customDateFormatForToastDateFormat(issueComment.getCreatedAt()));
}
else if(timeFormat.equals("normal")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "normal", context));
}
if(!issueComment.getCreatedAt().equals(issueComment.getUpdatedAt())) {
if(informationBuilder != null) {
informationBuilder.append(context.getString(R.string.colorfulBulletSpan)).append(context.getString(R.string.modifiedText));
}
}
}
holder.information.setText(informationBuilder);
Bundle bundle1 = new Bundle();
bundle1.putAll(bundle);
bundle1.putInt("commentId", Math.toIntExact(issueComment.getId()));
ReactionList reactionList = new ReactionList(context, bundle1);
holder.commentReactionBadges.addView(reactionList);
reactionList.setOnReactionAddedListener(() -> {
if(holder.commentReactionBadges.getVisibility() != View.VISIBLE) {
holder.commentReactionBadges.post(() -> holder.commentReactionBadges.setVisibility(View.VISIBLE));
}
});
}
@Override
public int getItemCount() {
return issuesComments.size();
} }
} }

View File

@ -26,13 +26,7 @@ import org.mian.gitnex.activities.IssueDetailActivity;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -47,10 +41,10 @@ import java.util.Locale;
public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
TinyDB tinyDb;
private List<Issue> issuesList; private List<Issue> issuesList;
private Runnable loadMoreListener; private Runnable loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
TinyDB tinyDb;
public IssuesAdapter(Context ctx, List<Issue> issuesListMain) { public IssuesAdapter(Context ctx, List<Issue> issuesListMain) {
@ -88,9 +82,26 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
return issuesList.size(); return issuesList.size();
} }
class IssuesHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
private Issue issueObject; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
issuesList = list;
notifyDataChanged();
}
class IssuesHolder extends RecyclerView.ViewHolder {
private final ImageView issueAssigneeAvatar; private final ImageView issueAssigneeAvatar;
private final TextView issueTitle; private final TextView issueTitle;
@ -100,6 +111,7 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
private final LinearLayout frameLabels; private final LinearLayout frameLabels;
private final HorizontalScrollView labelsScrollViewDots; private final HorizontalScrollView labelsScrollViewDots;
private final LinearLayout frameLabelsDots; private final LinearLayout frameLabelsDots;
private Issue issueObject;
IssuesHolder(View itemView) { IssuesHolder(View itemView) {
@ -138,12 +150,7 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
int imgRadius = AppUtil.getPixelsFromDensity(context, 3); int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(issue.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(issue.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(issueAssigneeAvatar); .into(issueAssigneeAvatar);
String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + issue.getNumber() + "</font>"; String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + issue.getNumber() + "</font>";
@ -158,8 +165,7 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
frameLabels.setOnClickListener(v -> context.startActivity(intentIssueDetail)); frameLabels.setOnClickListener(v -> context.startActivity(intentIssueDetail));
frameLabelsDots.setOnClickListener(v -> context.startActivity(intentIssueDetail)); frameLabelsDots.setOnClickListener(v -> context.startActivity(intentIssueDetail));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(issue.getLabels() != null) { if(issue.getLabels() != null) {
@ -206,8 +212,9 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
int height = AppUtil.getPixelsFromDensity(context, 20); int height = AppUtil.getPixelsFromDensity(context, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(context, 12); int textSize = AppUtil.getPixelsFromScaledDensity(context, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize).width(LabelWidthCalculator TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18)); .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig()
.buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
frameLabels.addView(labelsView); frameLabels.addView(labelsView);
@ -241,22 +248,4 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
issuesList = list;
notifyDataChanged();
}
} }

View File

@ -29,122 +29,122 @@ import java.util.List;
* @author M M Arif * @author M M Arif
*/ */
public class LabelsAdapter extends RecyclerView.Adapter<LabelsAdapter.LabelsViewHolder> { public class LabelsAdapter extends RecyclerView.Adapter<LabelsAdapter.LabelsViewHolder> {
private final List<Label> labelsList; private final List<Label> labelsList;
private final String type; private final String type;
private final String orgName; private final String orgName;
class LabelsViewHolder extends RecyclerView.ViewHolder { public LabelsAdapter(Context ctx, List<Label> labelsMain, String type, String orgName) {
private Label labels; this.labelsList = labelsMain;
this.type = type;
this.orgName = orgName;
}
private final MaterialCardView labelView; @NonNull
private final ImageView labelIcon; @Override
private final TextView labelName; public LabelsAdapter.LabelsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_labels, parent, false);
return new LabelsAdapter.LabelsViewHolder(v);
}
private LabelsViewHolder(View itemView) { @Override
super(itemView); public void onBindViewHolder(@NonNull LabelsAdapter.LabelsViewHolder holder, int position) {
labelView = itemView.findViewById(R.id.labelView); Label currentItem = labelsList.get(position);
labelIcon = itemView.findViewById(R.id.labelIcon); holder.labels = currentItem;
labelName = itemView.findViewById(R.id.labelName);
ImageView labelsOptionsMenu = itemView.findViewById(R.id.labelsOptionsMenu);
if((type.equals("repo") && !((RepoDetailActivity) itemView.getContext()).repository.getPermissions().isPush()) || String labelColor = currentItem.getColor();
(type.equals("org") && (((OrganizationDetailActivity) itemView.getContext()).permissions == null || !((OrganizationDetailActivity) itemView.getContext()).permissions.isIsOwner()))) { String labelName = currentItem.getName();
labelsOptionsMenu.setVisibility(View.GONE);
}
labelsOptionsMenu.setOnClickListener(v -> {
final Context context = v.getContext(); int color = Color.parseColor("#" + labelColor);
int contrastColor = new ColorInverter().getContrastColor(color);
@SuppressLint("InflateParams") ImageViewCompat.setImageTintList(holder.labelIcon, ColorStateList.valueOf(contrastColor));
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_labels_in_list, null);
TextView labelMenuEdit = view.findViewById(R.id.labelMenuEdit); holder.labelName.setTextColor(contrastColor);
TextView labelMenuDelete = view.findViewById(R.id.labelMenuDelete); holder.labelName.setText(labelName);
TextView bottomSheetHeader = view.findViewById(R.id.bottomSheetHeader); holder.labelView.setCardBackgroundColor(color);
}
bottomSheetHeader.setText(labels.getName()); @Override
BottomSheetDialog dialog = new BottomSheetDialog(context); public int getItemCount() {
dialog.setContentView(view); return labelsList.size();
dialog.show(); }
labelMenuEdit.setOnClickListener(editLabel -> {
Intent intent = new Intent(context, CreateLabelActivity.class);
intent.putExtra("labelId", String.valueOf(labels.getId()));
intent.putExtra("labelTitle", labels.getName());
intent.putExtra("labelColor", labels.getColor());
intent.putExtra("labelAction", "edit");
intent.putExtra("type", type);
intent.putExtra("orgName", orgName);
if(type.equals("repo")) {
intent.putExtra(RepositoryContext.INTENT_EXTRA, ((RepoDetailActivity) itemView.getContext()).repository);
}
context.startActivity(intent);
dialog.dismiss();
});
labelMenuDelete.setOnClickListener(deleteLabel -> {
RepositoryContext repo;
if(type.equals("repo")) {
repo = ((RepoDetailActivity) itemView.getContext()).repository;
} else {
repo = null;
}
AlertDialogs.labelDeleteDialog(context, labels.getName(), String.valueOf(labels.getId()),
type, orgName, repo);
dialog.dismiss();
});
});
}
}
public LabelsAdapter(Context ctx, List<Label> labelsMain, String type, String orgName) {
this.labelsList = labelsMain;
this.type = type;
this.orgName = orgName;
}
@NonNull
@Override
public LabelsAdapter.LabelsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_labels, parent, false);
return new LabelsAdapter.LabelsViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull LabelsAdapter.LabelsViewHolder holder, int position) {
Label currentItem = labelsList.get(position);
holder.labels = currentItem;
String labelColor = currentItem.getColor();
String labelName = currentItem.getName();
int color = Color.parseColor("#" + labelColor);
int contrastColor = new ColorInverter().getContrastColor(color);
ImageViewCompat.setImageTintList(holder.labelIcon, ColorStateList.valueOf(contrastColor));
holder.labelName.setTextColor(contrastColor);
holder.labelName.setText(labelName);
holder.labelView.setCardBackgroundColor(color);
}
@Override
public int getItemCount() {
return labelsList.size();
}
@SuppressLint("NotifyDataSetChanged") @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() { public void notifyDataChanged() {
notifyDataSetChanged(); notifyDataSetChanged();
} }
class LabelsViewHolder extends RecyclerView.ViewHolder {
private final MaterialCardView labelView;
private final ImageView labelIcon;
private final TextView labelName;
private Label labels;
private LabelsViewHolder(View itemView) {
super(itemView);
labelView = itemView.findViewById(R.id.labelView);
labelIcon = itemView.findViewById(R.id.labelIcon);
labelName = itemView.findViewById(R.id.labelName);
ImageView labelsOptionsMenu = itemView.findViewById(R.id.labelsOptionsMenu);
if((type.equals("repo") && !((RepoDetailActivity) itemView.getContext()).repository.getPermissions().isPush()) || (type.equals(
"org") && (((OrganizationDetailActivity) itemView.getContext()).permissions == null || !((OrganizationDetailActivity) itemView.getContext()).permissions.isIsOwner()))) {
labelsOptionsMenu.setVisibility(View.GONE);
}
labelsOptionsMenu.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_labels_in_list, null);
TextView labelMenuEdit = view.findViewById(R.id.labelMenuEdit);
TextView labelMenuDelete = view.findViewById(R.id.labelMenuDelete);
TextView bottomSheetHeader = view.findViewById(R.id.bottomSheetHeader);
bottomSheetHeader.setText(labels.getName());
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
labelMenuEdit.setOnClickListener(editLabel -> {
Intent intent = new Intent(context, CreateLabelActivity.class);
intent.putExtra("labelId", String.valueOf(labels.getId()));
intent.putExtra("labelTitle", labels.getName());
intent.putExtra("labelColor", labels.getColor());
intent.putExtra("labelAction", "edit");
intent.putExtra("type", type);
intent.putExtra("orgName", orgName);
if(type.equals("repo")) {
intent.putExtra(RepositoryContext.INTENT_EXTRA, ((RepoDetailActivity) itemView.getContext()).repository);
}
context.startActivity(intent);
dialog.dismiss();
});
labelMenuDelete.setOnClickListener(deleteLabel -> {
RepositoryContext repo;
if(type.equals("repo")) {
repo = ((RepoDetailActivity) itemView.getContext()).repository;
}
else {
repo = null;
}
AlertDialogs.labelDeleteDialog(context, labels.getName(), String.valueOf(labels.getId()), type, orgName, repo);
dialog.dismiss();
});
});
}
}
} }

View File

@ -21,18 +21,11 @@ import java.util.List;
public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.LabelsViewHolder> { public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.LabelsViewHolder> {
private List<Integer> currentLabelsIds;
private final List<Label> labels; private final List<Label> labels;
private final List<String> labelsStrings = new ArrayList<>(); private final List<String> labelsStrings = new ArrayList<>();
private List<Integer> labelsIds = new ArrayList<>();
private final LabelsListAdapterListener labelsListener; private final LabelsListAdapterListener labelsListener;
private List<Integer> currentLabelsIds;
public interface LabelsListAdapterListener { private List<Integer> labelsIds = new ArrayList<>();
void labelsInterface(List<String> data);
void labelsIdsInterface(List<Integer> data);
}
public LabelsListAdapter(List<Label> labelsMain, LabelsListAdapterListener labelsListener, List<Integer> currentLabelsIds) { public LabelsListAdapter(List<Label> labelsMain, LabelsListAdapterListener labelsListener, List<Integer> currentLabelsIds) {
@ -41,23 +34,6 @@ public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.La
this.currentLabelsIds = currentLabelsIds; this.currentLabelsIds = currentLabelsIds;
} }
static class LabelsViewHolder extends RecyclerView.ViewHolder {
private final CheckBox labelSelection;
private final TextView labelText;
private final ImageView labelColor;
private LabelsViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
labelSelection = itemView.findViewById(R.id.labelSelection);
labelText = itemView.findViewById(R.id.labelText);
labelColor = itemView.findViewById(R.id.labelColor);
}
}
@NonNull @NonNull
@Override @Override
public LabelsListAdapter.LabelsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public LabelsListAdapter.LabelsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -129,4 +105,31 @@ public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.La
currentLabelsIds = list; currentLabelsIds = list;
notifyDataSetChanged(); notifyDataSetChanged();
} }
public interface LabelsListAdapterListener {
void labelsInterface(List<String> data);
void labelsIdsInterface(List<Integer> data);
}
static class LabelsViewHolder extends RecyclerView.ViewHolder {
private final CheckBox labelSelection;
private final TextView labelText;
private final ImageView labelColor;
private LabelsViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
labelSelection = itemView.findViewById(R.id.labelSelection);
labelText = itemView.findViewById(R.id.labelText);
labelColor = itemView.findViewById(R.id.labelColor);
}
}
} }

View File

@ -35,10 +35,10 @@ import java.util.Locale;
public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final RepositoryContext repository;
private List<Milestone> dataList; private List<Milestone> dataList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final RepositoryContext repository;
public MilestonesAdapter(Context ctx, List<Milestone> dataListMain, RepositoryContext repository) { public MilestonesAdapter(Context ctx, List<Milestone> dataListMain, RepositoryContext repository) {
this.repository = repository; this.repository = repository;
@ -64,9 +64,54 @@ public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
((MilestonesAdapter.DataHolder) holder).bindData(dataList.get(position)); ((MilestonesAdapter.DataHolder) holder).bindData(dataList.get(position));
} }
class DataHolder extends RecyclerView.ViewHolder { @Override
public int getItemViewType(int position) {
return position;
}
private Milestone milestones; @Override
public int getItemCount() {
return dataList.size();
}
private void updateAdapter(int position) {
dataList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, dataList.size());
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Milestone> list) {
dataList = list;
notifyDataChanged();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class DataHolder extends RecyclerView.ViewHolder {
private final TextView msTitle; private final TextView msTitle;
private final TextView msDescription; private final TextView msDescription;
@ -74,6 +119,7 @@ public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private final TextView msClosedIssues; private final TextView msClosedIssues;
private final TextView msDueDate; private final TextView msDueDate;
private final ProgressBar msProgress; private final ProgressBar msProgress;
private Milestone milestones;
DataHolder(View itemView) { DataHolder(View itemView) {
@ -211,49 +257,7 @@ public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
msDueDate.setText(context.getString(R.string.milestoneNoDueDate)); msDueDate.setText(context.getString(R.string.milestoneNoDueDate));
} }
} }
} }
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return dataList.size();
}
private void updateAdapter(int position) {
dataList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, dataList.size());
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Milestone> list) {
dataList = list;
notifyDataChanged();
}
} }

View File

@ -28,34 +28,6 @@ public class MostVisitedReposAdapter extends RecyclerView.Adapter<MostVisitedRep
private List<Repository> mostVisitedReposList; private List<Repository> mostVisitedReposList;
static class MostVisitedViewHolder extends RecyclerView.ViewHolder {
private Repository repository;
private final ImageView image;
private final TextView repoName;
private final TextView orgName;
private final TextView mostVisited;
private MostVisitedViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
repoName = itemView.findViewById(R.id.repo_name);
orgName = itemView.findViewById(R.id.org_name);
mostVisited = itemView.findViewById(R.id.most_visited);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
RepositoryContext repositoryContext = new RepositoryContext(repository.getRepositoryOwner(), repository.getRepositoryName(), context);
Intent intent = repositoryContext.getIntent(context, RepoDetailActivity.class);
context.startActivity(intent);
});
}
}
public MostVisitedReposAdapter(List<Repository> reposListMain) { public MostVisitedReposAdapter(List<Repository> reposListMain) {
this.mostVisitedReposList = reposListMain; this.mostVisitedReposList = reposListMain;
} }
@ -100,4 +72,33 @@ public class MostVisitedReposAdapter extends RecyclerView.Adapter<MostVisitedRep
mostVisitedReposList = list; mostVisitedReposList = list;
notifyDataChanged(); notifyDataChanged();
} }
static class MostVisitedViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView repoName;
private final TextView orgName;
private final TextView mostVisited;
private Repository repository;
private MostVisitedViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
repoName = itemView.findViewById(R.id.repo_name);
orgName = itemView.findViewById(R.id.org_name);
mostVisited = itemView.findViewById(R.id.most_visited);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
RepositoryContext repositoryContext = new RepositoryContext(repository.getRepositoryOwner(), repository.getRepositoryName(), context);
Intent intent = repositoryContext.getIntent(context, RepoDetailActivity.class);
context.startActivity(intent);
});
}
}
} }

View File

@ -20,62 +20,57 @@ import java.util.List;
public class MyProfileEmailsAdapter extends RecyclerView.Adapter<MyProfileEmailsAdapter.EmailsViewHolder> { public class MyProfileEmailsAdapter extends RecyclerView.Adapter<MyProfileEmailsAdapter.EmailsViewHolder> {
private final List<Email> emailsList; private final List<Email> emailsList;
private final Context context; private final Context context;
static class EmailsViewHolder extends RecyclerView.ViewHolder { public MyProfileEmailsAdapter(Context ctx, List<Email> emailsListMain) {
this.context = ctx;
this.emailsList = emailsListMain;
}
private final ImageView emailPrimary; @NonNull
private final TextView userEmail; @Override
public MyProfileEmailsAdapter.EmailsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_profile_emails, parent, false);
return new MyProfileEmailsAdapter.EmailsViewHolder(v);
}
private EmailsViewHolder(View itemView) { @Override
super(itemView); public void onBindViewHolder(@NonNull MyProfileEmailsAdapter.EmailsViewHolder holder, int position) {
emailPrimary = itemView.findViewById(R.id.emailPrimary); Email currentItem = emailsList.get(position);
userEmail = itemView.findViewById(R.id.userEmail);
} holder.userEmail.setText(currentItem.getEmail());
}
public MyProfileEmailsAdapter(Context ctx, List<Email> emailsListMain) { if(currentItem.isPrimary()) {
this.context = ctx; TextDrawable drawable = TextDrawable.builder().beginConfig().textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null)).fontSize(36).width(220).height(60).endConfig()
this.emailsList = emailsListMain; .buildRoundRect(context.getResources().getString(R.string.emailTypeText), ResourcesCompat.getColor(context.getResources(), R.color.tooltipBackground, null), 8);
} holder.emailPrimary.setImageDrawable(drawable);
}
else {
holder.emailPrimary.setVisibility(View.GONE);
}
@NonNull }
@Override
public MyProfileEmailsAdapter.EmailsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_profile_emails, parent, false);
return new MyProfileEmailsAdapter.EmailsViewHolder(v);
}
@Override @Override
public void onBindViewHolder(@NonNull MyProfileEmailsAdapter.EmailsViewHolder holder, int position) { public int getItemCount() {
return emailsList.size();
}
Email currentItem = emailsList.get(position); static class EmailsViewHolder extends RecyclerView.ViewHolder {
holder.userEmail.setText(currentItem.getEmail()); private final ImageView emailPrimary;
private final TextView userEmail;
if(currentItem.isPrimary()) { private EmailsViewHolder(View itemView) {
TextDrawable drawable = TextDrawable.builder() super(itemView);
.beginConfig()
.textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null))
.fontSize(36)
.width(220)
.height(60)
.endConfig()
.buildRoundRect(context.getResources().getString(R.string.emailTypeText), ResourcesCompat.getColor(context.getResources(), R.color.tooltipBackground, null), 8);
holder.emailPrimary.setImageDrawable(drawable);
}
else {
holder.emailPrimary.setVisibility(View.GONE);
}
} emailPrimary = itemView.findViewById(R.id.emailPrimary);
userEmail = itemView.findViewById(R.id.userEmail);
@Override }
public int getItemCount() {
return emailsList.size(); }
}
} }

View File

@ -27,9 +27,9 @@ import java.util.List;
public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private List<NotificationThread> notificationThreads;
private final OnMoreClickedListener onMoreClickedListener; private final OnMoreClickedListener onMoreClickedListener;
private final OnNotificationClickedListener onNotificationClickedListener; private final OnNotificationClickedListener onNotificationClickedListener;
private List<NotificationThread> notificationThreads;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
public NotificationsAdapter(Context context, List<NotificationThread> notificationThreads, OnMoreClickedListener onMoreClickedListener, OnNotificationClickedListener onNotificationClickedListener) { public NotificationsAdapter(Context context, List<NotificationThread> notificationThreads, OnMoreClickedListener onMoreClickedListener, OnNotificationClickedListener onNotificationClickedListener) {
@ -65,14 +65,41 @@ public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.View
return notificationThreads.size(); return notificationThreads.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void updateList(List<NotificationThread> list) {
notificationThreads = list;
notifyDataChanged();
}
public interface OnNotificationClickedListener {
void onNotificationClicked(NotificationThread notificationThread);
}
public interface OnMoreClickedListener {
void onMoreClicked(NotificationThread notificationThread);
}
class NotificationsHolder extends RecyclerView.ViewHolder { class NotificationsHolder extends RecyclerView.ViewHolder {
private final LinearLayout frame; private final LinearLayout frame;
private final TextView subject; private final TextView subject;
private final TextView repository; private final TextView repository;
private final ImageView type; private final ImageView type;
private ImageView pinned;
private final ImageView more; private final ImageView more;
private ImageView pinned;
NotificationsHolder(View itemView) { NotificationsHolder(View itemView) {
@ -92,13 +119,15 @@ public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.View
String subjectId = ""; String subjectId = "";
if(StringUtils.containsAny(notificationThread.getSubject().getType().toLowerCase(), "pull", "issue")) { if(StringUtils.containsAny(notificationThread.getSubject().getType().toLowerCase(), "pull", "issue")) {
subjectId = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + url.substring(url.lastIndexOf("/") + 1) + "</font>"; subjectId = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + url.substring(
url.lastIndexOf("/") + 1) + "</font>";
} }
subject.setText(HtmlCompat.fromHtml(subjectId + " " + notificationThread.getSubject().getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY)); subject.setText(HtmlCompat.fromHtml(subjectId + " " + notificationThread.getSubject().getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY));
if(!notificationThread.getSubject().getType().equalsIgnoreCase("repository")) { if(!notificationThread.getSubject().getType().equalsIgnoreCase("repository")) {
repository.setText(notificationThread.getRepository().getFullName()); repository.setText(notificationThread.getRepository().getFullName());
} else { }
else {
repository.setVisibility(View.GONE); repository.setVisibility(View.GONE);
pinned.setVisibility(View.GONE); pinned.setVisibility(View.GONE);
pinned = itemView.findViewById(R.id.pinnedVertical); pinned = itemView.findViewById(R.id.pinnedVertical);
@ -151,28 +180,7 @@ public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.View
more.setOnClickListener(v -> onMoreClickedListener.onMoreClicked(notificationThread)); more.setOnClickListener(v -> onMoreClickedListener.onMoreClicked(notificationThread));
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void updateList(List<NotificationThread> list) {
notificationThreads = list;
notifyDataChanged();
}
public interface OnNotificationClickedListener {
void onNotificationClicked(NotificationThread notificationThread);
}
public interface OnMoreClickedListener {
void onMoreClicked(NotificationThread notificationThread);
}
} }

View File

@ -28,121 +28,10 @@ import java.util.List;
public class OrganizationsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { public class OrganizationsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final Context context; private final Context context;
private List<Organization> orgList;
private final List<Organization> orgListFull; private final List<Organization> orgListFull;
private List<Organization> orgList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
public OrganizationsListAdapter(Context ctx, List<Organization> orgListMain) {
this.context = ctx;
this.orgList = orgListMain;
orgListFull = new ArrayList<>(orgList);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
return new OrganizationsListAdapter.OrgHolder(inflater.inflate(R.layout.list_organizations, parent, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
((OrganizationsListAdapter.OrgHolder) holder).bindData(orgList.get(position));
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return orgList.size();
}
class OrgHolder extends RecyclerView.ViewHolder {
private Organization userOrganizations;
private final ImageView image;
private final TextView orgName;
private final TextView orgDescription;
OrgHolder(View itemView) {
super(itemView);
orgName = itemView.findViewById(R.id.orgName);
orgDescription = itemView.findViewById(R.id.orgDescription);
image = itemView.findViewById(R.id.imageAvatar);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
Intent intent = new Intent(context, OrganizationDetailActivity.class);
intent.putExtra("orgName", userOrganizations.getUsername());
context.startActivity(intent);
});
}
void bindData(Organization org) {
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
this.userOrganizations = org;
orgName.setText(org.getUsername());
PicassoService.getInstance(context).get().load(org.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image);
if(!org.getDescription().equals("")) {
orgDescription.setVisibility(View.VISIBLE);
orgDescription.setText(org.getDescription());
}
else {
orgDescription.setVisibility(View.GONE);
}
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public abstract static class OnLoadMoreListener {
protected abstract void onLoadMore();
public void onLoadFinished() {}
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Organization> list) {
orgList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return orgFilter;
}
private final Filter orgFilter = new Filter() { private final Filter orgFilter = new Filter() {
@Override @Override
@ -179,4 +68,117 @@ public class OrganizationsListAdapter extends RecyclerView.Adapter<RecyclerView.
notifyDataChanged(); notifyDataChanged();
} }
}; };
public OrganizationsListAdapter(Context ctx, List<Organization> orgListMain) {
this.context = ctx;
this.orgList = orgListMain;
orgListFull = new ArrayList<>(orgList);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
return new OrganizationsListAdapter.OrgHolder(inflater.inflate(R.layout.list_organizations, parent, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
((OrganizationsListAdapter.OrgHolder) holder).bindData(orgList.get(position));
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return orgList.size();
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Organization> list) {
orgList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return orgFilter;
}
public abstract static class OnLoadMoreListener {
protected abstract void onLoadMore();
public void onLoadFinished() {
}
}
class OrgHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView orgName;
private final TextView orgDescription;
private Organization userOrganizations;
OrgHolder(View itemView) {
super(itemView);
orgName = itemView.findViewById(R.id.orgName);
orgDescription = itemView.findViewById(R.id.orgDescription);
image = itemView.findViewById(R.id.imageAvatar);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
Intent intent = new Intent(context, OrganizationDetailActivity.class);
intent.putExtra("orgName", userOrganizations.getUsername());
context.startActivity(intent);
});
}
void bindData(Organization org) {
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
this.userOrganizations = org;
orgName.setText(org.getUsername());
PicassoService.getInstance(context).get().load(org.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image);
if(!org.getDescription().equals("")) {
orgDescription.setVisibility(View.VISIBLE);
orgDescription.setText(org.getDescription());
}
else {
orgDescription.setVisibility(View.GONE);
}
}
}
} }

View File

@ -26,13 +26,7 @@ import org.mian.gitnex.activities.IssueDetailActivity;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -80,9 +74,26 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
return prList.size(); return prList.size();
} }
class PullRequestsHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
private PullRequest pullRequestObject; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<PullRequest> list) {
prList = list;
notifyDataChanged();
}
class PullRequestsHolder extends RecyclerView.ViewHolder {
private final ImageView assigneeAvatar; private final ImageView assigneeAvatar;
private final TextView prTitle; private final TextView prTitle;
@ -92,6 +103,7 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
private final LinearLayout frameLabels; private final LinearLayout frameLabels;
private final HorizontalScrollView labelsScrollViewDots; private final HorizontalScrollView labelsScrollViewDots;
private final LinearLayout frameLabelsDots; private final LinearLayout frameLabelsDots;
private PullRequest pullRequestObject;
PullRequestsHolder(View itemView) { PullRequestsHolder(View itemView) {
@ -139,18 +151,12 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
String timeFormat = tinyDb.getString("dateFormat", "pretty"); String timeFormat = tinyDb.getString("dateFormat", "pretty");
int imgRadius = AppUtil.getPixelsFromDensity(context, 3); int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(pullRequest.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(pullRequest.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(this.assigneeAvatar); .into(this.assigneeAvatar);
this.pullRequestObject = pullRequest; this.pullRequestObject = pullRequest;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(pullRequest.getLabels() != null) { if(pullRequest.getLabels() != null) {
@ -197,8 +203,9 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
int height = AppUtil.getPixelsFromDensity(context, 20); int height = AppUtil.getPixelsFromDensity(context, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(context, 12); int textSize = AppUtil.getPixelsFromScaledDensity(context, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize).width(LabelWidthCalculator TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18)); .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig()
.buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
frameLabels.addView(labelsView); frameLabels.addView(labelsView);
@ -220,24 +227,7 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
this.prCreatedTime.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(pullRequest.getCreatedAt()), context)); this.prCreatedTime.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(pullRequest.getCreatedAt()), context));
} }
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<PullRequest> list) {
prList = list;
notifyDataChanged();
}
} }

View File

@ -39,16 +39,13 @@ public class ReactionAuthorsAdapter extends RecyclerView.Adapter<ReactionAuthors
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User userInfo = userInfos.get(position); User userInfo = userInfos.get(position);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(userInfo.getAvatarUrl()).placeholder(R.drawable.loader_animated).resize(240, 240).transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 6), 0))
.load(userInfo.getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.resize(240, 240)
.transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 6), 0))
.centerCrop().into(holder.authorAvatar); .centerCrop().into(holder.authorAvatar);
if(userInfo.getFullName() == null || userInfo.getFullName().isEmpty()) { if(userInfo.getFullName() == null || userInfo.getFullName().isEmpty()) {
holder.authorFullName.setVisibility(View.GONE); holder.authorFullName.setVisibility(View.GONE);
} else { }
else {
holder.authorFullName.setText(userInfo.getFullName()); holder.authorFullName.setText(userInfo.getFullName());
holder.authorFullName.setVisibility(View.VISIBLE); holder.authorFullName.setVisibility(View.VISIBLE);
} }
@ -75,6 +72,7 @@ public class ReactionAuthorsAdapter extends RecyclerView.Adapter<ReactionAuthors
authorFullName = itemView.findViewById(R.id.authorFullName); authorFullName = itemView.findViewById(R.id.authorFullName);
authorLogin = itemView.findViewById(R.id.authorLogin); authorLogin = itemView.findViewById(R.id.authorLogin);
} }
} }
} }

View File

@ -23,13 +23,7 @@ import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.FragmentReleasesBinding; import org.mian.gitnex.databinding.FragmentReleasesBinding;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.structs.FragmentRefreshListener; import org.mian.gitnex.structs.FragmentRefreshListener;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -43,192 +37,118 @@ import retrofit2.Response;
public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.ReleasesViewHolder> { public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.ReleasesViewHolder> {
private List<Release> releasesList; private final Context context;
private final Context context;
private final String repoOwner; private final String repoOwner;
private final String repoName; private final String repoName;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private final FragmentRefreshListener startDownload; private final FragmentRefreshListener startDownload;
private final FragmentReleasesBinding fragmentReleasesBinding; private final FragmentReleasesBinding fragmentReleasesBinding;
private List<Release> releasesList;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
protected class ReleasesViewHolder extends RecyclerView.ViewHolder { public ReleasesAdapter(Context ctx, List<Release> releasesMain, FragmentRefreshListener startDownload, String repoOwner, String repoName, FragmentReleasesBinding fragmentReleasesBinding) {
this.context = ctx;
this.releasesList = releasesMain;
this.startDownload = startDownload;
this.repoOwner = repoOwner;
this.repoName = repoName;
this.fragmentReleasesBinding = fragmentReleasesBinding;
}
private Release releases; @NonNull
@Override
public ReleasesAdapter.ReleasesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_releases, parent, false);
return new ReleasesAdapter.ReleasesViewHolder(v);
}
private final TextView releaseType; @Override
private final TextView releaseName; public void onBindViewHolder(@NonNull ReleasesAdapter.ReleasesViewHolder holder, int position) {
private final ImageView authorAvatar;
private final TextView authorName;
private final TextView releaseTag;
private final TextView releaseDate;
private final TextView releaseBodyContent;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final RecyclerView downloadList;
private final ImageView optionsMenu;
private ReleasesViewHolder(View itemView) { final TinyDB tinyDb = TinyDB.getInstance(context);
final Locale locale = context.getResources().getConfiguration().locale;
final String timeFormat = tinyDb.getString("dateFormat", "pretty");
int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
super(itemView); Release currentItem = releasesList.get(position);
holder.releases = currentItem;
releaseType = itemView.findViewById(R.id.releaseType); holder.releaseName.setText(currentItem.getName());
releaseName = itemView.findViewById(R.id.releaseName);
authorAvatar = itemView.findViewById(R.id.authorAvatar);
authorName = itemView.findViewById(R.id.authorName);
releaseTag = itemView.findViewById(R.id.releaseTag);
TextView releaseCommitSha = itemView.findViewById(R.id.releaseCommitSha);
releaseDate = itemView.findViewById(R.id.releaseDate);
releaseBodyContent = itemView.findViewById(R.id.releaseBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
downloadList = itemView.findViewById(R.id.downloadList);
optionsMenu = itemView.findViewById(R.id.releasesOptionsMenu);
downloadList.setHasFixedSize(true); if(currentItem.isPrerelease()) {
downloadList.setLayoutManager(new LinearLayoutManager(itemView.getContext())); holder.releaseType.setBackgroundResource(R.drawable.shape_pre_release);
holder.releaseType.setText(R.string.releaseTypePre);
}
else if(currentItem.isDraft()) {
holder.releaseType.setBackgroundResource(R.drawable.shape_draft_release);
holder.releaseType.setText(R.string.releaseDraftText);
}
else {
holder.releaseType.setBackgroundResource(R.drawable.shape_stable_release);
holder.releaseType.setText(R.string.releaseTypeStable);
}
new Handler().postDelayed(() -> { if(currentItem.getAuthor().getAvatarUrl() != null) {
if(!AppUtil.checkGhostUsers(releases.getAuthor().getLogin())) { PicassoService.getInstance(context).get().load(currentItem.getAuthor().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(holder.authorAvatar);
}
authorAvatar.setOnClickListener(loginId -> { holder.authorName.setText(context.getResources().getString(R.string.releasePublishedBy, currentItem.getAuthor().getLogin()));
Context context = loginId.getContext();
Intent intent = new Intent(context, ProfileActivity.class); if(currentItem.getTagName() != null) {
intent.putExtra("username", releases.getAuthor().getLogin()); holder.releaseTag.setText(currentItem.getTagName());
context.startActivity(intent); }
});
}
}, 500);
optionsMenu.setOnClickListener(v -> { if(currentItem.getPublishedAt() != null) {
final Context context = v.getContext(); holder.releaseDate.setText(TimeHelper.formatTime(currentItem.getPublishedAt(), locale, timeFormat, context));
}
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_release_in_list, itemView.findViewById(android.R.id.content), false); if(timeFormat.equals("pretty")) {
holder.releaseDate.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(currentItem.getPublishedAt()), context));
}
TextView deleteRelease = view.findViewById(R.id.deleteRelease); if(!currentItem.getBody().equals("")) {
Markdown.render(context, currentItem.getBody(), holder.releaseBodyContent);
}
else {
holder.releaseBodyContent.setText(R.string.noReleaseBodyContent);
}
BottomSheetDialog dialog = new BottomSheetDialog(context); holder.downloadCopyFrame.setOnClickListener(v -> {
dialog.setContentView(view);
dialog.show();
deleteRelease.setOnClickListener(v1 -> { if(holder.downloads.getVisibility() == View.GONE) {
deleteRelease(context, releases.getName(), releases.getId(), repoOwner, repoName, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
public ReleasesAdapter(Context ctx, List<Release> releasesMain, FragmentRefreshListener startDownload, String repoOwner, String repoName, FragmentReleasesBinding fragmentReleasesBinding) { holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_down);
this.context = ctx; holder.downloads.setVisibility(View.VISIBLE);
this.releasesList = releasesMain; }
this.startDownload = startDownload; else {
this.repoOwner = repoOwner;
this.repoName = repoName;
this.fragmentReleasesBinding = fragmentReleasesBinding;
}
@NonNull holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_right);
@Override holder.downloads.setVisibility(View.GONE);
public ReleasesAdapter.ReleasesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { }
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_releases, parent, false);
return new ReleasesAdapter.ReleasesViewHolder(v);
}
@Override });
public void onBindViewHolder(@NonNull ReleasesAdapter.ReleasesViewHolder holder, int position) {
final TinyDB tinyDb = TinyDB.getInstance(context); holder.releaseZipDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getZipballUrl()));
final Locale locale = context.getResources().getConfiguration().locale; holder.releaseTarDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getTarballUrl()));
final String timeFormat = tinyDb.getString("dateFormat", "pretty");
int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
Release currentItem = releasesList.get(position); ReleasesDownloadsAdapter adapter = new ReleasesDownloadsAdapter(currentItem.getAssets(), startDownload);
holder.releases = currentItem; holder.downloadList.setAdapter(adapter);
holder.releaseName.setText(currentItem.getName()); if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
if(currentItem.isPrerelease()) { if(!((RepoDetailActivity) context).repository.getPermissions().isPush()) {
holder.releaseType.setBackgroundResource(R.drawable.shape_pre_release); holder.optionsMenu.setVisibility(View.GONE);
holder.releaseType.setText(R.string.releaseTypePre); }
} }
else if(currentItem.isDraft()) {
holder.releaseType.setBackgroundResource(R.drawable.shape_draft_release);
holder.releaseType.setText(R.string.releaseDraftText);
}
else {
holder.releaseType.setBackgroundResource(R.drawable.shape_stable_release);
holder.releaseType.setText(R.string.releaseTypeStable);
}
if(currentItem.getAuthor().getAvatarUrl() != null) { @Override
PicassoService.getInstance(context).get().load(currentItem.getAuthor().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.authorAvatar); public int getItemCount() {
} return releasesList.size();
}
holder.authorName.setText(context.getResources().getString(R.string.releasePublishedBy, currentItem.getAuthor().getLogin()));
if(currentItem.getTagName() != null) {
holder.releaseTag.setText(currentItem.getTagName());
}
if(currentItem.getPublishedAt() != null) {
holder.releaseDate.setText(TimeHelper.formatTime(currentItem.getPublishedAt(), locale, timeFormat, context));
}
if(timeFormat.equals("pretty")) {
holder.releaseDate.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(currentItem.getPublishedAt()), context));
}
if(!currentItem.getBody().equals("")) {
Markdown.render(context, currentItem.getBody(), holder.releaseBodyContent);
}
else {
holder.releaseBodyContent.setText(R.string.noReleaseBodyContent);
}
holder.downloadCopyFrame.setOnClickListener(v -> {
if(holder.downloads.getVisibility() == View.GONE) {
holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_down);
holder.downloads.setVisibility(View.VISIBLE);
}
else {
holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_right);
holder.downloads.setVisibility(View.GONE);
}
});
holder.releaseZipDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getZipballUrl()));
holder.releaseTarDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getTarballUrl()));
ReleasesDownloadsAdapter adapter = new ReleasesDownloadsAdapter(currentItem.getAssets(), startDownload);
holder.downloadList.setAdapter(adapter);
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
if(!((RepoDetailActivity) context).repository.getPermissions().isPush()) {
holder.optionsMenu.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return releasesList.size();
}
public void setMoreDataAvailable(boolean moreDataAvailable) { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable; isMoreDataAvailable = moreDataAvailable;
@ -244,12 +164,6 @@ public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.Releas
loadMoreListener.onLoadFinished(); loadMoreListener.onLoadFinished();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) { public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener; this.loadMoreListener = loadMoreListener;
} }
@ -269,36 +183,116 @@ public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.Releas
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Material3_Dialog_Alert); MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Material3_Dialog_Alert);
materialAlertDialogBuilder.setTitle(String.format(context.getString(R.string.deleteGenericTitle), releaseName)) materialAlertDialogBuilder.setTitle(String.format(context.getString(R.string.deleteGenericTitle), releaseName)).setMessage(R.string.deleteReleaseConfirmation)
.setMessage(R.string.deleteReleaseConfirmation) .setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient.getApiInterface(context).repoDeleteRelease(owner, repo, releaseId).enqueue(new Callback<>() {
.setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient
.getApiInterface(context).repoDeleteRelease(owner, repo, releaseId).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
updateAdapter(position); updateAdapter(position);
Toasty.success(context, context.getString(R.string.releaseDeleted)); Toasty.success(context, context.getString(R.string.releaseDeleted));
MainActivity.reloadRepos = true; MainActivity.reloadRepos = true;
if(getItemCount() == 0) { if(getItemCount() == 0) {
fragmentReleasesBinding.noDataReleases.setVisibility(View.VISIBLE); fragmentReleasesBinding.noDataReleases.setVisibility(View.VISIBLE);
}
}
else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError));
}
else {
Toasty.error(context, context.getString(R.string.genericError));
} }
} }
else if(response.code() == 403) {
@Override Toasty.error(context, context.getString(R.string.authorizeError));
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { }
else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
})) }
.setNeutralButton(R.string.cancelButton, null).show();
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getString(R.string.genericError));
}
})).setNeutralButton(R.string.cancelButton, null).show();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
protected class ReleasesViewHolder extends RecyclerView.ViewHolder {
private final TextView releaseType;
private final TextView releaseName;
private final ImageView authorAvatar;
private final TextView authorName;
private final TextView releaseTag;
private final TextView releaseDate;
private final TextView releaseBodyContent;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final RecyclerView downloadList;
private final ImageView optionsMenu;
private Release releases;
private ReleasesViewHolder(View itemView) {
super(itemView);
releaseType = itemView.findViewById(R.id.releaseType);
releaseName = itemView.findViewById(R.id.releaseName);
authorAvatar = itemView.findViewById(R.id.authorAvatar);
authorName = itemView.findViewById(R.id.authorName);
releaseTag = itemView.findViewById(R.id.releaseTag);
TextView releaseCommitSha = itemView.findViewById(R.id.releaseCommitSha);
releaseDate = itemView.findViewById(R.id.releaseDate);
releaseBodyContent = itemView.findViewById(R.id.releaseBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
downloadList = itemView.findViewById(R.id.downloadList);
optionsMenu = itemView.findViewById(R.id.releasesOptionsMenu);
downloadList.setHasFixedSize(true);
downloadList.setLayoutManager(new LinearLayoutManager(itemView.getContext()));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(releases.getAuthor().getLogin())) {
authorAvatar.setOnClickListener(loginId -> {
Context context = loginId.getContext();
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", releases.getAuthor().getLogin());
context.startActivity(intent);
});
}
}, 500);
optionsMenu.setOnClickListener(v -> {
final Context context = v.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_release_in_list, itemView.findViewById(android.R.id.content), false);
TextView deleteRelease = view.findViewById(R.id.deleteRelease);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
deleteRelease.setOnClickListener(v1 -> {
deleteRelease(context, releases.getName(), releases.getId(), repoOwner, repoName, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
} }

View File

@ -20,17 +20,6 @@ public class ReleasesDownloadsAdapter extends RecyclerView.Adapter<ReleasesDownl
private final List<Attachment> releasesDownloadsList; private final List<Attachment> releasesDownloadsList;
private final FragmentRefreshListener startDownload; private final FragmentRefreshListener startDownload;
static class ReleasesDownloadsViewHolder extends RecyclerView.ViewHolder {
private final TextView downloadName;
private ReleasesDownloadsViewHolder(View itemView) {
super(itemView);
downloadName = itemView.findViewById(R.id.downloadName);
}
}
ReleasesDownloadsAdapter(List<Attachment> releasesDownloadsMain, FragmentRefreshListener startDownload) { ReleasesDownloadsAdapter(List<Attachment> releasesDownloadsMain, FragmentRefreshListener startDownload) {
this.releasesDownloadsList = releasesDownloadsMain; this.releasesDownloadsList = releasesDownloadsMain;
@ -62,4 +51,16 @@ public class ReleasesDownloadsAdapter extends RecyclerView.Adapter<ReleasesDownl
return releasesDownloadsList.size(); return releasesDownloadsList.size();
} }
static class ReleasesDownloadsViewHolder extends RecyclerView.ViewHolder {
private final TextView downloadName;
private ReleasesDownloadsViewHolder(View itemView) {
super(itemView);
downloadName = itemView.findViewById(R.id.downloadName);
}
}
} }

View File

@ -17,11 +17,7 @@ import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -74,17 +70,35 @@ public class RepoForksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
return forksList.size(); return forksList.size();
} }
class ForksHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
private org.gitnex.tea4j.v2.models.Repository userRepositories; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
forksList = list;
notifyDataChanged();
}
class ForksHolder extends RecyclerView.ViewHolder {
private final ImageView image; private final ImageView image;
private final TextView repoName; private final TextView repoName;
private final TextView orgName; private final TextView orgName;
private final TextView repoDescription; private final TextView repoDescription;
private CheckBox isRepoAdmin;
private final TextView repoStars; private final TextView repoStars;
private final TextView repoLastUpdated; private final TextView repoLastUpdated;
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private CheckBox isRepoAdmin;
ForksHolder(View itemView) { ForksHolder(View itemView) {
@ -115,13 +129,12 @@ public class RepoForksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
int color = generator.getColor(forksModel.getName()); int color = generator.getColor(forksModel.getName());
String firstCharacter = String.valueOf(forksModel.getFullName().charAt(0)); String firstCharacter = String.valueOf(forksModel.getFullName().charAt(0));
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28) TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28).endConfig().buildRoundRect(firstCharacter, color, 3);
.endConfig().buildRoundRect(firstCharacter, color, 3);
if(forksModel.getAvatarUrl() != null) { if(forksModel.getAvatarUrl() != null) {
if(!forksModel.getAvatarUrl().equals("")) { if(!forksModel.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(forksModel.getAvatarUrl()).placeholder(R.drawable.loader_animated) PicassoService.getInstance(context).get().load(forksModel.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image); .into(image);
} }
else { else {
image.setImageDrawable(drawable); image.setImageDrawable(drawable);
@ -183,24 +196,7 @@ public class RepoForksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
}); });
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
forksList = list;
notifyDataChanged();
}
} }

View File

@ -7,11 +7,7 @@ import android.graphics.Typeface;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CheckBox; import android.widget.*;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable; import com.amulyakhare.textdrawable.TextDrawable;
@ -19,11 +15,7 @@ import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -39,12 +31,46 @@ import java.util.Locale;
public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final Context context; private final Context context;
private List<org.gitnex.tea4j.v2.models.Repository> reposList;
private final List<org.gitnex.tea4j.v2.models.Repository> reposListFull; private final List<org.gitnex.tea4j.v2.models.Repository> reposListFull;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private final TinyDB tinyDb; private final TinyDB tinyDb;
public boolean isUserOrg = false; public boolean isUserOrg = false;
private List<org.gitnex.tea4j.v2.models.Repository> reposList;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private final Filter reposFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<org.gitnex.tea4j.v2.models.Repository> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(reposListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(org.gitnex.tea4j.v2.models.Repository item : reposListFull) {
if(item.getFullName().toLowerCase().contains(filterPattern) || item.getDescription().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
reposList.clear();
reposList.addAll((List) results.values);
notifyDataChanged();
}
};
public ReposListAdapter(List<org.gitnex.tea4j.v2.models.Repository> reposListMain, Context ctx) { public ReposListAdapter(List<org.gitnex.tea4j.v2.models.Repository> reposListMain, Context ctx) {
this.context = ctx; this.context = ctx;
@ -80,18 +106,53 @@ public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
return reposList.size(); return reposList.size();
} }
class ReposHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
private org.gitnex.tea4j.v2.models.Repository userRepositories; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return reposFilter;
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class ReposHolder extends RecyclerView.ViewHolder {
private final ImageView image; private final ImageView image;
private final TextView repoName; private final TextView repoName;
private final TextView orgName; private final TextView orgName;
private final TextView repoDescription; private final TextView repoDescription;
private CheckBox isRepoAdmin;
private final TextView repoStars; private final TextView repoStars;
private final TextView repoLastUpdated; private final TextView repoLastUpdated;
private final View spacerView; private final View spacerView;
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private CheckBox isRepoAdmin;
ReposHolder(View itemView) { ReposHolder(View itemView) {
@ -137,7 +198,8 @@ public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
if(repositories.getAvatarUrl() != null) { if(repositories.getAvatarUrl() != null) {
if(!repositories.getAvatarUrl().equals("")) { if(!repositories.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(repositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image); PicassoService.getInstance(context).get().load(repositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(image);
} }
else { else {
image.setImageDrawable(drawable); image.setImageDrawable(drawable);
@ -190,73 +252,7 @@ public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
isRepoAdmin.setChecked(repositories.getPermissions().isAdmin()); isRepoAdmin.setChecked(repositories.getPermissions().isAdmin());
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return reposFilter;
}
private final Filter reposFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<org.gitnex.tea4j.v2.models.Repository> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(reposListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(org.gitnex.tea4j.v2.models.Repository item : reposListFull) {
if(item.getFullName().toLowerCase().contains(filterPattern) || item.getDescription().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
reposList.clear();
reposList.addAll((List) results.values);
notifyDataChanged();
}
};
} }

View File

@ -31,122 +31,77 @@ import retrofit2.Response;
public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder> { public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder> {
private List<Tag> tags; private final Context context;
private final Context context; private final String repo;
private final String repo; private final String owner;
private final String owner;
private final FragmentRefreshListener startDownload; private final FragmentRefreshListener startDownload;
private final FragmentReleasesBinding fragmentReleasesBinding; private final FragmentReleasesBinding fragmentReleasesBinding;
private List<Tag> tags;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
protected class TagsViewHolder extends RecyclerView.ViewHolder { public TagsAdapter(Context ctx, List<Tag> releasesMain, String repoOwner, String repoName, FragmentRefreshListener startDownload, FragmentReleasesBinding fragmentReleasesBinding) {
this.context = ctx;
private Tag tagsHolder; this.tags = releasesMain;
private final TextView tagName; owner = repoOwner;
private final TextView tagBody; repo = repoName;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final ImageView options;
private TagsViewHolder(View itemView) {
super(itemView);
tagName = itemView.findViewById(R.id.tagName);
tagBody = itemView.findViewById(R.id.tagBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
options = itemView.findViewById(R.id.tagsOptionsMenu);
options.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams")
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_tag_in_list, null);
TextView delete = view.findViewById(R.id.tagMenuDelete);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
delete.setOnClickListener(v1 -> {
tagDeleteDialog(context, tagsHolder.getName(), owner, repo, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
public TagsAdapter(Context ctx, List<Tag> releasesMain, String repoOwner, String repoName, FragmentRefreshListener startDownload, FragmentReleasesBinding fragmentReleasesBinding) {
this.context = ctx;
this.tags = releasesMain;
owner = repoOwner;
repo = repoName;
this.startDownload = startDownload; this.startDownload = startDownload;
this.fragmentReleasesBinding = fragmentReleasesBinding; this.fragmentReleasesBinding = fragmentReleasesBinding;
} }
@NonNull @NonNull
@Override @Override
public TagsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public TagsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_tags, parent, false); View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_tags, parent, false);
return new TagsViewHolder(v); return new TagsViewHolder(v);
} }
@Override @Override
public void onBindViewHolder(@NonNull TagsViewHolder holder, int position) { public void onBindViewHolder(@NonNull TagsViewHolder holder, int position) {
Tag currentItem = tags.get(position); Tag currentItem = tags.get(position);
holder.tagsHolder = currentItem; holder.tagsHolder = currentItem;
holder.tagName.setText(currentItem.getName()); holder.tagName.setText(currentItem.getName());
if(!currentItem.getMessage().equals("")) { if(!currentItem.getMessage().equals("")) {
Markdown.render(context, currentItem.getMessage(), holder.tagBody); Markdown.render(context, currentItem.getMessage(), holder.tagBody);
} }
else { else {
holder.tagBody.setVisibility(View.GONE); holder.tagBody.setVisibility(View.GONE);
} }
holder.downloadCopyFrame.setOnClickListener(v -> { holder.downloadCopyFrame.setOnClickListener(v -> {
if(holder.downloads.getVisibility() == View.GONE) { if(holder.downloads.getVisibility() == View.GONE) {
holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_down); holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_down);
holder.downloads.setVisibility(View.VISIBLE); holder.downloads.setVisibility(View.VISIBLE);
} }
else { else {
holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_right); holder.downloadDropdownIcon.setImageResource(R.drawable.ic_chevron_right);
holder.downloads.setVisibility(View.GONE); holder.downloads.setVisibility(View.GONE);
} }
}); });
if(!((RepoDetailActivity) context).repository.getPermissions().isPush()) { if(!((RepoDetailActivity) context).repository.getPermissions().isPush()) {
holder.options.setVisibility(View.GONE); holder.options.setVisibility(View.GONE);
} }
holder.releaseZipDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getZipballUrl())); holder.releaseZipDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getZipballUrl()));
holder.releaseTarDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getTarballUrl())); holder.releaseTarDownloadFrame.setOnClickListener(v -> startDownload.onRefresh(currentItem.getTarballUrl()));
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) { if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true; isLoading = true;
loadMoreListener.onLoadMore(); loadMoreListener.onLoadMore();
} }
} }
@Override @Override
public int getItemCount() { public int getItemCount() {
return tags.size(); return tags.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable; isMoreDataAvailable = moreDataAvailable;
@ -162,11 +117,6 @@ public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder
loadMoreListener.onLoadFinished(); loadMoreListener.onLoadFinished();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) { public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener; this.loadMoreListener = loadMoreListener;
} }
@ -184,43 +134,92 @@ public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder
private void tagDeleteDialog(final Context context, final String tagName, final String owner, final String repo, int position) { private void tagDeleteDialog(final Context context, final String tagName, final String owner, final String repo, int position) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context).setTitle(String.format(context.getString(R.string.deleteGenericTitle), tagName))
.setTitle(String.format(context.getString(R.string.deleteGenericTitle), tagName)) .setMessage(R.string.deleteTagConfirmation).setCancelable(false).setNeutralButton(R.string.cancelButton, null)
.setMessage(R.string.deleteTagConfirmation) .setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient.getApiInterface(context).repoDeleteTag(owner, repo, tagName).enqueue(new Callback<>() {
.setCancelable(false)
.setNeutralButton(R.string.cancelButton, null)
.setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient
.getApiInterface(context).repoDeleteTag(owner, repo, tagName).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
updateAdapter(position); updateAdapter(position);
Toasty.success(context, context.getString(R.string.tagDeleted)); Toasty.success(context, context.getString(R.string.tagDeleted));
if(getItemCount() == 0) { if(getItemCount() == 0) {
fragmentReleasesBinding.noDataReleases.setVisibility(View.VISIBLE); fragmentReleasesBinding.noDataReleases.setVisibility(View.VISIBLE);
}
}
else if(response.code() == 403) {
Toasty.error(context, context.getString(R.string.authorizeError));
}
else if(response.code() == 409) {
Toasty.error(context, context.getString(R.string.tagDeleteError));
}
else {
Toasty.error(context, context.getString(R.string.genericError));
} }
} }
else if(response.code() == 403) {
@Override Toasty.error(context, context.getString(R.string.authorizeError));
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) { }
else if(response.code() == 409) {
Toasty.error(context, context.getString(R.string.tagDeleteError));
}
else {
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
})) }
.setNeutralButton(R.string.cancelButton, null);
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(context, context.getString(R.string.genericError));
}
})).setNeutralButton(R.string.cancelButton, null);
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
protected class TagsViewHolder extends RecyclerView.ViewHolder {
private final TextView tagName;
private final TextView tagBody;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final ImageView options;
private Tag tagsHolder;
private TagsViewHolder(View itemView) {
super(itemView);
tagName = itemView.findViewById(R.id.tagName);
tagBody = itemView.findViewById(R.id.tagBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
options = itemView.findViewById(R.id.tagsOptionsMenu);
options.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_tag_in_list, null);
TextView delete = view.findViewById(R.id.tagMenuDelete);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
delete.setOnClickListener(v1 -> {
tagDeleteDialog(context, tagsHolder.getName(), owner, repo, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
} }

View File

@ -39,11 +39,7 @@ public class TeamMembersByOrgPreviewAdapter extends RecyclerView.Adapter<TeamMem
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User userInfo = userData.get(position); User userInfo = userData.get(position);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(userInfo.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 3), 0)).resize(120, 120)
.load(userInfo.getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 3), 0))
.resize(120, 120)
.centerCrop().into(holder.avatar); .centerCrop().into(holder.avatar);
} }
@ -60,5 +56,7 @@ public class TeamMembersByOrgPreviewAdapter extends RecyclerView.Adapter<TeamMem
super(itemView); super(itemView);
avatar = itemView.findViewById(R.id.avatar); avatar = itemView.findViewById(R.id.avatar);
} }
} }
} }

View File

@ -49,13 +49,70 @@ public class TeamRepositoriesAdapter extends RecyclerView.Adapter<TeamRepositori
reposArr = new ArrayList<>(); reposArr = new ArrayList<>();
} }
class TeamReposViewHolder extends RecyclerView.ViewHolder { @NonNull
@Override
public TeamRepositoriesAdapter.TeamReposViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_collaborators_search, parent, false);
return new TeamRepositoriesAdapter.TeamReposViewHolder(v);
}
private Repository repoInfo; @Override
public void onBindViewHolder(@NonNull final TeamRepositoriesAdapter.TeamReposViewHolder holder, int position) {
Repository currentItem = reposList.get(position);
holder.repoInfo = currentItem;
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
holder.name.setText(currentItem.getName());
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28).endConfig()
.buildRoundRect(String.valueOf(currentItem.getFullName().charAt(0)), ColorGenerator.Companion.getMATERIAL().getColor(currentItem.getName()), 14);
if(currentItem.getAvatarUrl() != null && !currentItem.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(holder.repoAvatar);
}
else {
holder.repoAvatar.setImageDrawable(drawable);
}
}
@Override
public int getItemCount() {
return reposList.size();
}
private void getTeamRepos() {
if(getItemCount() > 0) {
Call<List<Repository>> call = RetrofitClient.getApiInterface(context).orgListTeamRepos((long) teamId, 1, 50);
call.enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<List<Repository>> call, @NonNull Response<List<Repository>> response) {
if(response.code() == 200) {
for(int i = 0; i < Objects.requireNonNull(response.body()).size(); i++) {
reposArr.addAll(response.body());
}
}
}
@Override
public void onFailure(@NonNull Call<List<Repository>> call, @NonNull Throwable t) {
}
});
}
}
class TeamReposViewHolder extends RecyclerView.ViewHolder {
private final ImageView repoAvatar; private final ImageView repoAvatar;
private final TextView name; private final TextView name;
private final ImageView addRepoButtonAdd; private final ImageView addRepoButtonAdd;
private Repository repoInfo;
private TeamReposViewHolder(View itemView) { private TeamReposViewHolder(View itemView) {
@ -89,69 +146,9 @@ public class TeamRepositoriesAdapter extends RecyclerView.Adapter<TeamRepositori
addRepoButtonAdd.setOnClickListener(v -> AlertDialogs.addRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName)); addRepoButtonAdd.setOnClickListener(v -> AlertDialogs.addRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName));
addRepoButtonRemove.setOnClickListener(v -> addRepoButtonRemove.setOnClickListener(v -> AlertDialogs.removeRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName));
AlertDialogs.removeRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName));
} }
} }
@NonNull
@Override
public TeamRepositoriesAdapter.TeamReposViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_collaborators_search, parent, false);
return new TeamRepositoriesAdapter.TeamReposViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull final TeamRepositoriesAdapter.TeamReposViewHolder holder, int position) {
Repository currentItem = reposList.get(position);
holder.repoInfo = currentItem;
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
holder.name.setText(currentItem.getName());
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28)
.endConfig().buildRoundRect(String.valueOf(currentItem.getFullName().charAt(0)), ColorGenerator.Companion.getMATERIAL().getColor(currentItem.getName()), 14);
if(currentItem.getAvatarUrl() != null && !currentItem.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.repoAvatar);
}
else {
holder.repoAvatar.setImageDrawable(drawable);
}
}
@Override
public int getItemCount() {
return reposList.size();
}
private void getTeamRepos() {
if(getItemCount() > 0) {
Call<List<Repository>> call = RetrofitClient
.getApiInterface(context)
.orgListTeamRepos((long) teamId, 1, 50);
call.enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<List<Repository>> call, @NonNull Response<List<Repository>> response) {
if(response.code() == 200) {
for(int i = 0; i < Objects.requireNonNull(response.body()).size(); i++) {
reposArr.addAll(response.body());
}
}
}
@Override
public void onFailure(@NonNull Call<List<Repository>> call, @NonNull Throwable t) {
}
});
}
}
} }

Some files were not shown because too many files have changed in this diff Show More