wip on creating new file. still has to do branches section for old and new.

This commit is contained in:
M M Arif 2019-09-18 13:25:49 +05:00
parent c38d249571
commit 8d1b47de8e
9 changed files with 482 additions and 5 deletions

View File

@ -1,9 +1,32 @@
package org.mian.gitnex.activities;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.gson.JsonElement;
import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.helpers.AlertDialogs;
import org.mian.gitnex.helpers.Authorization;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.models.Branches;
import org.mian.gitnex.models.NewFile;
import org.mian.gitnex.util.AppUtil;
import org.mian.gitnex.util.TinyDB;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
/**
* Author M M Arif
@ -11,12 +34,267 @@ import org.mian.gitnex.R;
public class NewFileActivity extends AppCompatActivity {
public ImageView closeActivity;
private View.OnClickListener onClickListener;
private Button newFileCreate;
private EditText newFileName;
private EditText newFileContent;
private EditText newFileBranchName;
private EditText newFileCommitMessage;
private Spinner newFileBranchesSpinner;
final Context ctx = this;
List<Branches> branchesList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_file);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
boolean connToInternet = AppUtil.haveNetworkConnection(getApplicationContext());
TinyDB tinyDb = new TinyDB(getApplicationContext());
final String instanceUrl = tinyDb.getString("instanceUrl");
final String loginUid = tinyDb.getString("loginUid");
String repoFullName = tinyDb.getString("repoFullName");
String[] parts = repoFullName.split("/");
final String repoOwner = parts[0];
final String repoName = parts[1];
final String instanceToken = "token " + tinyDb.getString(loginUid + "-token");
closeActivity = findViewById(R.id.close);
newFileName = findViewById(R.id.newFileName);
newFileContent = findViewById(R.id.newFileContent);
newFileBranchName = findViewById(R.id.newFileBranchName);
newFileCommitMessage = findViewById(R.id.newFileCommitMessage);
initCloseListener();
closeActivity.setOnClickListener(onClickListener);
newFileCreate = findViewById(R.id.newFileCreate);
initCloseListener();
closeActivity.setOnClickListener(onClickListener);
newFileBranchesSpinner = findViewById(R.id.newFileBranchesSpinner);
newFileBranchesSpinner.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getBranches(instanceUrl, instanceToken, repoOwner, repoName, loginUid);
disableProcessButton();
if(!connToInternet) {
newFileCreate.setEnabled(false);
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius( 8 );
shape.setColor(getResources().getColor(R.color.hintColor));
newFileCreate.setBackground(shape);
} else {
newFileCreate.setOnClickListener(createFileListener);
}
}
private View.OnClickListener createFileListener = new View.OnClickListener() {
public void onClick(View v) {
processNewFile();
}
};
private void processNewFile() {
boolean connToInternet = AppUtil.haveNetworkConnection(getApplicationContext());
AppUtil appUtil = new AppUtil();
TinyDB tinyDb = new TinyDB(getApplicationContext());
final String instanceUrl = tinyDb.getString("instanceUrl");
final String loginUid = tinyDb.getString("loginUid");
final String instanceToken = "token " + tinyDb.getString(loginUid + "-token");
String repoFullName = tinyDb.getString("repoFullName");
String[] parts = repoFullName.split("/");
final String repoOwner = parts[0];
final String repoName = parts[1];
String newFileName_ = newFileName.getText().toString();
String newFileContent_ = newFileContent.getText().toString();
String newFileBranchName_ = newFileBranchName.getText().toString();
String newFileCommitMessage_ = newFileCommitMessage.getText().toString();
Branches bModel = (Branches) newFileBranchesSpinner.getSelectedItem();
Log.i("bModel", bModel.toString());
if(!connToInternet) {
Toasty.info(getApplicationContext(), getResources().getString(R.string.checkNetConnection));
return;
}
if(newFileName_.equals("") || newFileContent_.equals("") || newFileCommitMessage_.equals("")) {
Toasty.info(getApplicationContext(), getString(R.string.newFileRequiredFields));
return;
}
if(!appUtil.checkStringsWithDash(newFileBranchName_)) {
Toasty.info(getApplicationContext(), getString(R.string.newFileInvalidBranchName));
return;
}
if(appUtil.charactersLength(newFileCommitMessage_) > 255) {
Toasty.info(getApplicationContext(), getString(R.string.newFileCommitMessageError));
}
else {
disableProcessButton();
//Log.i("base64", appUtil.encodeBase64(newFileContent_));
createNewFile(instanceUrl, Authorization.returnAuthentication(getApplicationContext(), loginUid, instanceToken), repoOwner, repoName, newFileName_, appUtil.encodeBase64(newFileContent_), newFileBranchName_, newFileCommitMessage_);
}
}
private void createNewFile(final String instanceUrl, final String token, String repoOwner, String repoName, String fileName, String fileContent, String fileBranchName, String fileCommitMessage) {
NewFile createNewFileJsonStr = new NewFile(fileContent, fileCommitMessage, fileBranchName);
Call<JsonElement> call = RetrofitClient
.getInstance(instanceUrl)
.getApiInterface()
.createNewFile(token, repoOwner, repoName, fileName, createNewFileJsonStr);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(@NonNull Call<JsonElement> call, @NonNull retrofit2.Response<JsonElement> response) {
if(response.code() == 201) {
enableProcessButton();
Toasty.info(getApplicationContext(), getString(R.string.newFileSuccessMessage));
finish();
}
else if(response.code() == 401) {
enableProcessButton();
AlertDialogs.authorizationTokenRevokedDialog(ctx, getResources().getString(R.string.alertDialogTokenRevokedTitle),
getResources().getString(R.string.alertDialogTokenRevokedMessage),
getResources().getString(R.string.alertDialogTokenRevokedCopyNegativeButton),
getResources().getString(R.string.alertDialogTokenRevokedCopyPositiveButton));
}
else {
if(response.code() == 404) {
enableProcessButton();
Toasty.info(getApplicationContext(), getString(R.string.apiNotFound));
}
else {
enableProcessButton();
Toasty.info(getApplicationContext(), getString(R.string.orgCreatedError));
}
}
}
@Override
public void onFailure(@NonNull Call<JsonElement> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString());
enableProcessButton();
}
});
}
private void getBranches(String instanceUrl, String instanceToken, String repoOwner, String repoName, String loginUid) {
Call<List<Branches>> call = RetrofitClient
.getInstance(instanceUrl)
.getApiInterface()
.getBranches(Authorization.returnAuthentication(getApplicationContext(), loginUid, instanceToken), repoOwner, repoName);
call.enqueue(new Callback<List<Branches>>() {
@Override
public void onResponse(@NonNull Call<List<Branches>> call, @NonNull retrofit2.Response<List<Branches>> response) {
if(response.isSuccessful()) {
if(response.code() == 200) {
List<Branches> branchesList_ = response.body();
branchesList.add(new Branches("No branch"));
assert branchesList_ != null;
if(branchesList_.size() > 0) {
for (int i = 0; i < branchesList_.size(); i++) {
Branches data = new Branches(
branchesList_.get(i).getName()
);
branchesList.add(data);
}
}
ArrayAdapter<Branches> adapter = new ArrayAdapter<>(getApplicationContext(),
R.layout.spinner_item, branchesList);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
newFileBranchesSpinner.setAdapter(adapter);
enableProcessButton();
}
}
}
@Override
public void onFailure(@NonNull Call<List<Branches>> call, @NonNull Throwable t) {
Log.e("onFailure", t.toString());
}
});
}
private void initCloseListener() {
onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
};
}
private void disableProcessButton() {
newFileCreate.setEnabled(false);
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius( 8 );
shape.setColor(getResources().getColor(R.color.hintColor));
newFileCreate.setBackground(shape);
}
private void enableProcessButton() {
newFileCreate.setEnabled(true);
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius( 8 );
shape.setColor(getResources().getColor(R.color.btnBackground));
newFileCreate.setBackground(shape);
}
}

View File

@ -3,6 +3,7 @@ package org.mian.gitnex.interfaces;
import com.google.gson.JsonElement;
import org.mian.gitnex.models.AddEmail;
import org.mian.gitnex.models.Branches;
import org.mian.gitnex.models.NewFile;
import org.mian.gitnex.models.UpdateIssueAssignee;
import org.mian.gitnex.models.UpdateIssueState;
import org.mian.gitnex.models.Collaborators;
@ -210,4 +211,7 @@ public interface ApiInterface {
@GET("repos/{owner}/{repo}/subscribers") // get all repo watchers
Call<List<UserInfo>> getRepoWatchers(@Header("Authorization") String token, @Path("owner") String ownerName, @Path("repo") String repoName);
@POST("repos/{owner}/{repo}/contents/{file}") // create new file
Call<JsonElement> createNewFile(@Header("Authorization") String token, @Path("owner") String ownerName, @Path("repo") String repoName, @Path("file") String fileName, @Body NewFile jsonStr);
}

View File

@ -0,0 +1,98 @@
package org.mian.gitnex.models;
/**
* Author M M Arif
*/
public class NewFile {
private String branch;
private String content;
private String message;
private String new_branch;
private authorObject author;
private committerObject committer;
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getContents() {
return content;
}
public void setContents(String contents) {
this.content = contents;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNew_branch() {
return new_branch;
}
public void setNew_branch(String new_branch) {
this.new_branch = new_branch;
}
public class authorObject {
private String email;
private String name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class committerObject {
private String email;
private String name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public NewFile(String content, String message, String new_branch) {
this.content = content;
this.message = message;
this.new_branch = new_branch;
}
}

View File

@ -7,9 +7,11 @@ import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import android.util.DisplayMetrics;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Locale;
@ -77,6 +79,10 @@ public class AppUtil {
return str.matches("^[\\w.-]+$");
}
public Boolean checkStringsWithDash(String str) { // [a-zA-Z0-9-_. ]
return str.matches("^[\\w-]+$");
}
public Boolean checkIntegers(String str) {
return str.matches("\\d+");
}
@ -180,4 +186,28 @@ public class AppUtil {
}
public String encodeBase64(String str) {
String base64Str = str;
if(!str.equals("")) {
byte[] data = str.getBytes(StandardCharsets.UTF_8);
base64Str = Base64.encodeToString(data, Base64.DEFAULT);
}
return base64Str;
}
public String decodeBase64(String str) {
String base64Str = str;
if(!str.equals("")) {
byte[] data = Base64.decode(base64Str, Base64.DEFAULT);
base64Str = new String(data, StandardCharsets.UTF_8);
}
return base64Str;
}
}

View File

@ -115,6 +115,25 @@
android:inputType="textCapSentences|textMultiLine"
android:textColorHighlight="@color/colorWhite"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/newFileOldBranches"
android:textColor="@color/colorWhite"
android:textSize="16sp"
android:layout_marginTop="10dp"/>
<Spinner
android:id="@+id/newFileBranchesSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingStart="5dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
@ -178,6 +197,7 @@
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:width="140dp"
android:text="@string/newFileButtonCopy"
android:background="@drawable/shape_buttons"
android:textColor="@color/btnTextColor" />

View File

@ -408,6 +408,19 @@
<string name="zipArchiveDownloadReleasesTab">Zip Archive</string>
<string name="tarArchiveDownloadReleasesTab">Tar Archive</string>
<!-- new file -->
<string name="newFileNameTintCopy">File Name</string>
<string name="newFileBranchTintCopy">Branch Name</string>
<string name="newFileContentTintCopy">File Content</string>
<string name="newFileButtonCopy">Create New File</string>
<string name="newFileNameHintMessage">with folder: app/test.md</string>
<string name="newFileMessageTintCopy">Commit Message</string>
<string name="newFileInvalidBranchName">Invalid branch name, may only contain &#8211;, a&#8211;z, 0&#8211;9</string>
<string name="newFileCommitMessageError">Commit message is too long</string>
<string name="newFileSuccessMessage">New file created</string>
<string name="newFileOldBranches">Current Branches</string>
<string name="newFileRequiredFields">Fields like filename, contents and commit message are required.</string>
<!-- generic copy -->
<string name="okButton">OK</string>
<string name="doneButton">Fertig</string>
@ -427,6 +440,7 @@
<string name="descriptionText">Beschreibung</string>
<string name="websiteText">Website</string>
<string name="locationText">Standort</string>
<string name="characters255Limit">Max 255 characters</string>
<!-- generic copy -->
</resources>

View File

@ -408,6 +408,19 @@
<string name="zipArchiveDownloadReleasesTab">Zip Archive</string>
<string name="tarArchiveDownloadReleasesTab">Tar Archive</string>
<!-- new file -->
<string name="newFileNameTintCopy">File Name</string>
<string name="newFileBranchTintCopy">Branch Name</string>
<string name="newFileContentTintCopy">File Content</string>
<string name="newFileButtonCopy">Create New File</string>
<string name="newFileNameHintMessage">with folder: app/test.md</string>
<string name="newFileMessageTintCopy">Commit Message</string>
<string name="newFileInvalidBranchName">Invalid branch name, may only contain &#8211;, a&#8211;z, 0&#8211;9</string>
<string name="newFileCommitMessageError">Commit message is too long</string>
<string name="newFileSuccessMessage">New file created</string>
<string name="newFileOldBranches">Current Branches</string>
<string name="newFileRequiredFields">Fields like filename, contents and commit message are required.</string>
<!-- generic copy -->
<string name="okButton">OK</string>
<string name="doneButton">Done</string>
@ -428,6 +441,7 @@
<string name="websiteText">Website</string>
<string name="locationText">Location</string>
<string name="openWebRepo">Ouvrir avec le Browser</string>
<string name="characters255Limit">Max 255 characters</string>
<!-- generic copy -->
</resources>

View File

@ -408,6 +408,19 @@
<string name="zipArchiveDownloadReleasesTab">Zip Archive</string>
<string name="tarArchiveDownloadReleasesTab">Tar Archive</string>
<!-- new file -->
<string name="newFileNameTintCopy">File Name</string>
<string name="newFileBranchTintCopy">Branch Name</string>
<string name="newFileContentTintCopy">File Content</string>
<string name="newFileButtonCopy">Create New File</string>
<string name="newFileNameHintMessage">with folder: app/test.md</string>
<string name="newFileMessageTintCopy">Commit Message</string>
<string name="newFileInvalidBranchName">Invalid branch name, may only contain &#8211;, a&#8211;z, 0&#8211;9</string>
<string name="newFileCommitMessageError">Commit message is too long</string>
<string name="newFileSuccessMessage">New file created</string>
<string name="newFileOldBranches">Current Branches</string>
<string name="newFileRequiredFields">Fields like filename, contents and commit message are required.</string>
<!-- generic copy -->
<string name="okButton">OK</string>
<string name="doneButton">Готово</string>
@ -428,6 +441,7 @@
<string name="websiteText">Веб-сайт</string>
<string name="locationText">Место расположения</string>
<string name="openWebRepo">Открыть с помощью браузера</string>
<string name="characters255Limit">Max 255 characters</string>
<!-- generic copy -->
</resources>

View File

@ -99,7 +99,6 @@
<string name="emptyFieldPassword">Password is required</string>
<string name="checkNetConnection">Cannot access network, please check your Internet connection</string>
<string name="emptyFields">All fields are required</string>
<string name="repoNameErrorEmpty">Repository name is empty</string>
<string name="repoNameErrorInvalid">Repository name is not valid. [a&#8211;z A&#8211;Z 0&#8211;9 &#8211; _]</string>
@ -449,11 +448,16 @@
<!-- new file -->
<string name="newFileNameTintCopy">File Name</string>
<string name="newFileBranchTintCopy">Branch Name</string>
<string name="newFileBranchTintCopy">New Branch Name</string>
<string name="newFileContentTintCopy">File Content</string>
<string name="newFileButtonCopy">Create New File</string>
<string name="newFileNameHintMessage">with folder: app/test.md</string>
<string name="newFileMessageTintCopy">Commit Message</string>
<string name="newFileInvalidBranchName">Invalid branch name, may only contain &#8211;, a&#8211;z, 0&#8211;9</string>
<string name="newFileCommitMessageError">Commit message is too long</string>
<string name="newFileSuccessMessage">New file created</string>
<string name="newFileOldBranches">Current Branches</string>
<string name="newFileRequiredFields">Fields like filename, contents and commit message are required.</string>
<!-- generic copy -->
<string name="okButton">OK</string>
@ -478,6 +482,7 @@
<string name="websiteText">Website</string>
<string name="locationText">Location</string>
<string name="characters255Limit">Max 255 characters</string>
<string name="emptyFields">All fields are required</string>
<!-- generic copy -->
</resources>