package com.ved.musicmapapp.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.widget.Toast; import com.google.android.gms.drive.internal.ar; import com.ved.musicmapapp.Objects.Artist; import com.ved.musicmapapp.Objects.FacebookFriend; import com.ved.musicmapapp.Objects.Genre; import com.ved.musicmapapp.Objects.Playlist; import com.ved.musicmapapp.Objects.PlaylistArSong; import com.ved.musicmapapp.Objects.PlaylistArtist; import com.ved.musicmapapp.Objects.Song; import com.ved.musicmapapp.Objects.User; import com.ved.musicmapapp.adapters.DBAdapter; public class Statics { public static final String ACTION_LOGOUT = "com.ved.musicmapapp.LogoutBroadcastReceiver"; public static int LIMIT_VIEW_COUNT = 60; // public static int EXPAND_VIEW_COUNT = 20; public static ArrayList<FacebookFriend> lstFriends; public static long serverTime; public static User curUser; // public static Artist dynamicArtist; // public static ArrayList<User> /* allUsers, youFollows, followYous, */ // globalUsers; public static int countUseApps; public static HashMap<String, User> hashUsers; public static ArrayList<Artist> likeDatas; public static boolean isFollowingLoaded = false; public static boolean isFollowersLoaded = false; public static boolean isWhoToFollowLoaded = false; public static int FOLLOW = 1; public static int UNFOLLOW = 0; public static int LIKE = 1; public static int DISLIKE = 0; // public static String artist_last_update = ""; public static String DATAPATH = "http://playlistr.me/"; // public static String DATAPATH = // "http://sdc.eduportal.vn/sdcdevelopment/musicmap/"; // public static String DATAPATH = "http://192.168.130.1:81/musicmap/"; public static String WS_PATH = DATAPATH + "webservices/"; public static final String WEB_APP_URL = "http://playlistr.me/web/"; public static String GCM_SENDER_ID = "679637134495"; public static String REGISTER_GCM_URL = WS_PATH + "registerGCM.php"; // public static HashMap<Integer,ArrayList<Playlist>> userPlaylists = new HashMap<Integer, ArrayList<Playlist>>(); public static void showToast(Context ctx, String text) { Toast.makeText(ctx, text, Toast.LENGTH_LONG).show(); } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { // InputStream is = new URL(url).openStream(); URL url1 = new URL(url); URLConnection con = url1.openConnection(); con.setConnectTimeout(8000); con.setReadTimeout(8000); InputStream is = con.getInputStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static boolean isNetworkConnected(Context context) { try { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.isConnected()) { return true; } } catch (Exception e) { } return false; } public static double distance(double lat1, double lon1, double lat2, double lon2, String unit) { double theta = lon1 - lon2; double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta)); dist = Math.acos(dist); dist = rad2deg(dist); double miles = dist * 60 * 1.1515; unit = unit.toUpperCase(); if (unit.equalsIgnoreCase("K")) { return (miles * 1.609344); } else if (unit.equalsIgnoreCase("N")) { return (miles * 0.8684); } else { return miles; } } public static boolean getBoolean(String value) { return value.equals("1"); } public static double deg2rad(double deg) { return Math.PI * deg / 180; } public static double rad2deg(double rad) { return 180 * rad / Math.PI; } public static void calculateTime(/* long milisec, */User u) { Calendar cur = Calendar.getInstance(); cur.setTimeInMillis(serverTime); if (u.getArtistcount() == 0) { u.setTypeUpdate(7); u.setLastUDString(""); return; } Calendar last = Calendar.getInstance(); last.setTimeInMillis(u.getLastArtistUpdateTime() * 1000); if (cur.get(Calendar.YEAR) == last.get(Calendar.YEAR)) { if (cur.get(Calendar.MONTH) == last.get(Calendar.MONTH)) { if (cur.get(Calendar.DAY_OF_MONTH) == last .get(Calendar.DAY_OF_MONTH)) { if (cur.get(Calendar.HOUR_OF_DAY) == last .get(Calendar.HOUR_OF_DAY)) { u.setTypeUpdate(1); u.setLastUDString("a few mins ago"); } else { int hours = cur.get(Calendar.HOUR_OF_DAY) - last.get(Calendar.HOUR_OF_DAY); u.setTypeUpdate(2); u.setValueTypeUpdate(hours); u.setLastUDString(hours + " hours ago"); } } else { int days = cur.get(Calendar.DAY_OF_MONTH) - last.get(Calendar.DAY_OF_MONTH); if (days == 1) { u.setTypeUpdate(3); u.setLastUDString("yesterday"); } else { u.setTypeUpdate(4); u.setValueTypeUpdate(days); u.setLastUDString(days + " days ago"); } } } else { int months = cur.get(Calendar.MONTH) - last.get(Calendar.MONTH); u.setTypeUpdate(5); u.setValueTypeUpdate(months); u.setLastUDString(months + " months ago"); } } else { int years = cur.get(Calendar.YEAR) - last.get(Calendar.YEAR); u.setTypeUpdate(6); u.setValueTypeUpdate(years); u.setLastUDString(years + " years ago"); } } /** * Convert JSON string to list user * * @param task * : AsyncTask which use this function * @param json * : string return from server * @param curFbid * : current user Facebook id * @param users * : current users list * @param follow_fbid * @return */ public static User getCurrentUserAndSaveRestInDB(String json, String curFbid, String follow_fbid, Context contx) { User followUser = null; int followYou = 0, youFollow = 0; Log.d("json", json); DBAdapter adapter = new DBAdapter(contx); try { JSONArray jArray = new JSONArray(json); for (int i = 0; i < jArray.length(); i++) { JSONObject job = jArray.getJSONObject(i); User u = getUserFromJSON(job); Log.i("User", u.getFullName()); User userTmp = hashUsers.get(u.getFbid()); if (userTmp != null) { userTmp.compareTo(u); hashUsers.put(u.getFbid(), userTmp); adapter.addUser(userTmp); } else { hashUsers.put(u.getFbid(), u); adapter.addUser(u); } if (null != follow_fbid && u.getFbid().equals(follow_fbid)) { followUser = u; } if (curFbid.equals(u.getFbid())) { // Current user Statics.curUser = u; } else { if (u.isFollowed()) { youFollow++; } if (u.isFollowMe()) { followYou++; } } } } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } if (null != curUser) { curUser.setTotalFollowYou(followYou); curUser.setTotalYouFollow(youFollow); } return followUser; } public static User getDataFromJSON(AsyncTask task, String json, String curFbid, ArrayList<User> users, String follow_fbid) { User followUser = null; int followYou = 0, youFollow = 0; if (null != users) { users.clear(); } else { // Statics.allUsers.clear(); // Statics.hashUsers.clear(); // Statics.youFollows.clear(); // Statics.followYous.clear(); } Log.d("json", json); try { JSONArray jArray = new JSONArray(json); for (int i = 0; i < jArray.length(); i++) { if (task != null && task.isCancelled()) { if (null != users) { users.clear(); } else { // Statics.allUsers.clear(); // Statics.hashUsers.clear(); // Statics.youFollows.clear(); // Statics.followYous.clear(); } break; } JSONObject job = jArray.getJSONObject(i); User u = getUserFromJSON(job); Log.i("User", u.getFullName()); if (null != users) { users.add(u); // hashUsers.put(u.getFbid(), u); try { User userTmp = hashUsers.get(u.getFbid()); if (userTmp != null) { userTmp.compareTo(u); hashUsers.put(u.getFbid(), userTmp); } else { hashUsers.put(u.getFbid(), u); } } catch (Exception ex) { } continue; } try { User userTmp = hashUsers.get(u.getFbid()); if (userTmp != null) { userTmp.compareTo(u); hashUsers.put(u.getFbid(), userTmp); } else { hashUsers.put(u.getFbid(), u); } } catch (Exception ex) { } if (null != follow_fbid && u.getFbid().equals(follow_fbid)) { followUser = u; } if (curFbid.equals(u.getFbid())) { // Current user try { Statics.curUser = u; } catch (Exception ex) { } } else { // Other user if (u.isFollowed()) { youFollow++; } if (u.isFollowMe()) { followYou++; } } } } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } if (null != users) { Collections.sort(users, new UserSort()); } if (null != curUser) { try { curUser.setTotalFollowYou(followYou); curUser.setTotalYouFollow(youFollow); } catch (Exception ex) { } } return followUser; } public static float similarText(String first, String second) { first = first.toLowerCase(); second = second.toLowerCase(); return (float) (similar(first, second) * 200) / (first.length() + second.length()); } private static int similar(String first, String second) { int p, q, l, sum; int pos1 = 0; int pos2 = 0; int max = 0; char[] arr1 = first.toCharArray(); char[] arr2 = second.toCharArray(); int firstLength = arr1.length; int secondLength = arr2.length; for (p = 0; p < firstLength; p++) { for (q = 0; q < secondLength; q++) { for (l = 0; (p + l < firstLength) && (q + l < secondLength) && (arr1[p + l] == arr2[q + l]); l++) ; if (l > max) { max = l; pos1 = p; pos2 = q; } } } sum = max; if (sum > 0) { if (pos1 > 0 && pos2 > 0) { sum += similar(first.substring(0, pos1 > firstLength ? firstLength : pos1), second.substring(0, pos2 > secondLength ? secondLength : pos2)); } if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) { sum += similar(first.substring(pos1 + max, firstLength), second.substring(pos2 + max, secondLength)); } } return sum; } public static int PixelFromDp(Context context, int dp) { return (int) (dp * context.getResources().getDisplayMetrics().density); } public static int DpFromPixel(Context context, int pixel) { return (int) (pixel / context.getResources().getDisplayMetrics().density); } public static ArrayList<User> getUsersFromJSON(String json) { ArrayList<User> users = new ArrayList<User>(); try { JSONArray jArray = new JSONArray(json); for (int i = 0; i < jArray.length(); i++) { JSONObject job = jArray.getJSONObject(i); users.add(getUserFromJSON(job)); } } catch (JSONException e) { e.printStackTrace(); } return users; } public static User getUserFromJSON(JSONObject json) throws JSONException { String fbid = json.getString("fbid"); serverTime = json.getLong("serverTime") * 1000; Log.i("getUserFromJSON", "json : " + json); User u = new User(); u.setID(json.getInt("id")); u.setFbid(fbid); u.setFirstName(json.getString("first_name")); u.setLastName(json.getString("last_name")); u.setFullName(json.getString("full_name")); u.setEmail(json.getString("email")); u.setBirthday(json.getString("birthday")); u.setCity(json.getString("city")); u.setCountry(json.getString("country")); u.setAddress(json.getString("address")); u.setLat(json.getDouble("lat")); u.setLon(json.getDouble("lon")); u.setAboutMe(json.getString("about_me")); u.setGender(json.getString("gender")); u.setReligion(json.getString("religion")); u.setDeviceId(json.getString("device_id")); u.setJoinDate(json.getLong("join_date")); u.setGcmRegId(json.getString("gcm_regid")); u.setUserName(json.getString("username")); u.setNoSong(json.getInt("noSong")); u.setArtistcount(json.getInt("artists_count")); u.setPercentage(json.getInt("percentage")); u.setFollowMe(json.getBoolean("followMe")); u.setFollowed(Statics.getBoolean(json.getString("followed"))); u.setStartFollow(json.getLong("startFollow")); u.setEndFollow(json.getLong("endFollow")); u.setNoLastAdd(json.getInt("noLastAdd")); try { u.setArtists(getArtistFromJSON(json, u.getID())); ArrayList<String> allGenres = new ArrayList<String>(); for(int i = 0;i<u.getArtists().size();i++){ Artist arts = u.getArtists().get(i); if(arts.getGenre() != null) { for(int j = 0;j<arts.getGenre().size();j++){ ArrayList<String> g = arts.getGenreNames(); for(String gg : g){ if(!allGenres.toString().toLowerCase().contains(gg.toLowerCase())) allGenres.add(Character.toUpperCase(gg.trim().charAt(0)) + gg.trim().substring(1)); } } } } u.setGenre(allGenres); } catch (Exception e) { // e.printStackTrace(); } try { u.setPlaylists(getPlaylistFromJSON(json.getString("playlists"))); } catch (Exception e) { // e.printStackTrace(); } try { u.setLastUpdate(json.getString("last_update")); } catch (JSONException e) { // Log.e("json", e.getMessage()); } try { u.setLastArtistUpdateTime(json.getLong("last_artist_update_time")); } catch (JSONException e) { // Log.e("json", e.getMessage()); } calculateTime(u); return u; } public static ArrayList<PlaylistArtist> getPlaylistArtistFromJSON(JSONObject json, int userID, int playlistId) throws JSONException { ArrayList<PlaylistArtist> artists = new ArrayList<PlaylistArtist>(); // Foreach Artists JSONArray jArts = json.getJSONArray("artists"); for (int j = 0; j < jArts.length(); j++) { JSONObject art = jArts.getJSONObject(j); PlaylistArtist a = new PlaylistArtist(); a.setID(art.getInt("id")); a.setName(art.getString("name_cleaned")); a.setAvatar(art.getString("avatar")); a.setGlobalPlaylist(art.getInt("globalPlaylist")); a.setLiked(Statics.getBoolean(art.getString("isLiked"))); a.setStartLike(art.getLong("startLike")); a.setEndLike(art.getLong("endLike")); a.setUserArtistId(art.getInt("user_artist_id")); a.setHasArtist(art.getBoolean("hasArtist")); a.setLatUpdate(art.getLong("last_update")); a.setPlaylistId(playlistId); ArrayList<PlaylistArSong> songs = new ArrayList<PlaylistArSong>(); // Foreach Songs JSONArray jSongs = art.getJSONArray("songs"); for (int k = 0; k < jSongs.length(); k++) { JSONObject js = jSongs.getJSONObject(k); PlaylistArSong s = new PlaylistArSong(); s.setID(js.getInt("id")); s.setTitle(js.getString("title")); s.setAlbum(js.getString("album")); try { String temp = js.getString("_7digital_buylink_us"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.setBuyLink(temp,"us"); } catch (Exception e) { s.setBuyLink(null,"us"); } try { String temp = js.getString("_7digital_id_us"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.set7DigigtalTrackId(temp,"us"); } catch (Exception e) { s.set7DigigtalTrackId(null,"us"); } try { String temp = js.getString("_7digital_buylink_gb"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.setBuyLink(temp,"gb"); } catch (Exception e) { s.setBuyLink(null,"gb"); } try { String temp = js.getString("_7digital_id_gb"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.set7DigigtalTrackId(temp,"gb"); } catch (Exception e) { s.set7DigigtalTrackId(null,"gb"); } s.setLiked(Statics.getBoolean(js.getString("isLiked"))); s.setStartLike(art.getLong("startLike")); s.setEndLike(art.getLong("endLike")); s.setHasSong(js.getBoolean("hasSong")); s.setUserId(userID); s.setAristitId(a.getID()); s.setPlaylistId(playlistId); // Add song to array songs.add(s); } // Add songs to artist a.setSongs(songs); // Add artist to array artists.add(a); } return artists; } public static ArrayList<Playlist> getPlaylistFromJSON(String json) { ArrayList <Playlist> playlists = new ArrayList<Playlist>(); JSONArray jsonArray; try { jsonArray = new JSONArray(json); for(int i = 0; i< jsonArray.length();i++){ JSONObject playlistJson = jsonArray.getJSONObject(i); int id = Integer.parseInt(playlistJson.getString("id")); String user_id = playlistJson.getString("user_id"); String playlist_name = playlistJson.getString("playlist_name"); long date_added = 0L; if(playlistJson.getString("date_added") != null && !playlistJson.getString("date_added").equals("null")) date_added = Long.parseLong(playlistJson.getString("date_added")); long last_updated = 0L; if(playlistJson.getString("last_updated") != null && !playlistJson.getString("last_updated").equals("null")) last_updated = Long.parseLong(playlistJson.getString("last_updated")); String artist_avatar = playlistJson.getString("artist_avatar"); int tracks = playlistJson.getInt("tracks"); Playlist playlist = new Playlist(id,user_id,playlist_name,date_added,last_updated,artist_avatar,tracks); playlists.add(playlist); } } catch (JSONException e) { e.printStackTrace(); } return playlists; } public static ArrayList<Genre> getGenreFromJSON(JSONArray json, int artistId,int userId,Artist artist){ ArrayList<Genre> genre = new ArrayList<Genre>(); ArrayList<String>temp = new ArrayList<String>(); try{ for (int j = 0; j < json.length(); j++) { JSONObject gen = json.getJSONObject(j); String genName = gen.getString("genre_name").trim(); // Log.e("check","genName from JSON: " + genName); if(genName.trim().equals("") || genName.trim().equals("<unknown>") || (genName.length() == 1)) continue; if(!temp.toString().toLowerCase().contains(genName.toLowerCase())){ temp.add(Character.toUpperCase(genName.trim().charAt(0)) + genName.trim().substring(1)); Genre genre2 = new Genre(artistId, genName,userId); genre.add(genre2); } } } catch(Exception e){ e.printStackTrace(); } if(temp.size() > 0) artist.setAllGenreNames(temp); return genre; } public static ArrayList<Artist> getArtistFromJSON(JSONObject json, int userID) throws JSONException { ArrayList<Artist> artists = new ArrayList<Artist>(); // Foreach Artists JSONArray jArts = json.getJSONArray("artists"); for (int j = 0; j < jArts.length(); j++) { JSONObject art = jArts.getJSONObject(j); Artist a = new Artist(); a.setID(art.getInt("id")); a.setName(art.getString("name")); a.setAvatar(art.getString("avatar")); a.setGlobalPlaylist(art.getInt("globalPlaylist")); a.setLiked(Statics.getBoolean(art.getString("isLiked"))); a.setStartLike(art.getLong("startLike")); a.setEndLike(art.getLong("endLike")); a.setUserArtistId(art.getInt("user_artist_id")); a.setHasArtist(art.getBoolean("hasArtist")); a.setLatUpdate(art.getLong("last_update")); ArrayList<Song> songs = new ArrayList<Song>(); // Foreach Songs JSONArray jSongs = art.getJSONArray("songs"); for (int k = 0; k < jSongs.length(); k++) { JSONObject js = jSongs.getJSONObject(k); Song s = new Song(); s.setID(js.getInt("id")); s.setTitle(js.getString("title")); s.setAlbum(js.getString("album")); try { String temp = js.getString("_7digital_buylink_us"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.setBuyLink(temp,"us"); } catch (Exception e) { s.setBuyLink(null,"us"); } try { String temp = js.getString("_7digital_id_us"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.set7DigigtalTrackId(temp,"us"); } catch (Exception e) { s.set7DigigtalTrackId(null,"us"); } try { String temp = js.getString("_7digital_buylink_gb"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.setBuyLink(temp,"gb"); } catch (Exception e) { s.setBuyLink(null,"gb"); } try { String temp = js.getString("_7digital_id_gb"); if (temp.length() == 0 || temp.equals("null")) temp = null; s.set7DigigtalTrackId(temp,"gb"); } catch (Exception e) { s.set7DigigtalTrackId(null,"gb"); } s.setLiked(Statics.getBoolean(js.getString("isLiked"))); s.setStartLike(art.getLong("startLike")); s.setEndLike(art.getLong("endLike")); s.setHasSong(js.getBoolean("hasSong")); s.setUserId(userID); s.setAristitId(a.getID()); // Add song to array songs.add(s); } // Add songs to artist a.setSongs(songs); a.setGenres(getGenreFromJSON(art.getJSONArray("genres"),art.getInt("id"),userID,a)); // Add artist to array artists.add(a); } Collections.sort(artists, new ArtistSortByDate()); return artists; } public static Artist getArtistFromPlaylistArtist(PlaylistArtist plArtist) { Artist a = new Artist(); a.setID(plArtist.getID()); a.setName(plArtist.getName()); a.setAvatar(plArtist.getAvatar()); a.setGlobalPlaylist(plArtist.getGlobalPlaylist()); a.setLiked(plArtist.isLiked()); a.setStartLike(plArtist.getStartLike()); a.setEndLike(plArtist.getEndLike()); a.setUserArtistId(plArtist.getUserArtistId()); a.setHasArtist(plArtist.isHasArtist()); a.setLatUpdate(plArtist.getLatUpdate()); ArrayList<Song> nSongs = new ArrayList<Song>(); ArrayList<PlaylistArSong> songs = plArtist.getSongs(); for(PlaylistArSong song : songs) { Song nSong = song; nSongs.add(nSong); } a.setSongs(nSongs); return a; } public static int getSelectedPlaylistSongCount(Playlist selectedPlaylist) { int songCount = 0; ArrayList<PlaylistArtist> atrists = selectedPlaylist.getArtists(); if(atrists != null) { for (PlaylistArtist artist : atrists) { ArrayList<PlaylistArSong> songs = artist.getSongs(); if(songs != null) { songCount+=songs.size(); } } } return songCount; } public static PlaylistArtist getArtistById(ArrayList<PlaylistArtist> artists, int artistId){ for(PlaylistArtist artist: artists) { if(artist.getID() == artistId) { return artist; } } return null; } }