package com.ved.musicmapapp.providers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.provider.Settings.Secure; import android.util.Log; import android.widget.RemoteViews; import com.ved.musicmapapp.MainActivity; import com.ved.musicmapapp.R; import com.ved.musicmapapp.Objects.LocalSong; import com.ved.musicmapapp.receiver.ProcessSyncingReceiver; import com.ved.musicmapapp.utils.LogFile; import com.ved.musicmapapp.utils.Statics; public class PostSongToServerTask extends AsyncTask<Void, Object, Boolean> { private static int BATCH_COUNT = 10; public int cleanedSongs = 0; // private static int NOTIFICATION_ID = 2014; public static String TAG = "HOCKEY_TEST"; public Context context; private String fbjson, fbid, device_id; public static ArrayList<LocalSong> exists = new ArrayList<LocalSong>(); public ArrayList<LocalSong> adds, dels; public static ArrayList<LocalSong> sPhones; // private JSONObject superJO; private int user_id = 0; private SharedPreferences prefs; private Editor edt; private boolean hasData = false, finished = false; // private boolean isAlreadySycning = false; /* * private Notification notification; private NotificationManager * mNotificationManager; */ private CleanSongTask[] cleanSongTasks; private LogFile logFile; private boolean doPosting = false; public PostSongToServerTask(Context context, boolean doPosting) { super(); Log.i("check","In PostSongToServerTask"); prefs = context.getSharedPreferences("MUSIC_MAP", Context.MODE_PRIVATE); edt = prefs.edit(); this.context = context; this.fbjson = prefs.getString("FB_JSON", ""); this.fbid = prefs.getString("FB_ID", ""); this.device_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); logFile = new LogFile(LogFile.TEMP_FOLDER + "/music_app_log.log"); this.doPosting = doPosting; TAG = "SyncSongTask"; } @Override protected void onPreExecute() { finished = false; context.sendBroadcast(new Intent(ProcessSyncingReceiver.BROAST_CAST_START_SYNCING)); } public void saveInSharedPreference(String key,String value){ edt.putString(key, value); edt.commit(); } protected Boolean doInBackground(Void... params) { exists.clear(); sPhones = getAllSongFromPhone(); saveInSharedPreference("sPhones", String.valueOf(sPhones.size())); if (prefs.getBoolean("IS_FIRST_TIME", true)) { syncSong(); while (!finished) { syncSong(); } } else { while (!finished) { syncSong(); } } return hasData; } private void getSongExit() { InputStream instream = null; try { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 20000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 20000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(Statics.WS_PATH + "getSongExist.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("fbid", fbid)); nvps.add(new BasicNameValuePair("fbusername", prefs.getString( "FB_USERNAME", ""))); nvps.add(new BasicNameValuePair("device_id", device_id)); nvps.add(new BasicNameValuePair("fbjson", fbjson)); String data = prefs.getString("DATA_UPLOAD", ""); boolean condition = false; try { new JSONObject(data).get("data"); condition = true; } catch (JSONException e) { e.printStackTrace(); } logFile.saveLog("GET SONG EXIT - DATA", data); if (data.length() > 0 && condition) { nvps.add(new BasicNameValuePair("data", data)); } httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httppost); edt.putString("DATA_UPLOAD", ""); edt.commit(); /* * */ HttpEntity entity = response.getEntity(); if (entity != null) { // get the response content as a string instream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(instream, "UTF-8")); String line; StringBuilder sb1 = new StringBuilder(""); while ((line = reader.readLine()) != null) { sb1.append(line + "\n"); } // publishProgress(0, sb1); Log.d(TAG, "DATA FROM GET SONG EXIST: " + sb1); // JSONObject jsonObject = new JSONObject(sb1.toString().trim()); user_id = Integer.parseInt(jsonObject.getString("userid") .toString().trim()); edt.putString("FB_USERNAME", jsonObject.getString("fbusername")); edt.putInt("USER_ID", user_id); edt.commit(); JSONArray songarray = jsonObject.getJSONArray("songs"); for (int i = 0; i < songarray.length(); i++) { LocalSong s = new LocalSong(); JSONObject song = songarray.getJSONObject(i); s.setTitle(song.getString("title")); s.setTitleEdited(song.getString("title_cleaned")); s.setArtist(song.getString("artist")); s.setArtistEdited(song.getString("artist_cleaned")); s.setDeleted(song.getBoolean("deleted")); exists.add(s); } Log.e("check", "exists size://" + exists.size()); saveInSharedPreference("sExists", String.valueOf(exists.size())); logFile.saveLog("GET SONG EXIT - RESPONE", sb1.toString()); // UPDATE USER ID } } catch (UnsupportedEncodingException e1) { Log.e("Exception", "" + e1.getMessage()); logFile.saveLog("GET SONG EXIT - ERROR", e1.getMessage()); // e1.printStackTrace(); } catch (ClientProtocolException e1) { Log.e("ClientProtocolException", "" + e1.getMessage()); logFile.saveLog("GET SONG EXIT - ERROR", e1.getMessage()); // e1.printStackTrace(); } catch (IOException e1) { Log.e("IOException", "" + e1.getMessage()); logFile.saveLog("GET SONG EXIT - ERROR", e1.getMessage()); // e1.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (instream != null) { try { instream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private void syncSong() { cleanedSongs = 0; try { adds = new ArrayList<LocalSong>(); dels = new ArrayList<LocalSong>(); if (!Statics.isNetworkConnected(context)) { finished = true; return; } if (exists.size() == 0) { getSongExit(); } else { user_id = prefs.getInt("USER_ID", 0); } // TODO RETURN IF NOT GET ID if (user_id < 1) { Log.d(TAG, "Could not get User's ID!"); publishProgress(0, "Could not get User's ID!"); finished = true; return; } if(!doPosting){ finished = true; return; } // VARIABLE CONTAIN JSON DATA JSONObject superJO = new JSONObject(); JSONObject dataJO = new JSONObject(); JSONObject userJO = new JSONObject(); try { userJO.put("id", user_id); userJO.put("email", "nvngoc@sdc.ud.edu.vn"); } catch (Exception e) { } // VARIABLE CHECK SONG EXIST boolean hasbreak = false; int x = 0; Log.d("MUSIC", sPhones.size() + ""); for (; x < sPhones.size(); x++) { LocalSong s1 = sPhones.get(x); if (this.isCancelled()) { finished = true; return; } Log.d("MUSIC", x + " : " + s1.getTitle()); // if (adds.size() >= BATCH_COUNT && prefs.getBoolean("IS_FIRST_TIME", true)) // break; boolean exist = false; for (LocalSong s2 : exists) { if (s1.getTitle().trim().equals(s2.getTitle().trim())) { if (s2.isDeleted()) { // Exist but deleted s1.setDeleted(true); s1.setTitleEdited(s2.getTitleEdited()); s1.setArtistEdited(s2.getArtistEdited()); } else { // Exist and using exist = true; } break; } } if (!exist) { adds.add(s1); } } if (x >= sPhones.size()) finished = true; /** * DEL */ for (LocalSong s3 : exists) { boolean exist = false; if (s3.isDeleted()) continue; for (LocalSong s4 : sPhones) { if (s3.getTitle().trim().equals(s4.getTitle().trim())) { exist = true; break; } } if (!exist) { dels.add(s3); } } // Clean song JSONArray addJA = new JSONArray(); cleanSongTasks = new CleanSongTask[CleanSongTask.STEP]; for (int i = 0; i < cleanSongTasks.length; i++) { cleanSongTasks[i] = new CleanSongTask(this, addJA, i); cleanSongTasks[i].execute(); } while (!isCleanFinished() && !this.isCancelled()) { if (null == context || !Statics.isNetworkConnected(context)) { hasbreak = true; // break; } } for (CleanSongTask task : cleanSongTasks) { if (task != null && !(task.getStatus() == Status.FINISHED)) { task.cancel(true); task = null; } } logFile.saveLog("CLEAN_SONG_TASK", "ADD: " + addJA.length()); // DEL JSONArray delJA = new JSONArray(); for (int i = 0; i < dels.size(); i++) { LocalSong s = dels.get(i); JSONObject delJO = new JSONObject(); try { delJO.put("title", s.getTitle()); delJO.put("artist", s.getArtist()); } catch (Exception e) { } // ADD TO ARRAY delJA.put(delJO); } try { dataJO.put("user", userJO); dataJO.put("sAdd", addJA); dataJO.put("sDel", delJA); superJO.put("data", dataJO); } catch (Exception e) { } Log.d("NEW_DATA", superJO.toString()); logFile.saveLog("CLEAN_SONG_TASK", "DELETE: " + dels.size()); int add = adds.size(), del = dels.size(); if (add == 0 && del == 0) { Intent intent = new Intent( ProcessSyncingReceiver.BROAST_CAST_RELOAD); context.sendBroadcast(intent); MainActivity.isSync = true; return; } // neu thay doi thi xoa // exists.clear(); // publishProgress(0, "Just found " + add + " new song(s) and " + // del // + " deleted song(s)."); if (hasbreak) { publishProgress(0, "Your data will be updated when Network Signal is better."); } // UPLOADING DATA Intent i = new Intent( ProcessSyncingReceiver.BROAST_CAST_UPDATE_SYNCING); i.putExtra("message", "Uploading data..."); context.sendBroadcast(i); InputStream instream2 = null; // TODO UPLOAD DATA if (null != context && Statics.isNetworkConnected(context)) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Statics.WS_PATH + "sync_song.php"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("data", superJO.toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8)); logFile.saveLog("UPLOADING_DATA", superJO.toString()); Log.e("check", ""+"uploading:///"+superJO.toString()); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null && (add > 0 || del > 0)) { // get the response content as a string instream2 = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(instream2, "UTF-8")); String line; StringBuilder sb = new StringBuilder(""); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } logFile.saveLog("UPLOAD_RESPONE", sb.toString()); JSONObject job = new JSONObject(sb.toString()); boolean rl = job.getBoolean("reload"); if (rl) { publishProgress(2); // onReload Intent intent = new Intent( ProcessSyncingReceiver.BROAST_CAST_RELOAD); context.sendBroadcast(intent); } if (!hasData) { hasData = rl; } } edt.putString("DATA_UPLOAD", ""); edt.commit(); MainActivity.isSync = true; } catch (IOException e) { logFile.saveLog("UPLOADED_DATA - ERROR", e.getMessage()); } catch (JSONException e) { logFile.saveLog("UPLOADED_DATA - ERROR", e.getMessage()); e.printStackTrace(); } finally { if (instream2 != null) instream2.close(); } } else { edt.putString("DATA_UPLOAD", superJO.toString()); edt.commit(); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onProgressUpdate(Object... values) { // Statics.showToast(context.getBaseContext(), // values[0]+" added, "+values[1]+" deleted"); int type = Integer.parseInt(values[0].toString()); if (type == 0) { // Notification try { Statics.showToast(context, values[1].toString()); } catch (Exception e) { } } else if (type == 2) { // Reload onReloadData(); } } public boolean isCleanFinished() { if (cleanSongTasks != null) { for (CleanSongTask task : cleanSongTasks) { if (task.curPosition < adds.size()) { return false; } } } return true; } protected void onPostExecute(Boolean result) { // isAlreadySycning = false; Intent i = new Intent(ProcessSyncingReceiver.BROAST_CAST_STOP_SYNCING); i.putExtra("HAS_DATA", hasData); context.sendBroadcast(i); } public void onReloadData() { }; public ArrayList<LocalSong> getAllSongFromPhone() { final ArrayList<LocalSong> songs = new ArrayList<LocalSong>(); String where = "is_music != 0 and _data not like '%amr' and _data not like '%ogg'"; Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI; // new File("").getT String[] cursor_cols = { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DISPLAY_NAME }; // Internal Cursor cursor; if (prefs.getBoolean("IS_FIRST_TIME", true)) { cursor = context.getContentResolver().query(uri, cursor_cols, where, null, MediaStore.Audio.Media.TITLE + " LIMIT 0, 10"); } else { cursor = context.getContentResolver().query(uri, cursor_cols, where, null, null); } fetchSongs(songs, cursor); uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; try { cursor = context.getContentResolver().query(uri, cursor_cols, where, null, null); fetchSongs(songs, cursor); } catch (Exception e) { publishProgress(0, "Could not get song from External SD Card!"); } // External // publishProgress(0, songs.size()); Log.e("check","Current songs count ://" + songs.size()); return songs; } private void fetchSongs(ArrayList<LocalSong> songs, Cursor cursor) { while (cursor.moveToNext()) { String title = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); title = title.replaceAll("\"", " "); boolean exist = false; for (LocalSong s : songs) { if (s.getTitle().trim().toLowerCase() .equals(title.trim().toLowerCase())) { exist = true; break; } } if (exist) continue; String artist = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); artist = artist.replaceAll("\"", " "); artist = artist.replace('\'', ' '); artist = artist.replace(',', '&'); artist = artist.replaceAll("[^a-zA-Z 0-9],_", " "); if (artist.length() == 0) artist = "<unknown>"; String album = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)); album = album.replaceAll("\"", " "); album = album.replace('\'', ' '); album = album.replaceAll("[^a-zA-Z 0-9],_", " "); String artist_cleaned = artist; if (!artist_cleaned.equals("<unknown>")) { artist_cleaned = cleanSongArtist(artist_cleaned); } String title_cleaned = cleanSongTrack(title, artist_cleaned); if (artist_cleaned.length() > 0 && title_cleaned.length() > 0) { songs.add(new LocalSong(-1, title, title_cleaned, artist,artist_cleaned, album, 0, 0,"<unknown>")); } } } private String cleanSongArtist(String str) { while (str.contains("(") && str.contains(")")) { int start = -1, end = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(' && start == -1) start = i; if (str.charAt(i) == ')') { end = i; break; } } if (end > start) str = str.replace(str.substring(start, end + 1), ""); } while (str.contains("[") && str.contains("]")) { int start = -1, end = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '[' && start == -1) start = i; if (str.charAt(i) == ']') { end = i; break; } } if (end > start) str = str.replace(str.substring(start, end + 1), ""); } while (str.contains("{") && str.contains("}")) { int start = -1, end = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '{' && start == -1) start = i; if (str.charAt(i) == '}') { end = i; break; } } if (end > start) str = str.replace(str.substring(start, end + 1), ""); } String tmp = str.toLowerCase(); if (tmp.contains("www.")) { int start = tmp.indexOf("www."), end = tmp.length() - 1; for (int i = start; i < tmp.length(); i++) { if (tmp.charAt(i) == ' ') { end = i; break; } } if (end > start) { str = str.replace(str.substring(start, end + 1), ""); tmp = str.toLowerCase(); } } // str = AccentRemover.toUrlFriendly(str); str = str.replaceAll("[~!@#$%^&*()_+:;\"?><,./=`]", " "); // trim() while (str.contains(" ")) { str = str.replace(" ", " "); } int i = 0, start = -1; for (; i < str.length(); i++) { if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { if (start == -1) start = i; } else if (start > 0 && i > start && (str.charAt(i) == ' ' || str.charAt(i) == '-')) { String s = str.substring(start, i); str = str.replace(s, ""); i -= s.length(); start = -1; } else { start = -1; } } if (start > 0 && i == str.length()) { str = str.replace(str.substring(start), ""); } str = str.replaceAll(" - ", " "); while (str.contains("--")) { str = str.replace("--", " "); } // trim() while (str.contains(" ")) { str = str.replace(" ", " "); } return str.trim(); } private String cleanSongTrack(String str, String artist) { while (str.contains("(") && str.contains(")")) { int start = -1, end = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(' && start == -1) start = i; if (str.charAt(i) == ')') { end = i; break; } } if (end > start) str = str.replace(str.substring(start, end + 1), ""); } while (str.contains("[") && str.contains("]")) { int start = -1, end = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '[' && start == -1) start = i; if (str.charAt(i) == ']') { end = i; break; } } if (end > start) str = str.replace(str.substring(start, end + 1), ""); } while (str.contains("{") && str.contains("}")) { int start = -1, end = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '{' && start == -1) start = i; if (str.charAt(i) == '}') { end = i; break; } } if (end > start) str = str.replace(str.substring(start, end + 1), ""); } // str = AccentRemover.toUrlFriendly(str); // artist = AccentRemover.toUrlFriendly(artist); Log.i("ARTIST", str + " " + artist); if (str.contains(artist)) { str = str.replaceAll(artist, " "); } String tmp = str.toLowerCase(); while (tmp.contains("www.")) { int start = tmp.indexOf("www."), end = tmp.length() - 1; for (int i = start; i < tmp.length(); i++) { if (tmp.charAt(i) == ' ') { end = i; break; } } if (end > start) { str = str.replace(str.substring(start, end + 1), ""); tmp = str.toLowerCase(); } } str = str.replaceAll("[~!@#$%^&*()_+:;\"?><,./=`]", " "); // trim() while (str.contains(" ")) { str = str.replace(" ", " "); } int i = 0, start = -1; for (; i < str.length(); i++) { if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { if (start == -1) start = i; } else if (start != -1 && i > start && (str.charAt(i) == ' ' || str.charAt(i) == '-')) { try { Character a = str.charAt(i + 1); Character b = str.charAt(i + 2); if ((a == 'a' || a == 'A' || a == 'p' || a == 'P') && (b == 'm' || b == 'M')) { start = -1; continue; } } catch (Exception e) { } String s = str.substring(start, i); str = str.replace(s, ""); i -= s.length(); start = -1; } else { start = -1; } } if (start > 0 && i == str.length()) { str = str.replace(str.substring(start), ""); } str = str.replaceAll("-", " "); // trim() while (str.contains(" ")) { str = str.replace(" ", " "); } return str.trim(); } private static Notification createSyncNotification(Context context) { Intent _intent = new Intent(context.getApplicationContext(), MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( context.getApplicationContext(), 0, _intent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.syncing_layout); remoteViews.setTextViewText(R.id.info, ""); remoteViews.setProgressBar(R.id.progress, 100, 0, true); Notification notif = new Notification(); // This is who should be launched if the user selects our notification. notif.contentIntent = pendingIntent; // In this sample, we'll use the same text for the ticker and the // expanded notification notif.tickerText = "Syncing in background..."; // the icon for the status bar notif.flags |= Notification.FLAG_ONGOING_EVENT; notif.contentView = remoteViews; return notif; } }