diff options
Diffstat (limited to 'app/src/main/java/org/bienvenidoainternet')
14 files changed, 2268 insertions, 0 deletions
diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/AppCompatPreferenceActivity.java b/app/src/main/java/org/bienvenidoainternet/baiparser/AppCompatPreferenceActivity.java new file mode 100644 index 0000000..e89a927 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/AppCompatPreferenceActivity.java @@ -0,0 +1,109 @@ +package org.bienvenidoainternet.baiparser; + +import android.content.res.Configuration; +import android.os.Bundle; +import android.preference.PreferenceActivity; +import android.support.annotation.LayoutRes; +import android.support.annotation.Nullable; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AppCompatDelegate; +import android.support.v7.widget.Toolbar; +import android.view.MenuInflater; +import android.view.View; +import android.view.ViewGroup; + +/** + * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls + * to be used with AppCompat. + */ +public abstract class AppCompatPreferenceActivity extends PreferenceActivity { + + private AppCompatDelegate mDelegate; + + @Override + protected void onCreate(Bundle savedInstanceState) { + getDelegate().installViewFactory(); + getDelegate().onCreate(savedInstanceState); + super.onCreate(savedInstanceState); + } + + @Override + protected void onPostCreate(Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + getDelegate().onPostCreate(savedInstanceState); + } + + public ActionBar getSupportActionBar() { + return getDelegate().getSupportActionBar(); + } + + public void setSupportActionBar(@Nullable Toolbar toolbar) { + getDelegate().setSupportActionBar(toolbar); + } + + @Override + public MenuInflater getMenuInflater() { + return getDelegate().getMenuInflater(); + } + + @Override + public void setContentView(@LayoutRes int layoutResID) { + getDelegate().setContentView(layoutResID); + } + + @Override + public void setContentView(View view) { + getDelegate().setContentView(view); + } + + @Override + public void setContentView(View view, ViewGroup.LayoutParams params) { + getDelegate().setContentView(view, params); + } + + @Override + public void addContentView(View view, ViewGroup.LayoutParams params) { + getDelegate().addContentView(view, params); + } + + @Override + protected void onPostResume() { + super.onPostResume(); + getDelegate().onPostResume(); + } + + @Override + protected void onTitleChanged(CharSequence title, int color) { + super.onTitleChanged(title, color); + getDelegate().setTitle(title); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + getDelegate().onConfigurationChanged(newConfig); + } + + @Override + protected void onStop() { + super.onStop(); + getDelegate().onStop(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + getDelegate().onDestroy(); + } + + public void invalidateOptionsMenu() { + getDelegate().invalidateOptionsMenu(); + } + + private AppCompatDelegate getDelegate() { + if (mDelegate == null) { + mDelegate = AppCompatDelegate.create(this, null); + } + return mDelegate; + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/CustomFragmentPagerAdapter.java b/app/src/main/java/org/bienvenidoainternet/baiparser/CustomFragmentPagerAdapter.java new file mode 100644 index 0000000..40052b8 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/CustomFragmentPagerAdapter.java @@ -0,0 +1,53 @@ +package org.bienvenidoainternet.baiparser; + +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentPagerAdapter; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Renard on 04-03-2016. + */ + +public class CustomFragmentPagerAdapter extends FragmentPagerAdapter { + + // List of fragments which are going to set in the view pager widget + List<Fragment> fragments; + + /** + * Constructor + * + * @param fm + * interface for interacting with Fragment objects inside of an + * Activity + */ + public CustomFragmentPagerAdapter(FragmentManager fm) { + super(fm); + this.fragments = new ArrayList<Fragment>(); + } + + /** + * Add a new fragment in the list. + * + * @param fragment + * a new fragment + */ + public void addFragment(Fragment fragment) { + this.fragments.add(fragment); + } + + @Override + public Fragment getItem(int arg0) { + return this.fragments.get(arg0); + } + + @Override + public int getCount() { + return this.fragments.size(); + } + + + +}
\ No newline at end of file diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/MainActivity.java b/app/src/main/java/org/bienvenidoainternet/baiparser/MainActivity.java new file mode 100644 index 0000000..050cfe9 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/MainActivity.java @@ -0,0 +1,478 @@ +package org.bienvenidoainternet.baiparser; + +import android.app.Activity; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.NavigationView; +import android.support.design.widget.Snackbar; +import android.support.v4.view.GravityCompat; +import android.support.v4.view.ViewPager; +import android.support.v4.widget.DrawerLayout; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.SubMenu; +import android.view.View; +import android.widget.BaseAdapter; +import android.widget.HeaderViewListAdapter; +import android.widget.ListView; +import android.widget.Toast; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.koushikdutta.async.future.FutureCallback; +import com.koushikdutta.ion.Ion; + +import org.bienvenidoainternet.baiparser.structure.Board; +import org.bienvenidoainternet.baiparser.structure.BoardItem; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Random; + +import layout.fragmentThreadList; + +public class MainActivity extends AppCompatActivity + implements NavigationView.OnNavigationItemSelectedListener, fragmentThreadList.OnFragmentInteractionListener { + + public static final float CURRENT_VERSION = 1.5F; + private ViewPager pager; // variable del ViewPager + CustomFragmentPagerAdapter pagerAdapter; // Adaptador del ViewPager + NavigationView navigationView; + DrawerLayout drawer; + FloatingActionButton fab; + public ThemeManager themeManager; + fragmentThreadList childFragment; // Segunda página del ViewPager, se muestra un solo hilo (selecionado del catálogo) + fragmentThreadList mainFragment; // Primera página del ViewPager, se muestra una lista de hilos. (catálogo) +// fragmentThreadList recentFragment; + Toolbar toolbar = null; + public int currentThemeId = 0, themeId = 0; // Id del recurso, Id del tema + public ArrayList<Board> boardList = new ArrayList<>(); + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putInt("currentThemeId", currentThemeId); + outState.putInt("themeId", themeId); + outState.putParcelableArrayList("boardList", boardList); + if (getSupportFragmentManager().getFragments() != null) { + if (getSupportFragmentManager().getFragments().size() != 0) { + try { + getSupportFragmentManager().putFragment(outState, "mainFragment", mainFragment); + getSupportFragmentManager().putFragment(outState, "childFragment", childFragment); + }catch (Exception e){ + e.printStackTrace(); + } + } + } + } + + public int getCurrentThemeId() { + return currentThemeId; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (savedInstanceState != null) { + currentThemeId = savedInstanceState.getInt("currentThemeId"); + boardList = savedInstanceState.getParcelableArrayList("boardList"); + } + SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); + themeId = Integer.valueOf(settings.getString("pref_theme", "1")); + + if (settings.getString("pref_password", "").isEmpty()){ + SharedPreferences.Editor edit = settings.edit(); + edit.putString("pref_password", makePassword()); + edit.commit(); + } + + switch (themeId) { + case 1: + currentThemeId = R.style.AppTheme_NoActionBar; + break; + case 2: + currentThemeId = R.style.AppTheme_Dark; + break; + case 3: + currentThemeId = R.style.AppTheme_HeadLine; + setTheme(R.style.AppTheme_HeadLine_Activity); + break; + case 4: + currentThemeId = R.style.AppTheme_Black; + setTheme(R.style.AppTheme_Black_Activity); + break; + } + + themeManager = new ThemeManager(this); + Log.d("ThemeManager", "isDarkTheme: " + themeManager.isDarkTheme()); + + setContentView(R.layout.activity_main); + toolbar = (Toolbar) findViewById(R.id.toolbar); + toolbar.setTitle("Bievenido a internet"); + this.setSupportActionBar(toolbar); + + + fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (childFragment.currentBoard != null) { + if (!childFragment.boardItems.isEmpty()) { + try { + Intent in = new Intent(getApplicationContext(), ResponseActivity.class); + Bundle b = new Bundle(); + b.putParcelable("theReply", childFragment.boardItems.get(0)); + b.putParcelable("theBoard", childFragment.currentBoard); + in.putExtras(b); + startActivity(in); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + }); + fab.setVisibility(View.GONE); + + drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( + this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); + drawer.setDrawerListener(toggle); + toggle.syncState(); + + navigationView = (NavigationView) findViewById(R.id.nav_view); + navigationView.setNavigationItemSelectedListener(this); + + if (savedInstanceState != null) { + mainFragment = (fragmentThreadList) getSupportFragmentManager().getFragment(savedInstanceState, "mainFragment"); + childFragment = (fragmentThreadList) getSupportFragmentManager().getFragment(savedInstanceState, "childFragment"); +// recentFragment = (fragmentThreadList) getSupportFragmentManager().getFragment(savedInstanceState, "recentFragment"); + } else { + mainFragment = fragmentThreadList.newInstance(true, null, null); + childFragment = fragmentThreadList.newInstance(false, null, null); +// recentFragment = fragmentThreadList.newInstance(false, null, -1); + } + + this.pager = (ViewPager) findViewById(R.id.pager); + this.pagerAdapter = new CustomFragmentPagerAdapter(getSupportFragmentManager()); + pagerAdapter.addFragment(mainFragment); + pagerAdapter.addFragment(childFragment); +// pagerAdapter.addFragment(recentFragment); + this.pager.setAdapter(pagerAdapter); + + pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + + } + + @Override + public void onPageSelected(int position) { + if (position == 0){ + if (mainFragment.currentBoard != null) { + toolbar.setTitle("Catálogo"); + toolbar.setSubtitle(mainFragment.currentBoard.getBoardName()); + } + if (mainFragment.getMode()){ + toolbar.setTitle("Post recientes"); + toolbar.setSubtitle(""); + } + fab.setVisibility(View.INVISIBLE); + }else if (position == 1){ + if (childFragment.currentBoard != null) { + toolbar.setTitle(childFragment.currentBoard.getBoardName()); + if (!childFragment.boardItems.isEmpty()){ + toolbar.setSubtitle(childFragment.boardItems.get(0).getSubject()); + } + fab.setVisibility(View.VISIBLE); + } + } + } + + @Override + public void onPageScrollStateChanged(int state) { + + } + }); + + if (boardList.isEmpty()){ + getBoardList(); + }else{ + Menu menu = navigationView.getMenu(); + SubMenu sub = menu.addSubMenu("Lista de Boards"); + for (Board b : boardList) { + sub.add(b.getBoardName()); + } + refreshNavigator(); + } + + // TODO: Aplicar tema al navigator +// navigationView.setBackgroundColor(themeManager.getPrimaryDarkColor()); + checkForUpdates(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == 1) { + if(resultCode == Activity.RESULT_OK){ + boolean result = data.getBooleanExtra("result", false); + if (result){ + this.recreate(); + } + } + } + } + + @Override + public void onBackPressed() { + if (this.pager.getCurrentItem() == 0) { + super.onBackPressed(); + } else { + this.pager.setCurrentItem(this.pager.getCurrentItem() - 1); + return; + } + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } else { + super.onBackPressed(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + switch (id) { + case R.id.action_exit: + System.exit(0); + break; + case R.id.action_refresh: + if (pager.getCurrentItem() == 0) { + mainFragment.refresh(); + } else { + childFragment.refresh(); + } + if (boardList.isEmpty()){ + getBoardList(); + } + break; + case R.id.action_settings: + Intent in2 = new Intent(getApplicationContext(), SettingsActivity.class); + startActivityForResult(in2, 1); + break; + case R.id.action_to_bot: + if (pager.getCurrentItem() == 0) { + mainFragment.scrollToBotton(); + } else { + childFragment.scrollToBotton(); + } + break; + case R.id.action_to_top: + if (pager.getCurrentItem() == 0) { + mainFragment.scrollToTop(); + } else { + childFragment.scrollToTop(); + } + break; + case R.id.action_update: + Intent updater = new Intent(getApplicationContext(), UpdaterActivity.class); + startActivity(updater); + } + return super.onOptionsItemSelected(item); + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public boolean onNavigationItemSelected(MenuItem item) { + // Handle navigation view item clicks here. + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + drawer.closeDrawer(GravityCompat.START); + int id = item.getItemId(); + toolbar.setSubtitle(item.getTitle()); + if (id == R.id.nav_recent_post){ + toolbar.setTitle("Post recientes"); + toolbar.setSubtitle(""); + pager.setCurrentItem(0); + mainFragment.loadRecentPost(); + } + for (Board b : boardList){ + if (b.getBoardName() == item.getTitle()){ + System.out.println("Updating mainfragment to " + b.getBoardName() + " d: " + b.getBoardDir()); + mainFragment.setCatalogMode(); + mainFragment.updateBoardItems(b, null); + pager.setCurrentItem(0); + navigationView.getMenu().findItem(R.id.nav_recent_post).setChecked(false); + } + } + return true; + } + + public Board getBoardFromDir(String dir){ + for (Board b : boardList){ + if (b.getBoardDir().equals(dir)){ + return b; + } + } + System.out.println("[MainActivity] Board not found " + dir); + return null; + } + + + @Override + public void onFragmentInteraction(Uri uri) { + + } + + @Override + public void showThread(Board board, BoardItem thread) { + childFragment.updateBoardItems(board, thread); + pager.setCurrentItem(1); + } + + + @Override + public void updateToolbar(Board cBoard, BoardItem btem) { + if (pager.getCurrentItem() == 1){ + toolbar.setTitle(cBoard.getBoardName()); + toolbar.setSubtitle(btem.getSubject()); + } + } + + @Override + public void updateToolbar(String s) { + toolbar.setTitle(s); + toolbar.setSubtitle(""); + } + + @Override + public void hideActionButton() { + if (pager.getCurrentItem() == 1){ + fab.hide(); + } + } + + @Override + public void showActionButton() { + if (pager.getCurrentItem() == 1){ + fab.show(); + } + } + + private void getBoardList(){ + Menu menu = navigationView.getMenu(); + final SubMenu sub = menu.addSubMenu("Lista de Boards"); + Ion.with(getApplicationContext()) + .load("http://bienvenidoainternet.org/cgi/api/boards") + .asJsonObject() + .setCallback(new FutureCallback<JsonObject>() { + @Override + public void onCompleted(Exception e, JsonObject result) { + if (e != null) { + e.printStackTrace(); + Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); + } else { + JsonArray boards = result.get("boards").getAsJsonArray(); + for (int i = 0; i < boards.size(); i++) { + try { + JSONObject board = new JSONObject(boards.get(i).toString()); + Board parsedBoard = new Board(board.getString("name"), board.getString("dir"), board.getInt("board_type")); + sub.add(parsedBoard.getBoardName()); + boardList.add(parsedBoard); + } catch (JSONException e1) { + e1.printStackTrace(); + Toast.makeText(getApplicationContext(), "Error parsing JSON", Toast.LENGTH_LONG).show(); + } + } + } + } + }); + refreshNavigator(); + } + + public void refreshNavigator(){ + for (int i = 0, count = navigationView.getChildCount(); i < count; i++) { + final View child = navigationView.getChildAt(i); + if (child != null && child instanceof ListView) { + final ListView menuView = (ListView) child; + final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter(); + final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter(); + wrapped.notifyDataSetChanged(); + } + } + } + /* + Crea una secuencia de caracteres de 8 digitos aleatorios (incluye mayusculas, minisculas y numeros). + */ + + public String makePassword(){ + Random r = new Random(); + String rnd = ""; + for (int i = 0; i < 8; i++){ + int a = r.nextInt(3); + char b; + if (a == 0){ + b = (char)(66 + r.nextInt(25)); + }else if (a == 1){ + b = (char)(97 + r.nextInt(25)); + }else{ + b = (char) (48 + r.nextInt(9)); + } + rnd = rnd + b; + } + return rnd; + } + + public void checkForUpdates(){ + Ion.with(getApplicationContext()) + .load("http://ahri.xyz/bai/version.php") + .asString() + .setCallback(new FutureCallback<String>() { + @Override + public void onCompleted(Exception e, String result) { + if (e != null){ + e.printStackTrace(); + }else{ + try { + JSONObject version = new JSONObject(result); + float lastVersion = (float) version.getDouble("version"); + if (CURRENT_VERSION == lastVersion){ + Log.v("Updater", "Up to date"); + }else{ + Log.v("Updater", "New version available : " + lastVersion); + Snackbar.make(getCurrentFocus(), "Nueva versión disponible", Snackbar.LENGTH_LONG) + .setAction("Actualizar", new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent updater = new Intent(getApplicationContext(), UpdaterActivity.class); + startActivity(updater); + } + }) + .setActionTextColor(Color.rgb(255,127,0)) + .show(); + } + } catch (JSONException e1) { + e1.printStackTrace(); + } + } + } + }); + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/RecentPostAdapter.java b/app/src/main/java/org/bienvenidoainternet/baiparser/RecentPostAdapter.java new file mode 100644 index 0000000..e67f276 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/RecentPostAdapter.java @@ -0,0 +1,90 @@ +package org.bienvenidoainternet.baiparser; + +import android.content.Context; +import android.text.Html; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.TextView; + +import org.bienvenidoainternet.baiparser.structure.BoardItem; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Created by Renard on 21-03-2016. + */ +public class RecentPostAdapter extends ArrayAdapter<BoardItem> { + + public RecentPostAdapter(Context context, List<BoardItem> objects) { + super(context, 0, objects); + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + LayoutInflater inflater = (LayoutInflater)getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View listItemView = convertView; + if (null == convertView) { + listItemView = inflater.inflate( + R.layout.recentpost_item, + parent, + false); + } + final BoardItem postItem = getItem(position); + TextView rp_message = (TextView) listItemView.findViewById(R.id.rp_message); + TextView rp_title = (TextView) listItemView.findViewById(R.id.rp_title); + TextView rp_timediff = (TextView) listItemView.findViewById(R.id.rp_timediff); + if (postItem.getParentBoard() != null){ + rp_title.setText(postItem.getParentBoard().getBoardName() + ": " + postItem.getSubject()); + }else{ + rp_title.setText(postItem.getSubject()); + } + rp_message.setText(Html.fromHtml(postItem.getMessage())); + Map<TimeUnit,Long> timeDiff = computeDiff(new Date(postItem.getTimeStamp() * 1000L), new Date(System.currentTimeMillis())); + String strTimeDiff = ""; + if (timeDiff.get(TimeUnit.SECONDS) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.SECONDS) + (timeDiff.get(TimeUnit.SECONDS) == 1 ? " segundo" : " segundos"); + } + + if (timeDiff.get(TimeUnit.MINUTES) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.MINUTES) + (timeDiff.get(TimeUnit.MINUTES) == 1 ? " minuto" : " minutos"); + } + + if (timeDiff.get(TimeUnit.HOURS) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.HOURS) + (timeDiff.get(TimeUnit.HOURS) == 1 ? " hora" : " horas"); + } + + if (timeDiff.get(TimeUnit.DAYS) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.DAYS) + (timeDiff.get(TimeUnit.DAYS) == 1 ? " día" : " días"); + } + rp_timediff.setText(strTimeDiff); + + + return listItemView; + } + + + public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) { + long diffInMillies = date2.getTime() - date1.getTime(); + List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class)); + Collections.reverse(units); + Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>(); + long milliesRest = diffInMillies; + for ( TimeUnit unit : units ) { + long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS); + long diffInMilliesForUnit = unit.toMillis(diff); + milliesRest = milliesRest - diffInMilliesForUnit; + result.put(unit,diff); + } + return result; + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/ResponseActivity.java b/app/src/main/java/org/bienvenidoainternet/baiparser/ResponseActivity.java new file mode 100644 index 0000000..b319426 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/ResponseActivity.java @@ -0,0 +1,216 @@ +package org.bienvenidoainternet.baiparser; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v7.app.AppCompatActivity; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.koushikdutta.async.future.FutureCallback; +import com.koushikdutta.ion.Ion; + +import org.bienvenidoainternet.baiparser.structure.Board; +import org.bienvenidoainternet.baiparser.structure.BoardItem; +import org.w3c.dom.Document; + +import java.io.File; + +import utils.ContentProviderUtils; + +//import org.apache.http.HttpEntity; +//import org.apache.http.entity.ContentType; +//import org.apache.http.entity.mime.HttpMultipartMode; +//import org.apache.http.entity.mime.MultipartEntityBuilder; +//import org.apache.http.entity.mime.content.FileBody; +//import org.apache.http.entity.mime.content.StringBody; + +public class ResponseActivity extends AppCompatActivity { + + private BoardItem theReply = null; + private Board currentBoard = null; + private SharedPreferences settings; + private String password; + private String selectedFile = ""; + private final int PICK_IMAGE = 1; + EditText filePath; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_response); + settings = PreferenceManager.getDefaultSharedPreferences(this); + password = settings.getString("pref_password", "12345678"); + Log.v("password", password); + + if (savedInstanceState != null){ + this.theReply = savedInstanceState.getParcelable("theReply"); + this.currentBoard = savedInstanceState.getParcelable("theBoard"); + } + if (getIntent().getExtras() != null){ + this.theReply = getIntent().getParcelableExtra("theReply"); + this.currentBoard = getIntent().getParcelableExtra("theBoard"); + } + if (theReply != null && currentBoard != null){ + System.out.println(theReply.getId() + " " + theReply.getName()); + } + + LinearLayout layoutProcess = (LinearLayout)findViewById(R.id.layoutPostProcess); + layoutProcess.setVisibility(View.GONE); + filePath = (EditText) findViewById(R.id.txtFilePath); + Button send = (Button)findViewById(R.id.btnSend); + send.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + TextView txtName = (TextView) findViewById(R.id.txtPosterName); + TextView txtEmail = (TextView) findViewById(R.id.txtEmail); + TextView txtMessage = (TextView) findViewById(R.id.txtResponse); + makePost(txtName.getText().toString(), txtEmail.getText().toString(), txtMessage.getText().toString()); + + } + }); + + Button bBold = (Button) findViewById(R.id.buttonBold); + bBold.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + TextView txtMessage = (TextView) findViewById(R.id.txtResponse); + if (txtMessage.getSelectionStart() == -1){ + txtMessage.setText(txtMessage.getText() + "<b></b>"); + }else{ + String s = txtMessage.getText().toString(); + String a = s.substring(0, txtMessage.getSelectionStart()); + String b = s.substring(txtMessage.getSelectionStart(), txtMessage.getSelectionEnd()); + String c = s.substring(txtMessage.getSelectionEnd(), txtMessage.getText().length()); + txtMessage.setText(a + "<b>" + b + "</b>" + c); + } + } + }); + Button bItalic = (Button) findViewById(R.id.buttonItalic); + bItalic.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + TextView txtMessage = (TextView) findViewById(R.id.txtResponse); + if (txtMessage.getSelectionStart() == -1){ + txtMessage.setText(txtMessage.getText() + "<i></i>"); + }else{ + String s = txtMessage.getText().toString(); + String a = s.substring(0, txtMessage.getSelectionStart()); + String b = s.substring(txtMessage.getSelectionStart(), txtMessage.getSelectionEnd()); + String c = s.substring(txtMessage.getSelectionEnd(), txtMessage.getText().length()); + txtMessage.setText(a + "<i>" + b + "</i>" + c); + } + } + }); + + Button select = (Button) findViewById(R.id.btnSelectFiles); + + select.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(); + intent.setType("image/*"); + intent.setAction(Intent.ACTION_GET_CONTENT); + startActivityForResult(Intent.createChooser(intent, "Seleccionar Archivo"), PICK_IMAGE); + } + }); + + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) { + Uri selectedImage = data.getData(); + String picturePath = ContentProviderUtils.getPath(getApplicationContext(), selectedImage); + selectedFile = picturePath; + filePath.setText(picturePath); + } + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + } + + private void makePost(String name, String email, String message){ + int parentId = theReply.getParentId(); + if (theReply.getParentId() == 0 || theReply.getParentId() == -1){ + parentId = theReply.getId(); + } + LinearLayout layoutProcess = (LinearLayout)findViewById(R.id.layoutPostProcess); + layoutProcess.setVisibility(View.VISIBLE); + final RelativeLayout formSendPost = (RelativeLayout) findViewById(R.id.layoutForm); + formSendPost.setVisibility(View.GONE); + ProgressBar progess = (ProgressBar) findViewById(R.id.barPosting); + final TextView err = (TextView)findViewById(R.id.txtPostingState); + err.setText(""); + File up = new File(selectedFile); + if (selectedFile.isEmpty()) Ion.with(getApplicationContext()) + .load("http://bienvenidoainternet.org/cgi/post") + .setLogging("posting", Log.VERBOSE) + .uploadProgressBar(progess) + .setMultipartParameter("board", currentBoard.getBoardDir()) + .setMultipartParameter("parent", String.valueOf(theReply.realParentId())) + .setMultipartParameter("password", password) + .setMultipartParameter("fielda", name) + .setMultipartParameter("fieldb", email) + .setMultipartParameter("name", "") + .setMultipartParameter("email", "") + .setMultipartParameter("message", message) + .asString() + .setCallback(new FutureCallback<String>() { + @Override + public void onCompleted(Exception e, String result) { + Log.v("sendPost", result); + if (e != null){ + Toast.makeText(getApplicationContext(), "Ha ocurrido un error! ;_;", Toast.LENGTH_LONG).show(); + formSendPost.setVisibility(View.VISIBLE); + err.setText("Error: " + e.getMessage()); + e.printStackTrace(); + }else{ + Toast.makeText(getApplicationContext(), "Post enviado", Toast.LENGTH_LONG).show(); + finish(); + } + } + }); + else{ + Ion.with(getApplicationContext()) + .load("http://bienvenidoainternet.org/cgi/post") + .uploadProgressBar(progess) + .setMultipartParameter("board", currentBoard.getBoardDir()) + .setMultipartParameter("parent", String.valueOf(parentId)) + .setMultipartParameter("password", password) + .setMultipartParameter("fielda", name) + .setMultipartParameter("fieldb", email) + .setMultipartParameter("name", "") + .setMultipartParameter("email", "") + .setMultipartParameter("message", message) + .setMultipartFile("file", up) + .asDocument() + .setCallback(new FutureCallback<Document>() { + @Override + public void onCompleted(Exception e, Document result) { + if (e != null){ + Toast.makeText(getApplicationContext(), "Ha ocurrido un error! ;_;", Toast.LENGTH_LONG).show(); + formSendPost.setVisibility(View.VISIBLE); + err.setText("Error: " + e.getMessage()); + e.printStackTrace(); + }else{ + Toast.makeText(getApplicationContext(), "Post enviado", Toast.LENGTH_LONG).show(); + finish(); + } + } + }); + } + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/SettingsActivity.java b/app/src/main/java/org/bienvenidoainternet/baiparser/SettingsActivity.java new file mode 100644 index 0000000..e8e7df4 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/SettingsActivity.java @@ -0,0 +1,184 @@ +package org.bienvenidoainternet.baiparser; + + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.res.Configuration; +import android.os.Build; +import android.os.Bundle; +import android.preference.ListPreference; +import android.preference.Preference; +import android.preference.PreferenceActivity; +import android.preference.PreferenceFragment; +import android.preference.PreferenceManager; +import android.support.v7.app.ActionBar; +import android.view.MenuItem; + +import java.util.List; + +/** + * A {@link PreferenceActivity} that presents a set of application settings. On + * handset devices, settings are presented as a single list. On tablets, + * settings are split by category, with category headers shown to the left of + * the list of settings. + * <p/> + * See <a href="http://developer.android.com/design/patterns/settings.html"> + * Android Design: Settings</a> for design guidelines and the <a + * href="http://developer.android.com/guide/topics/ui/settings.html">Settings + * API Guide</a> for more information on developing a Settings UI. + */ +public class SettingsActivity extends AppCompatPreferenceActivity { + /** + * A preference value change listener that updates the preference's summary + * to reflect its new value. + */ + private static boolean requireReset = false; + private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object value) { + String stringValue = value.toString(); + + if (preference instanceof ListPreference) { + // For list preferences, look up the correct display value in + // the preference's 'entries' list. + ListPreference listPreference = (ListPreference) preference; + int index = listPreference.findIndexOfValue(stringValue); + + // Set the summary to reflect the new value. + preference.setSummary( + index >= 0 + ? listPreference.getEntries()[index] + : null); + + }else { + // For all other preferences, set the summary to the value's + // simple string representation. + preference.setSummary(stringValue); + } + System.out.println(preference.getKey()); + return true; + } + }; + + /** + * Helper method to determine if the device has an extra-large screen. For + * example, 10" tablets are extra-large. + */ + private static boolean isXLargeTablet(Context context) { + return (context.getResources().getConfiguration().screenLayout + & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; + } + + /** + * Binds a preference's summary to its value. More specifically, when the + * preference's value is changed, its summary (line of text below the + * preference title) is updated to reflect the value. The summary is also + * immediately updated upon calling this method. The exact display format is + * dependent on the type of preference. + * + * @see #sBindPreferenceSummaryToValueListener + */ + private static void bindPreferenceSummaryToValue(Preference preference) { + // Set the listener to watch for value changes. + preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); + requireReset = true; + // Trigger the listener immediately with the preference's + // current value. + sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, + PreferenceManager + .getDefaultSharedPreferences(preference.getContext()) + .getString(preference.getKey(), "")); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setupActionBar(); + getFragmentManager().beginTransaction().replace(android.R.id.content, new GeneralPreferenceFragment()).commit(); + } + + /** + * Set up the {@link android.app.ActionBar}, if the API is available. + */ + private void setupActionBar() { + ActionBar actionBar = getSupportActionBar(); + + if (actionBar != null) { + // Show the Up button in the action bar. + actionBar.setDisplayHomeAsUpEnabled(true); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean onIsMultiPane() { + return isXLargeTablet(this); + } + + /** + * {@inheritDoc} + */ + @Override + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public void onBuildHeaders(List<Header> target) { +// loadHeadersFromResource(R.xml.pref_headers, target); + } + + /** + * This method stops fragment injection in malicious applications. + * Make sure to deny any unknown fragments here. + */ + protected boolean isValidFragment(String fragmentName) { + return PreferenceFragment.class.getName().equals(fragmentName) + || GeneralPreferenceFragment.class.getName().equals(fragmentName) + ; + } + + @Override + public void onBackPressed() { + Intent returnIntent = new Intent(); + returnIntent.putExtra("result", requireReset); + setResult(Activity.RESULT_OK,returnIntent); + finish(); + super.onBackPressed(); + } + + /** + * This fragment shows general preferences only. It is used when the + * activity is showing a two-pane settings UI. + */ + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public class GeneralPreferenceFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preferences); + setHasOptionsMenu(true); + + // Bind the summaries of EditText/List/Dialog/Ringtone preferences + // to their values. When their values change, their summaries are + // updated to reflect the new value, per the Android Design + // guidelines. +// bindPreferenceSummaryToValue(findPreference("example_text")); + bindPreferenceSummaryToValue(findPreference("pref_theme")); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { +// startActivity(new Intent(getActivity(), SettingsActivity.class)); + Intent returnIntent = new Intent(); + returnIntent.putExtra("result",requireReset); + setResult(Activity.RESULT_OK,returnIntent); + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/ThemeManager.java b/app/src/main/java/org/bienvenidoainternet/baiparser/ThemeManager.java new file mode 100644 index 0000000..7f0be86 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/ThemeManager.java @@ -0,0 +1,55 @@ +package org.bienvenidoainternet.baiparser; + +import android.content.res.TypedArray; +import android.graphics.Color; + +/** + * Created by Renard on 16-03-2016. + */ +public class ThemeManager { + private MainActivity ac; + private int currentThemeId; + public ThemeManager(MainActivity ac){ + this.ac = ac; + this.currentThemeId = ac.getCurrentThemeId(); + } + + public int getSageColor(){ + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.sageColor}); + return a.getColor(0, Color.CYAN); + } + + public int getMarginColor(){ + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.marginColor}); + return a.getColor(0, Color.CYAN); + } + + public void updateThemeId(int id){ + this.currentThemeId = id; + } + + public int getNameColor() { + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.nameColor}); + return a.getColor(0, Color.CYAN); + } + + public int getTripcodeColor() { + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.tripcodeColor}); + return a.getColor(0, Color.CYAN); + } + + public int getPrimaryColor(){ + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.colorPrimary}); + return a.getColor(0, Color.CYAN); + } + public int getPrimaryDarkColor(){ + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.colorPrimaryDark}); + return a.getColor(0, Color.CYAN); + } + + public boolean isDarkTheme(){ + TypedArray a = ac.getTheme().obtainStyledAttributes(currentThemeId, new int[]{R.attr.isDarkTheme}); + return a.getBoolean(0, false); + } + +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/ThreadListAdapter.java b/app/src/main/java/org/bienvenidoainternet/baiparser/ThreadListAdapter.java new file mode 100644 index 0000000..118e9c6 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/ThreadListAdapter.java @@ -0,0 +1,281 @@ +package org.bienvenidoainternet.baiparser; + +import android.animation.ArgbEvaluator; +import android.animation.ObjectAnimator; +import android.animation.ValueAnimator; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Typeface; +import android.graphics.drawable.ColorDrawable; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Html; +import android.text.Layout; +import android.text.Spannable; +import android.text.style.ClickableSpan; +import android.text.style.URLSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import org.bienvenidoainternet.baiparser.structure.BoardItem; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +/** + * Created by Renard on 11-03-2016. + */ +public class ThreadListAdapter extends ArrayAdapter<BoardItem>{ + private Context context; + private ThemeManager tm; + Typeface monaFont; + public boolean listThreads = false; + + public ThreadListAdapter(Context context, List<BoardItem> objects, ThemeManager tm) { + super(context, 0, objects); + this.context = context; + this.tm = tm; + monaFont = Typeface.createFromAsset(context.getAssets(), "fonts/mona.ttf"); + } + + private String intToHexString(int i){ + return String.format("#%06X", (0xFFFFFF & i)); + } + public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) { + long diffInMillies = date2.getTime() - date1.getTime(); + List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class)); + Collections.reverse(units); + Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>(); + long milliesRest = diffInMillies; + for ( TimeUnit unit : units ) { + long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS); + long diffInMilliesForUnit = unit.toMillis(diff); + milliesRest = milliesRest - diffInMilliesForUnit; + result.put(unit,diff); + } + return result; + } + @Override + public View getView(int position, final View convertView, final ViewGroup parent){ + LayoutInflater inflater = (LayoutInflater)getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View listItemView = convertView; + if (null == convertView) { + listItemView = inflater.inflate( + R.layout.thread_item, + parent, + false); + } + + final BoardItem boardItem = getItem(position); + if (boardItem == null){ + return listItemView; + } + SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getContext()); + boolean useMonaFont = settings.getBoolean("setting_monafont", true); + boolean monaBbsOnly = settings.getBoolean("setting_mona_bbsonly", true); + int marginColor = tm.getMarginColor(); + int sageColor = tm.getSageColor(); + int nameColor = tm.getNameColor(); + int tripcodeColor = tm.getTripcodeColor(); + String hexColor =intToHexString(boardItem.getIdColor()); + String sageHexColor = intToHexString(sageColor); + String nameHexColor = intToHexString(nameColor); + String tripcodeHexColor = intToHexString(tripcodeColor); + String strId = ""; + + TextView txtTitle = (TextView)listItemView.findViewById(R.id.lv_txtTitle); + TextView txtPoster = (TextView)listItemView.findViewById(R.id.lv_txtPoster); + TextView txtBody = (TextView) listItemView.findViewById(R.id.lv_txtBody); + TextView txtReplies = (TextView) listItemView.findViewById(R.id.lv_txtReplyCounter); + TextView txtFileInfo = (TextView) listItemView.findViewById(R.id.lv_txtFileInfo); + ImageView ivMargin = (ImageView)listItemView.findViewById(R.id.ivMargin); + ImageView ivThumb = (ImageView)listItemView.findViewById(R.id.ivThumb); + + ivThumb.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (!boardItem.getThumb().isEmpty() && convertView != null){ + if (boardItem.getFile().endsWith(".webm")){ + Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("http://bienvenidoainternet.org/" + boardItem.getParentBoard().getBoardDir() + "/src/" + boardItem.getFile())); + in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + v.getContext().startActivity(in); + }else { + Intent in = new Intent(convertView.getContext(), ViewerActivity.class); + Bundle b = new Bundle(); + b.putParcelable("boardItem", boardItem); + in.putExtras(b); + convertView.getContext().startActivity(in); + } + } + } + }); + + + ivMargin.setImageDrawable(new ColorDrawable(marginColor)); + + if (useMonaFont){ + if (monaBbsOnly && boardItem.getParentBoard() != null){ + if (boardItem.getParentBoard().getBoardType() == 1){ + txtBody.setTypeface(monaFont); + } + }else{ + txtBody.setTypeface(monaFont); + } + } + + // Si es una respuesta ocultamos el margen + if (boardItem.isReply){ + ivMargin.setVisibility(View.VISIBLE); + txtTitle.setVisibility(View.GONE); + }else{ + txtTitle.setVisibility(View.VISIBLE); + ivMargin.setVisibility(View.GONE); + txtTitle.setText(boardItem.getSubject()); + } + + // Si el fragmento esta viendo un hilo ocultamos los margenes + if (listThreads){ + ivMargin.setVisibility(View.GONE); + } + + // Si el item está eliminado activamos el soporte de <strike> + if (boardItem.getDeletedCode() != 0){ + txtBody.setPaintFlags(txtBody.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + }else{ + txtBody.setPaintFlags(txtBody.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); + } + + + if (boardItem.getThumb().isEmpty()){ + ivThumb.setVisibility(View.GONE); + }else{ + if (boardItem.getThumbBitmap() != null){ + ivThumb.setVisibility(View.VISIBLE); + ivThumb.setImageBitmap(boardItem.getThumbBitmap()); + }else{ + ivThumb.setVisibility(View.VISIBLE); + ivThumb.setImageResource(R.drawable.blank); + } + } + + Map<TimeUnit,Long> timeDiff = computeDiff(new Date(boardItem.getTimeStamp() * 1000L), new Date(System.currentTimeMillis())); + String strTimeDiff = ""; + if (timeDiff.get(TimeUnit.SECONDS) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.SECONDS) + (timeDiff.get(TimeUnit.SECONDS) == 1 ? " segundo" : " segundos"); + } + if (timeDiff.get(TimeUnit.MINUTES) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.MINUTES) + (timeDiff.get(TimeUnit.MINUTES) == 1 ? " minuto" : " minutos"); + } + if (timeDiff.get(TimeUnit.HOURS) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.HOURS) + (timeDiff.get(TimeUnit.HOURS) == 1 ? " hora" : " horas"); + } + if (timeDiff.get(TimeUnit.DAYS) != 0){ + strTimeDiff = "Hace " + timeDiff.get(TimeUnit.DAYS) + (timeDiff.get(TimeUnit.DAYS) == 1 ? " día" : " días"); + } + + + if (!boardItem.getPosterId().isEmpty() && !boardItem.getPosterId().equals("???")){ + strId = "<font color=" + hexColor + ">[" + boardItem.getPosterId() + "]</font> "; + } + + // Si estamos mostrando un item de BBS, mostrar el ID_BBS en ves del ID del post + int idToDisplay = 0; + if (boardItem.getParentBoard() != null){ + if (boardItem.getParentBoard().getBoardType() == 1){ + idToDisplay = boardItem.getBbsId(); + }else{ + idToDisplay = boardItem.getId(); + } + }else{ + idToDisplay = boardItem.getId(); + } + + txtPoster.setText(Html.fromHtml("<b>No. " + idToDisplay + "</b> por <font color=" + (boardItem.isSage() ? sageHexColor : nameHexColor) + ">" + boardItem.getName() + "</font> " + + (boardItem.getTripcode() == "" ? "" : "<font color=" + tripcodeHexColor + ">" + boardItem.getTripcode() + "</font>") + strId + " " + strTimeDiff)); + txtBody.setText(Html.fromHtml(boardItem.getMessage())); + + txtReplies.setVisibility(boardItem.isReply ? View.GONE : View.VISIBLE); + txtReplies.setText(boardItem.getTotalReplies() + " respuestas " + (boardItem.getTotalFiles() == 0 ? "" : ", " + boardItem.getTotalFiles() + " archivos")); + + txtFileInfo.setVisibility(boardItem.getThumb().isEmpty() ? View.GONE : View.VISIBLE); + txtFileInfo.setText((boardItem.getFileSize() / 1024) + " KB " + boardItem.getThumbHeight() + "x" + boardItem.getThumbWidth()); + + // Trasnparentar items con sage + if (convertView != null){ + convertView.setAlpha(boardItem.isSage() ? 0.75F : 1.0F); + } + + /* + http://stackoverflow.com/questions/8558732/listview-textview-with-linkmovementmethod-makes-list-item-unclickable + */ + txtBody.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + boolean ret = false; + CharSequence text = ((TextView) v).getText(); + Spannable stext = Spannable.Factory.getInstance().newSpannable(text); + TextView widget = (TextView) v; + int action = event.getAction(); + + if (action == MotionEvent.ACTION_UP || + action == MotionEvent.ACTION_DOWN) { + int x = (int) event.getX(); + int y = (int) event.getY(); + + x -= widget.getTotalPaddingLeft(); + y -= widget.getTotalPaddingTop(); + + x += widget.getScrollX(); + y += widget.getScrollY(); + + Layout layout = widget.getLayout(); + int line = layout.getLineForVertical(y); + int off = layout.getOffsetForHorizontal(line, x); + + ClickableSpan[] link = stext.getSpans(off, off, ClickableSpan.class); +/*04-03 17:46:54.646 13693-13693/org.bienvenidoainternet.baiparser V/URLParts: zonavip +04-03 17:46:54.646 13693-13693/org.bienvenidoainternet.baiparser V/URLParts: read +04-03 17:46:54.646 13693-13693/org.bienvenidoainternet.baiparser V/URLParts: 43872 +04-03 17:46:54.650 13693-13693/org.bienvenidoainternet.baiparser V/URLParts: 25*/ + if (link.length != 0) { + if (link[0] instanceof URLSpan){ + URLSpan uspan = (URLSpan) link[0]; + if (uspan.getURL().contains("/read/") && !uspan.getURL().contains("http")){ + String url = uspan.getURL(); + String[] parts = url.split("/"); + if (parts.length == 4 && listThreads){ + Log.v("ConvertView", convertView.getParent().toString()); + } + return true; + } + } + if (action == MotionEvent.ACTION_UP) { + link[0].onClick(widget); + } + ret = true; + } + } + return ret; + } + }); + return listItemView; + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/UpdaterActivity.java b/app/src/main/java/org/bienvenidoainternet/baiparser/UpdaterActivity.java new file mode 100644 index 0000000..e98f303 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/UpdaterActivity.java @@ -0,0 +1,127 @@ +package org.bienvenidoainternet.baiparser; + +import android.content.Context; +import android.content.ContextWrapper; +import android.content.Intent; +import android.net.Uri; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.text.Html; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import com.koushikdutta.async.future.FutureCallback; +import com.koushikdutta.ion.Ion; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; + +public class UpdaterActivity extends AppCompatActivity { + private float lastVersion = 1.0F; + Button btnUpdate; + ProgressBar barUpdate; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_updater); + setTheme(R.style.AppTheme_Black_Activity); + btnUpdate = (Button) findViewById(R.id.btnDownloadLastVersion); + barUpdate = (ProgressBar) findViewById(R.id.barUpdateProgress); + TextView txtCurrentVersion = (TextView) findViewById(R.id.txtCurrentVersion); + btnUpdate.setEnabled(false); + txtCurrentVersion.setText("Versión actual: " + MainActivity.CURRENT_VERSION); + getVersionData(); + btnUpdate.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + downloadApk(); + } + }); + } + + private void getVersionData(){ + Ion.with(getApplicationContext()) + .load("http://ahri.xyz/bai/version.php") + .asString() + .setCallback(new FutureCallback<String>() { + @Override + public void onCompleted(Exception e, String result) { + if (e != null) { + e.printStackTrace(); + } else { + JSONObject version = null; + try { + version = new JSONObject(result); + lastVersion = (float) version.getDouble("version"); + TextView txtLastVersion = (TextView) findViewById(R.id.txtLastVersion); + txtLastVersion.setText("Última versión: " + lastVersion); + + if (lastVersion > MainActivity.CURRENT_VERSION) { + getChangelog(); + btnUpdate.setEnabled(true); + } + } catch (JSONException e1) { + e1.printStackTrace(); + } + } + } + }); + } + + private void getChangelog(){ + Ion.with(getApplicationContext()) + .load("http://ahri.xyz/bai/lastChangelog.txt") + .asString() + .setCallback(new FutureCallback<String>() { + @Override + public void onCompleted(Exception e, String result) { + if (e != null){ + e.printStackTrace(); + }else{ + TextView txtChangelog = (TextView) findViewById(R.id.txtChangelog); + txtChangelog.setText(Html.fromHtml(result)); + } + } + }); + } + + private void downloadApk(){ + ContextWrapper cw = new ContextWrapper(getApplicationContext()); + File directory = cw.getDir("src", Context.MODE_PRIVATE); + if (!directory.exists()) { + directory.mkdir(); + } + final File filePath = new File(directory, "last.apk"); + if (filePath.exists()) { + filePath.delete(); + } + Ion.with(getApplicationContext()) + .load("http://ahri.xyz/bai/" + lastVersion + "/last.apk") + .setLogging("Updater", Log.VERBOSE) + .progressBar(barUpdate) + .write(filePath) + .setCallback(new FutureCallback<File>() { + @Override + public void onCompleted(Exception e, File result) { + if (e != null) { + Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); + } else { + Intent promptInstall = new Intent(Intent.ACTION_VIEW) + .setDataAndType(Uri.fromFile(filePath), + "application/vnd.android.package-archive"); + startActivity(promptInstall); + } + } + }); + } +} + + diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/ViewerActivity.java b/app/src/main/java/org/bienvenidoainternet/baiparser/ViewerActivity.java new file mode 100644 index 0000000..b113c2a --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/ViewerActivity.java @@ -0,0 +1,247 @@ +package org.bienvenidoainternet.baiparser; + +import android.content.Context; +import android.content.ContextWrapper; +import android.graphics.Bitmap; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.Environment; +import android.support.v7.app.AppCompatActivity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.ProgressBar; +import android.widget.Toast; + +import com.davemorrissey.labs.subscaleview.ImageSource; +import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView; +import com.koushikdutta.async.future.FutureCallback; +import com.koushikdutta.ion.Ion; + +import org.bienvenidoainternet.baiparser.structure.BoardItem; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import pl.droidsonroids.gif.GifDrawable; +import pl.droidsonroids.gif.GifImageView; + +public class ViewerActivity extends AppCompatActivity { + private SubsamplingScaleImageView imageView; + private GifImageView gifView; + private BoardItem bi; + File imagePath; + + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + +// SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); +// int themeId = Integer.valueOf(settings.getString("setting_theme", "1")), currentThemeId = R.style.AppTheme; +// switch (themeId) { +// case 1: +// currentThemeId = R.style.AppTheme_NoActionBar; +// break; +// case 2: +// currentThemeId = R.style.AppTheme_Dark; +// break; +// case 3: +// currentThemeId = R.style.AppTheme_HeadLine; +// break; +// case 4: +// currentThemeId = R.style.AppTheme_Black; +// break; +// } +// setTheme(currentThemeId); + + + if (savedInstanceState != null){ + bi = savedInstanceState.getParcelable("boardItem"); + } + if (getIntent().getExtras() != null){ + bi = getIntent().getParcelableExtra("boardItem"); + } + setContentView(R.layout.activity_viewer); + imageView = (SubsamplingScaleImageView)findViewById(R.id.imageView); + gifView = (GifImageView) findViewById(R.id.gifView); + setTitle(bi.getFile()); +// imageView.setOnClickListener(new View.OnClickListener() { +// new TaskDownloadFile().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + downloadFile(); + this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + File baiDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Bai/"); + if (!baiDir.exists()){ + baiDir.mkdir(); + } + if (item.getItemId() == R.id.menu_save_img){ + File to = new File(Environment.getExternalStorageDirectory().getPath() + "/Bai/" + bi.getFile()); + try{ + InputStream in = new FileInputStream(imagePath); + OutputStream out = new FileOutputStream(to); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + Toast.makeText(getApplicationContext(), bi.getFile() + " guardado.", Toast.LENGTH_LONG).show(); + }catch (Exception e){ + e.printStackTrace(); + } + + } + if (item.getItemId() == android.R.id.home) { + onBackPressed(); + } + return super.onOptionsItemSelected(item); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_viewer, menu); + return true; + } + + private void downloadFile(){ + ContextWrapper cw = new ContextWrapper(getApplicationContext()); + File directory = cw.getDir("src", Context.MODE_PRIVATE); + final File filePath = new File(directory, bi.getParentBoard().getBoardDir() + "_" + bi.getFile()); + final ProgressBar downloadBar = (ProgressBar) findViewById(R.id.downloadProgressBar); + if (filePath.exists()){ + downloadBar.setVisibility(View.GONE); + if (bi.getFile().endsWith(".gif")){ + try { + GifDrawable gifFromFile = new GifDrawable(filePath); + gifView.setImageDrawable(gifFromFile); + imageView.setVisibility(View.GONE); + }catch(Exception e){ + e.printStackTrace(); + } + }else{ + imageView.setImage(ImageSource.uri(filePath.toURI().getPath())); + gifView.setVisibility(View.GONE); + } + } + Ion.with(getApplicationContext()) + .load("http://bienvenidoainternet.org/" + bi.getParentBoard().getBoardDir() + "/src/" + bi.getFile()) + .progressBar(downloadBar) + .asInputStream() + .setCallback(new FutureCallback<InputStream>() { + @Override + public void onCompleted(Exception e, InputStream result) { + downloadBar.setVisibility(View.GONE); + if (e != null){ + e.printStackTrace(); + }else{ + FileOutputStream fout; + try { + fout = new FileOutputStream(filePath); + final byte data[] = new byte[1024]; + int count; + while ((count = result.read(data, 0, 1024)) != -1) { + fout.write(data, 0, count); + } + }catch(Exception e1) { + e1.printStackTrace(); + } + if (bi.getFile().endsWith(".gif")){ + try { + GifDrawable gifFromFile = new GifDrawable(filePath); + gifView.setImageDrawable(gifFromFile); + imageView.setVisibility(View.GONE); + }catch(Exception e2){ + e2.printStackTrace(); + } + }else{ + imageView.setImage(ImageSource.uri(filePath.toURI().getPath())); + gifView.setVisibility(View.GONE); + } + } + } + }); + } + + class TaskDownloadFile extends AsyncTask<Void, Void, File> { + + @Override + protected File doInBackground(Void... params) { + Bitmap downloadedBitmap = null; + ContextWrapper cw = new ContextWrapper(getApplicationContext()); + File directory = cw.getDir("src", Context.MODE_PRIVATE); + File mypath = new File(directory, bi.getParentBoard().getBoardDir() + "_" + bi.getFile()); + if (mypath.exists()){ + System.out.println("[Viewer] resource exist!"); + return mypath; + } + try { + String sUrl = "http://bienvenidoainternet.org/" + bi.getParentBoard().getBoardDir() + "/src/" + bi.getFile(); + System.out.println("[Viewer]dwonloading " + sUrl); +// System.out.println(sUrl); + InputStream in = new java.net.URL(sUrl).openStream(); +// downloadedBitmap = BitmapFactory.decodeStream(in); + +// if (downloadedBitmap != null){ + FileOutputStream fout = null; + try { +// in = new BufferedInputStream(new URL(urlString).openStream()); + fout = new FileOutputStream(mypath); + + final byte data[] = new byte[1024]; + int count; + while ((count = in.read(data, 0, 1024)) != -1) { + fout.write(data, 0, count); + } + + + }catch(Exception e){ + e.printStackTrace(); + }finally { + if (in != null) { + in.close(); + } + if (fout != null) { + fout.close(); + } + } +// } + } catch (Exception e) { + e.printStackTrace(); + } + + return mypath; + } + + @Override + protected void onPostExecute(File file) { + super.onPostExecute(file); + imagePath = file; +// iv.setImageBitmap(bitmap); + if (bi.getFile().endsWith(".gif")){ + try { + GifDrawable gifFromFile = new GifDrawable(file); + gifView.setImageDrawable(gifFromFile); + imageView.setVisibility(View.GONE); + }catch(Exception e){ + e.printStackTrace(); + } + }else{ + imageView.setImage(ImageSource.uri(file.toURI().getPath())); + gifView.setVisibility(View.GONE); +// imageView.setImage(ImageSource.resource(R.drawable.bai)); +// System.out.println("not a gif file: " + file.toURI().getPath()); + } + + } + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/structure/Board.java b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/Board.java new file mode 100644 index 0000000..209804e --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/Board.java @@ -0,0 +1,60 @@ +package org.bienvenidoainternet.baiparser.structure; + +import android.os.Parcel; +import android.os.Parcelable; + +/** + * Created by Renard on 17-03-2016. + */ + +public class Board implements Parcelable{ + private String boardName, boardDir; + private int boardType; + public Board(String boardName,String boardDir,int boardType){ + this.boardName = boardName; + this.boardDir = boardDir; + this.boardType = boardType; + } + + public Board(Parcel in){ + this.boardName = in.readString(); + this.boardDir = in.readString(); + this.boardType = in.readInt(); + } + + public String getBoardDir() { + return boardDir; + } + + public String getBoardName() { + return boardName; + } + + public int getBoardType() { + return boardType; + } + + public static final Creator<Board> CREATOR = new Creator<Board>() { + @Override + public Board createFromParcel(Parcel in) { + return new Board(in); + } + + @Override + public Board[] newArray(int size) { + return new Board[size]; + } + }; + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(boardName); + dest.writeString(boardDir); + dest.writeInt(boardType); + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/structure/BoardItem.java b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/BoardItem.java new file mode 100644 index 0000000..c43384a --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/BoardItem.java @@ -0,0 +1,310 @@ +package org.bienvenidoainternet.baiparser.structure; + +import android.graphics.Bitmap; +import android.os.Parcel; +import android.os.Parcelable; + +/** + * Created by Renard on 17-03-2016. + */ +public class BoardItem implements Parcelable { + private String name = ""; + private String timestamp_formatted = ""; + private String thumb = ""; + private String tripcode = ""; + private String email = ""; + private String file = ""; + private String message = ""; + private String subject = ""; + private String posterId = ""; + private int parentid, id, idcolor, totalreplies = 0, totalfiles, thumb_height, thumb_weight, filesize, deleted_code, bbs_id = 1, parentPostCount; + private long timestamp = 0; + + private Bitmap thumbBitmap = null; + public boolean downloadingThumb = false; + public boolean isReply = false; + private Board parentBoard = null; + + protected BoardItem(Parcel in) { + name = in.readString(); + timestamp_formatted = in.readString(); + thumb = in.readString(); + tripcode = in.readString(); + email = in.readString(); + file = in.readString(); + message = in.readString(); + subject = in.readString(); + posterId = in.readString(); + parentid = in.readInt(); + id = in.readInt(); + idcolor = in.readInt(); + totalreplies = in.readInt(); + totalfiles = in.readInt(); + thumb_height = in.readInt(); + thumb_weight = in.readInt(); + filesize = in.readInt(); + deleted_code = in.readInt(); + bbs_id = in.readInt(); + parentPostCount = in.readInt(); + timestamp = in.readLong(); + thumbBitmap = in.readParcelable(Bitmap.class.getClassLoader()); + downloadingThumb = in.readByte() != 0; + isReply = in.readByte() != 0; + parentBoard = in.readParcelable(Board.class.getClassLoader()); + } + + public static final Creator<BoardItem> CREATOR = new Creator<BoardItem>() { + @Override + public BoardItem createFromParcel(Parcel in) { + return new BoardItem(in); + } + + @Override + public BoardItem[] newArray(int size) { + return new BoardItem[size]; + } + }; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getFile() { + return file; + } + + public void setFile(String file) { + this.file = file; + } + + public int getFileSize() { + return filesize; + } + + public void setFilesize(int filesize) { + this.filesize = filesize; + } + + public int getIdColor() { + return idcolor; + } + + public void setIdColor(int idcolor) { + this.idcolor = idcolor; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + // TODO: Dar formato a los mensajes de otra forma + this.message = message.replace("<span class=\"unkfunc\">", "<font color=#85c749><i>"); + this.message = this.message.replace("</span>", "</i></font>"); + if (this.message.contains("<hr")){ + this.message = this.message.replace("<hr />", "<br><br><small><font color=#FF8800><i>") + "</i></small></font>"; + } + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Board getParentBoard() { + return parentBoard; + } + + public void setParentBoard(Board parentBoard) { + this.parentBoard = parentBoard; + } + + public int getParentId() { + return parentid; + } + + public void setParentId(int parentid) { + this.parentid = parentid; + } + + public int getParentPostCount() { + return parentPostCount; + } + + public void setParentPostCount(int parentPostCount) { + this.parentPostCount = parentPostCount; + } + + public String getPosterId() { + return posterId; + } + + public void setPosterId(String posterId) { + this.posterId = posterId; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getThumb() { + return thumb; + } + + public void setThumb(String thumb) { + this.thumb = thumb; + } + + public int getThumbHeight() { + return thumb_height; + } + + public void setThumbHeight(int thumb_height) { + this.thumb_height = thumb_height; + } + + public int getThumbWidth() { + return thumb_weight; + } + + public void setThumbWidth(int thumb_weight) { + this.thumb_weight = thumb_weight; + } + + public Bitmap getThumbBitmap() { + return thumbBitmap; + } + + public void setThumbBitmap(Bitmap thumbBitmap) { + this.thumbBitmap = thumbBitmap; + } + + public long getTimeStamp() { + return timestamp; + } + + public void setTimeStamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getTimeStampFormatted() { + return timestamp_formatted; + } + + public void setTimeStampFormatted(String timestamp_formatted) { + this.timestamp_formatted = timestamp_formatted; + } + + public int getTotalFiles() { + return totalfiles; + } + + public void setTotalFiles(int totalfiles) { + this.totalfiles = totalfiles; + } + + public int getTotalReplies() { + return totalreplies; + } + + public void setTotalReplies(int totalreplies) { + this.totalreplies = totalreplies; + } + + public String getTripcode() { + return tripcode; + } + + public void setTripcode(String tripcode) { + this.tripcode = tripcode; + } + + public int getDeletedCode() { + return deleted_code; + } + + public void setDeletedCode(int deleted_code) { + this.deleted_code = deleted_code; + if (deleted_code == 1){ + this.message = "Eliminado por el usuario."; + }else if (deleted_code == 2){ + this.message = "Eliminado por el Staff."; + } + } + + public int getBbsId() { + return bbs_id; + } + + public void setBbsId(int bbs_id) { + this.bbs_id = bbs_id; + } + + public int realParentId(){ + if (parentid == 0){ + return id; + } + return parentid; + } + + public BoardItem() { + + } + + public boolean isSage(){ + return this.email.equals("sage"); + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(name); + dest.writeString(timestamp_formatted); + dest.writeString(thumb); + dest.writeString(tripcode); + dest.writeString(email); + dest.writeString(file); + dest.writeString(message); + dest.writeString(subject); + dest.writeString(posterId); + dest.writeInt(parentid); + dest.writeInt(id); + dest.writeInt(idcolor); + dest.writeInt(totalreplies); + dest.writeInt(totalfiles); + dest.writeInt(thumb_height); + dest.writeInt(thumb_weight); + dest.writeInt(filesize); + dest.writeInt(deleted_code); + dest.writeInt(bbs_id); + dest.writeInt(parentPostCount); + dest.writeLong(timestamp); + dest.writeParcelable(thumbBitmap, flags); + dest.writeByte((byte) (downloadingThumb ? 1 : 0)); + dest.writeByte((byte) (isReply ? 1 : 0)); + dest.writeParcelable(parentBoard, flags); + } +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/structure/JsonType.java b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/JsonType.java new file mode 100644 index 0000000..8db5c11 --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/JsonType.java @@ -0,0 +1,10 @@ +package org.bienvenidoainternet.baiparser.structure; + +/** + * Created by Renard on 17-03-2016. + */ +public enum JsonType { + BOARD_THREAD_LIST, + THREAD_REPLY_LIST, + BOARD_LIST; +} diff --git a/app/src/main/java/org/bienvenidoainternet/baiparser/structure/ReplyID.java b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/ReplyID.java new file mode 100644 index 0000000..b6758fb --- /dev/null +++ b/app/src/main/java/org/bienvenidoainternet/baiparser/structure/ReplyID.java @@ -0,0 +1,48 @@ +package org.bienvenidoainternet.baiparser.structure; + +import android.graphics.Color; +import android.os.Parcel; +import android.os.Parcelable; + +import java.util.Random; + +/** + * Created by Renard on 18-03-2016. + */ +public class ReplyID implements Parcelable{ + public String id; + public int color; + public ReplyID(String id){ + this.id = id; + Random r = new Random(); + this.color = Color.rgb(r.nextInt(125) + 127, r.nextInt(127) + 127, r.nextInt(127) + 127); + } + + protected ReplyID(Parcel in) { + id = in.readString(); + color = in.readInt(); + } + + public static final Creator<ReplyID> CREATOR = new Creator<ReplyID>() { + @Override + public ReplyID createFromParcel(Parcel in) { + return new ReplyID(in); + } + + @Override + public ReplyID[] newArray(int size) { + return new ReplyID[size]; + } + }; + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(id); + dest.writeInt(color); + } +} |