Commit 60e0a9dd authored by Schoumi's avatar Schoumi

First Commit of the project before cleanup and gpl header add

parent cb1755c5
# Built application files
*.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
......@@ -16,6 +6,7 @@ gen/
.gradle/
build/
/*/build/
gradlew*
# Local configuration file (sdk path, etc)
local.properties
......@@ -25,3 +16,7 @@ proguard/
# Log Files
*.log
#android-studio file
.idea
*.iml
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "fr.mobdev.gobelim"
minSdkVersion 11
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
}
package fr.mobdev.gobelim;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.mobdev.gobelim" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="fr.mobdev.gobelim.activity.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
<activity
android:name="fr.mobdev.gobelim.activity.HistoryActivity"
android:label="@string/title_activity_history">
</activity>
<activity
android:name="fr.mobdev.gobelim.activity.LinkActivity"
android:label="@string/title_activity_link"
>
</activity>
<activity
android:name="fr.mobdev.gobelim.activity.ServersActivity"
android:label="@string/title_activity_servers"
>
</activity>
</application>
</manifest>
package fr.mobdev.gobelim;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import fr.mobdev.gobelim.objects.Img;
import fr.mobdev.gobelim.objects.Server;
public class Database extends SQLiteOpenHelper {
private static Database instance;
public static Database getInstance(Context context)
{
if(instance == null)
instance = new Database(context, "Lutim.db", null, 1);
return instance;
}
private Database(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table if not exists history (" +
"id integer primary key autoincrement, url varchar(1024), short_hash varchar(1024), real_short_hash varchar(1024), date INTEGER, storage_duration INTEGER ,thumb TEXT);");
db.execSQL("Create table if not exists servers (" +
"id integer primary key autoincrement, url varchar(1024), isDefault INTEGER);");
ContentValues values = new ContentValues();
values.put("url","https://framapic.org");
values.put("isDefault",true);
db.insert("servers",null,values);
values.clear();
values.put("url","https://lut.im");
values.put("isDefault",false);
db.insert("servers", null, values);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//nothing to do right now
}
public List<Img> getHistory() {
List<Img> history = new ArrayList<Img>();
String orderBy = "date ASC";
Cursor cursor = getReadableDatabase().query("history", null, null, null, null, null, orderBy);
while(cursor.moveToNext())
{
int col = 0;
long id = cursor.getLong(col++);
String url = cursor.getString(col++);
String shortHash = cursor.getString(col++);
String realShortHash = cursor.getString(col++);
long timestamp = cursor.getLong(col++);
int storageDuration = cursor.getInt(col++);
byte[] thumbData = cursor.getBlob(col++);
Calendar date = Calendar.getInstance();
date.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
date.setTimeInMillis(timestamp);
Img img = new Img(id, url, shortHash, realShortHash, date, storageDuration, thumbData);
history.add(img);
}
return history;
}
public void deleteImg(List<Img> deletedList) {
for(Img img : deletedList)
{
String whereClause = "id = ?";
String[] whereArgs = new String[1];
whereArgs[0] = String.valueOf(img.getId());
getWritableDatabase().delete("history", whereClause, whereArgs);
}
}
public void addImage(Img img) {
ContentValues values = new ContentValues();
values.put("url", img.getUrl());
values.put("short_hash", img.getShortHash());
values.put("real_short_hash", img.getRealShortHash());
values.put("date", img.getDate().getTimeInMillis());
values.put("storage_duration", img.getStorageDuration());
if(img.getThumbData() != null)
values.put("thumb",img.getThumbData());
getWritableDatabase().insert("history", null, values);
}
public void addServer(String url)
{
ContentValues values = new ContentValues();
values.put("url",url);
values.put("isDefault",false);
getWritableDatabase().insert("servers", null, values);
}
public List<Server> getServers(boolean defaultFirst)
{
List<Server> servers = new ArrayList<Server>();
Cursor cursor = getReadableDatabase().query("servers", null, null, null, null, null, null);
while(cursor.moveToNext())
{
int col = 0;
long id = cursor.getLong(col++);
String url = cursor.getString(col++);
int defValue = cursor.getInt(col++);
boolean isDefault = false;
if(defValue == 1)
isDefault = true;
Server server = new Server(id, url, isDefault);
if(defaultFirst && isDefault)
{
servers.add(0,server);
}
else
{
servers.add(server);
}
}
return servers;
}
public void deleteServer(long idServer)
{
String whereClause ="id = ?";
String[] whereArgs = new String[1];
whereArgs[0] = String.valueOf(idServer);
getWritableDatabase().delete("servers",whereClause,whereArgs);
}
public void setDefaultServer(long newDefaultId, long oldDefaultId)
{
String whereClause = "id = ?";
String[] whereargs = new String[1];
whereargs[0] = String.valueOf(newDefaultId);
ContentValues values = new ContentValues();
values.put("isDefault",true);
getWritableDatabase().update("servers", values, whereClause, whereargs);
if(oldDefaultId != -1) {
values.clear();
whereargs[0] = String.valueOf(oldDefaultId);
values.put("isDefault", false);
getWritableDatabase().update("servers", values, whereClause, whereargs);
}
}
}
package fr.mobdev.gobelim;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.util.Log;
import fr.mobdev.gobelim.listener.NetworkListener;
import fr.mobdev.gobelim.objects.Img;
public class NetworkManager {
private NetworkListener listener;
private static NetworkManager instance;
private Context context;
private static int id;
private NetworkManager(NetworkListener listener,Context context)
{
this.listener = listener;
this.context = context;
}
public static NetworkManager getInstance(NetworkListener listener, Context context){
if (instance == null)
instance = new NetworkManager(listener,context);
if(listener != instance.getListener())
instance.setListener(listener);
return instance;
}
private NetworkListener getListener()
{
return listener;
}
private void setListener(NetworkListener listener)
{
this.listener = listener;
}
public void upload(final String siteUrl, final int nbDays, final String fileName, final byte[] bytearray)
{
if(!isConnectedToInternet(context))
return;
new Thread(new Runnable() {
@Override
public void run() {
Img img = uploadImage(siteUrl,nbDays, fileName,bytearray);
if(img != null)
listener.fileUploaded(img);
}
}).start();
}
public Img uploadImage(String siteUrl, int nbDays, String fileName, byte[] byteArray) {
Log.v("Url",siteUrl);
//getData
URL url = null;
Img imgOutput = null;
try {
url = new URL(siteUrl);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpURLConnection conn = null;
InputStream stream = null;
DataOutputStream request = null;
try {
if(isConnectedToInternet(context))
{
String attachmentFileName = fileName;
String crlf = "\r\n";
String hyphens = "--";
String boundary = "------------------------dd8a045fcc22b35c";
conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
String location = conn.getHeaderField("Location");
if(location != null) {
siteUrl = location;
url = new URL(location);
}
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent", "Gobelim");
// conn.setFixedLengthStreamingMode(byteArray.length);
// conn.setChunkedStreamingMode(0);
conn.setInstanceFollowRedirects(true);
//conn.set
conn.setRequestProperty("Expect", "100-continue");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
request = new DataOutputStream(conn.getOutputStream());
request.writeBytes(hyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"format\"" + crlf);
request.writeBytes(crlf);
request.writeBytes("json" + crlf);
request.writeBytes(hyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"delete-day\"" + crlf);
request.writeBytes(crlf);
request.writeBytes(nbDays + crlf);
request.writeBytes(hyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + attachmentFileName + "\"" + crlf);
request.writeBytes("Content-Type: application/octet-stream" + crlf);
request.writeBytes(crlf);
request.flush();
request.write(byteArray);
request.writeBytes(crlf);
request.writeBytes(hyphens + boundary + hyphens + crlf);
request.flush();
stream = conn.getInputStream();
}
} catch (IOException e1) {
e1.printStackTrace();
listener.fileUploadError("Network Error");
}
/******************************************************************************/
if(stream != null) {
InputStreamReader isr = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(isr);
boolean isReading = true;
String data;
String jsonStr = "";
do {
try {
data = br.readLine();
if (data != null)
jsonStr += data;
else
isReading = false;
} catch (IOException e) {
e.printStackTrace();
isReading = false;
}
} while (isReading);
//parseJSon
try {
request.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("after read answer");
System.out.println(jsonStr);
try {
JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
JSONObject msg = rootObject.getJSONObject("msg"); // Get the element object
if(msg.has("msg")) {
String error = msg.getString("msg");
listener.fileUploadError(error);
return null;
}
else if(msg.has("short")) {
String hashOutput = msg.getString("short");
String realHashOutput = msg.getString("real_short");
imgOutput = new Img(0, siteUrl, hashOutput, realHashOutput, Calendar.getInstance(), nbDays, null);
}
} catch (JSONException e) {
// JSON Parsing error
e.printStackTrace();
listener.fileUploadError("JSON Unreadable");
}
}
return imgOutput;
}
private boolean isConnectedToInternet(Context context)
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null)
{
State networkState = networkInfo.getState();
if (networkState.equals(State.CONNECTED))
{
return true;
}
}
return false;
}
}
\ No newline at end of file
package fr.mobdev.gobelim.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import fr.mobdev.gobelim.Database;
import fr.mobdev.gobelim.objects.Img;
import fr.mobdev.gobelim.R;
public class HistoryActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
ListView historyList = (ListView) findViewById(R.id.history_list);
final List<Img> images = Database.getInstance(getApplicationContext()).getHistory();
HistoryAdapter adapter = new HistoryAdapter(this,R.layout.history_item,R.id.url_history_item,images);
historyList.setAdapter(adapter);
historyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent linkIntent = new Intent(HistoryActivity.this,LinkActivity.class);
if(position < images.size()) {
Img image = images.get(position);
linkIntent.putExtra("URL", image.getUrl());
linkIntent.putExtra("short", image.getShortHash());
startActivity(linkIntent);
}
}
});
}
private class HistoryAdapter extends ArrayAdapter<Img>
{
private List<Img> images;
private LayoutInflater mInflater;
int resource;
public HistoryAdapter(Context context, int resource, int textViewResourceId, List<Img> objects) {
super(context, resource, textViewResourceId, objects);
images = new ArrayList(objects);
this.resource = resource;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
Img image = images.get(position);
if (convertView == null) {
convertView = mInflater.inflate(resource, parent, false);
}
TextView urlView = (TextView) convertView.findViewById(R.id.url_history_item);
String url = image.getUrl();
if(!url.endsWith("/"))
url+="/";
url+=image.getShortHash();
urlView.setText(url);
//display date
TextView dateView = (TextView) convertView.findViewById(R.id.date);
Calendar date = image.getDate();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
df.setTimeZone(TimeZone.getDefault());
String dateString = df.format(date.getTime());
dateView.setText(dateString);
//display durationLastDay
TextView durationView = (TextView) convertView.findViewById(R.id.duration);
int storageDuration = image.getStorageDuration();
if(storageDuration == 0) {
durationView.setText(getString(R.string.no_duration));
}
else {
Calendar today = Calendar.getInstance();
long millis = today.getTimeInMillis() - date.getTimeInMillis();
long days = millis / (24*60*60*1000);
if(storageDuration - days < 0) {
durationView.setText(getString(R.string.duration_ended));
}
else {
if(storageDuration - days == 1)
durationView.setText(storageDuration - days +" "+ getString(R.string.day));
else
durationView.setText(storageDuration - days +" "+ getString(R.string.days));
}
}
ImageView thumb = (ImageView) convertView.findViewById(R.id.thumbnail);
if(image.getThumb() != null)
thumb.setImageBitmap(image.getThumb());
return convertView;
}
}
}
package fr.mobdev.gobelim.activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.content.ClipboardManager;
import android.widget.Toast;
import fr.mobdev.gobelim.R;
public class LinkActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.link);
Intent receiveIntent = getIntent();
String url = receiveIntent.getStringExtra("URL");
String shortHash = receiveIntent.getStringExtra("short");
if(!url.endsWith("/"))
url = url.concat("/");
url = url.concat(shortHash);
final String sharedUrl = url;
ImageButton shareButton = (ImageButton) findViewById(R.id.share_button);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sharedUrl);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
ImageButton copyClipboardButton = (ImageButton) findViewById(R.id.copy_clipboard_button);
copyClipboardButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied URL", sharedUrl);
clipboard.setPrimaryClip(clip);
Toast.makeText(LinkActivity.this,getString(R.string.copy_to_clipboard),Toast.LENGTH_SHORT).show();
}
});
TextView link = (TextView) findViewById(R.id.link);
link.setText(sharedUrl);
}
}
This diff is collapsed.
package fr.mobdev.gobelim.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;