//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.Activity; //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.util.Log; //import android.view.View; //import android.widget.RemoteViews; // //import com.ved.musicmapapp.MainActivity; //import com.ved.musicmapapp.R; //import com.ved.musicmapapp.Objects.LocalSong; //import com.ved.musicmapapp.utils.Statics; // //public class FirstSyncSongTask extends AsyncTask<Void, Object, Void> { // private static int BATCH_COUNT = 10; // public static ArrayList<LocalSong> sPhones; // public static boolean getSongOk; // // private Activity activity; // private String fbjson, fbid, device_id; // // private ArrayList<LocalSong> exists, adds, dels; // private int user_id = 0; // private SharedPreferences prefs; // private Editor edt; // private boolean hasData = false, finished = false; // // public FirstSyncSongTask(String fbjson, String fbid, String device_id, Activity activity) { // super(); // this.activity = activity; // this.fbjson = fbjson; // this.fbid = fbid; // this.device_id = device_id; // // prefs = activity.getSharedPreferences("MUSIC_MAP", Context.MODE_PRIVATE); // edt = prefs.edit(); // } // // @Override // protected void onPreExecute() { // sPhones = new ArrayList<LocalSong>(); // getSongOk = false; // } // // protected Void doInBackground(Void... params) { // // GET ALL SONG FROM THE PHONE // getAllSongFromPhone(); // getSongOk = true; // // syncSong(); // // return null; // } // // private void syncSong(){ // exists = new ArrayList<LocalSong>(); // adds = new ArrayList<LocalSong>(); // dels = new ArrayList<LocalSong>(); // try{ // if(!Statics.isNetworkConnected(activity)){ // finished = true; // return; // } // 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(); // } // // 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 // InputStream instream = entity.getContent(); // BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // String line; // StringBuilder sb = new StringBuilder(""); // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // // publishProgress(0, sb); // // try { // user_id = Integer.parseInt(sb.toString().trim()); // } catch (Exception e) { // JSONArray songarray = new JSONArray(sb.toString().trim()); // 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")); // user_id = song.getInt("user_id"); // exists.add(s); // } // } // // // } // } catch (UnsupportedEncodingException e1) { // Log.e("Exception", "" + e1.getMessage()); // //e1.printStackTrace(); // } catch (ClientProtocolException e1) { // Log.e("ClientProtocolException", "" + e1.getMessage()); // //e1.printStackTrace(); // } catch (IOException e1) { // Log.e("IOException", "" + e1.getMessage()); // //e1.printStackTrace(); // } catch (JSONException e) { // e.printStackTrace(); // } // // // TODO RETURN IF NOT GET ID // if(user_id < 1){ // onProgressUpdate(0, "Could not get User's ID!"); // finished = true; // return; // } // // // UPDATE USER ID // edt.putInt("USER_ID", user_id); // edt.commit(); // // // // 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; // // for (; x < sPhones.size(); x++) { // LocalSong s1 = sPhones.get(x); // if(this.isCancelled()){ // finished = true; // return; // } // if(adds.size() >= BATCH_COUNT) 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); // } // } // // // ADD // JSONArray addJA = new JSONArray(); // // for (int i = 0; i < adds.size(); i++) { // if(this.isCancelled()) { // finished = true; // return; // } // // LocalSong s = adds.get(i); // // // Break if no internet connection // if(null ==activity || !Statics.isNetworkConnected(activity)){ // hasbreak = true; // break; // } // // // if(!s.isDeleted()){ // cleanSongData(s); // } // // float percent = ((float)i/adds.size())*100; // publishProgress(1, (int)percent); // // JSONObject addJO = new JSONObject(); // try { // addJO.put("title", s.getTitle()); // addJO.put("title_edited", s.getTitleEdited()); // addJO.put("artist", s.getArtist()); // addJO.put("artist_edited", s.getArtistEdited()); // addJO.put("album", s.getAlbum()); // } catch (Exception e) {} // // // ADD TO ARRAY // addJA.put(addJO); // // } // // // // 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()); // // int add = adds.size(), del = dels.size(); // publishProgress(0, add +" - "+ del); //// if(add==0 && del==0) return null; // if(hasbreak){ // publishProgress(0, "Your data will be updated when Network Signal is better."); // } // // //TODO UPLOAD DATA // if(null != activity && Statics.isNetworkConnected(activity)){ // 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)); // // publishProgress(0, 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 // InputStream instream = entity.getContent(); // BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // String line; // StringBuilder sb = new StringBuilder(""); // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // // // JSONObject job = new JSONObject(sb.toString()); // boolean rl = job.getBoolean("reload"); // // publishProgress(0, sb.toString()); // // if(rl){ // publishProgress(2); // } // // if(!hasData){ // hasData = rl; // } // } // // edt.putString("DATA_UPLOAD", ""); // edt.commit(); // // //publishProgress(0, add+" added, "+del+" deleted"); // //hasData = true; // }catch (IOException e) { // // } catch (JSONException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // }else{ // edt.putString("DATA_UPLOAD", superJO.toString()); // edt.commit(); // } // } // // private void cleanSongData(LocalSong s) { // String artist_cleaned = s.getArtistEdited(); // String title_cleaned = s.getTitleEdited(); // // String artist = artist_cleaned.replace(" ", "%20"); // String title = title_cleaned.replace(" ", "%20"); // // if(artist.equals("<unknown>")){ // s.setAlbum(""); // JSONObject json; // try { // json = Statics.readJsonFromUrl("http://ws.audioscrobbler.com/2.0/?method=track.search&track="+title+"&api_key=7fcf89d40877011f8b3a8b1689a527a5&format=json&limit=1"); // JSONObject obj = json.getJSONObject("results").getJSONObject("trackmatches").getJSONObject("track"); // s.setArtistEdited(removeFt(obj.getString("artist"))); // s.setTitleEdited(obj.getString("name")); // } catch (Exception e) { // s.setArtistEdited(""); // s.setTitleEdited(title_cleaned); //// e.printStackTrace(); // } // // }else{ // JSONObject json; // try { // json = Statics.readJsonFromUrl("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=7fcf89d40877011f8b3a8b1689a527a5&artist="+artist+"&track="+title+"&autocorrect=1&format=json"); // JSONObject obj = json.getJSONObject("track"); // s.setArtistEdited(removeFt(obj.getJSONObject("artist").getString("name"))); // s.setTitleEdited(obj.getString("name")); // s.setAlbum(obj.getJSONObject("album").getString("title")); // } catch (Exception e) { //// e.printStackTrace(); // // s.setArtistEdited(removeFt(artist_cleaned)); // s.setTitleEdited(title_cleaned); // s.setAlbum(""); // } // // } // if(s.getAlbum().equals("<unknown>")) s.setAlbum(""); // if(s.getTitleEdited().length()==0) s.setTitleEdited(title_cleaned); // if(s.getArtistEdited().length()==0 || s.getArtistEdited().equals("[unknown]")) s.setArtistEdited("Unknown_Artist"); // } // // @Override // protected void onProgressUpdate(Object... values) { //// Statics.showToast(activity.getBaseContext(), values[0]+" added, "+values[1]+" deleted"); // int type = Integer.parseInt(values[0].toString()); // if(type == 0){ // Notification // try { // Statics.showToast(activity.getBaseContext(), values[1].toString()); // } catch (Exception e) {} // }else if(type == 1){ // Progress update // /*pd.setMessage("Loading "+values[1].toString()+"%...");*/ // }else if(type==2){ // Statics.showToast(activity.getBaseContext(), "All Playlists Refreshed!"); // onReloadData(); // } // // } // // protected void onPostExecute(Void result) { // //TODO // //mNotificationManager.cancel(NOTIFICATION_ID); // // try { // activity.findViewById(R.id.prog_syncing).setVisibility(View.GONE); // activity.findViewById(R.id.prog_syncing_nav).setVisibility(View.GONE); // activity.findViewById(R.id.imv_refresh).setVisibility(View.VISIBLE); // } catch (Exception e) {} // // onSuccess(hasData); // } // // public void onReloadData(){}; // // public void onSuccess(boolean hasData){} // // // private String removeFt(String str){ // String tmp = str.toLowerCase(); // if(tmp.contains(" ft ")){ // str = str.substring(0, tmp.indexOf(" ft ")); // } // // if(tmp.contains(" ft. ")){ // str = str.substring(0, tmp.indexOf(" ft. ")); // } // // tmp = str.toLowerCase(); // if(tmp.contains(" feat ")){ // str = str.substring(0, tmp.indexOf(" feat ")); // } // // tmp = str.toLowerCase(); // if(tmp.contains(" feat. ")){ // str = str.substring(0, tmp.indexOf(" feat. ")); // } // // tmp = str.toLowerCase(); // if(tmp.contains(" featuring ")){ // str = str.substring(0, tmp.indexOf(" featuring ")); // } // // return str.trim(); // } // // public void getAllSongFromPhone(){ // // 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 = activity.getContentResolver().query(uri, cursor_cols, where, null, null); // // fetchSongs(sPhones, cursor); // // // uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; // try { // cursor = activity.getContentResolver().query(uri, cursor_cols, where, null, null); // fetchSongs(sPhones, cursor); // // } catch (Exception e) { // publishProgress(0, "Could not get song from External SD Card!"); // } // // // // External // // publishProgress(0, sPhones.size()); // // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // try { // //((TextView)activity.findViewById(R.id.tvTotalSong)).setText("in the total "+sPhones.size()+" songs"); // } catch (Exception e) {} // } // }); // // // } // // private void fetchSongs(ArrayList<LocalSong> songs, Cursor cursor){ // while (cursor.moveToNext()) { // // // String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); // // // boolean exist = false; // for(LocalSong s:songs){ // if(s.getTitle().trim().toLowerCase().equals(title.trim().toLowerCase())){ // Log.i("TEST", title); // exist = true; // break; // } // } // if(exist) continue; // // String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); // 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.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)); // } // } // } // // 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; // } // //} // // //