diff --git a/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java b/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java index 2bf9ee7..4d5887a 100644 --- a/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java +++ b/src/it/reyboz/bustorino/backend/ArrivalsFetcher.java @@ -1,50 +1,52 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; // "arrivals" è più usato di "transit" o simili, e chi sono io per mettermi a dibattere con gli inglesi? +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; public interface ArrivalsFetcher extends Fetcher { // /** // * Reads arrival times from a (hopefully) real-time source, e.g. the GTT website. // * Don't call this in UI thread! // * // * @param stopID stop ID, in normalized form. // * @param routeID route ID, in normalized form. // * @param res result code (will be set by this method) // * @return arrival times // * @see it.reyboz.bustorino.backend.Fetcher.result // * @see FiveTNormalizer // */ // Palina ReadArrivalTimesRoute(String stopID, String routeID, AtomicReference res); /** * Reads arrival times from a (hopefully) real-time source, e.g. the GTT website. * Don't call this in UI thread! * * @param stopID stop ID, in normalized form. * @param res result code (will be set by this method) * @return arrival times * @see it.reyboz.bustorino.backend.Fetcher.result * @see FiveTNormalizer */ Palina ReadArrivalTimesAll(String stopID, AtomicReference res); } diff --git a/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java b/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java index 1dd7833..ba9682e 100644 --- a/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java +++ b/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java @@ -1,188 +1,275 @@ +/* + BusTO - Backend components + Copyright (C) 2018 Fabio Mazza + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ package it.reyboz.bustorino.backend; import android.support.annotation.Nullable; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Hashtable; +import java.util.*; import java.util.concurrent.atomic.AtomicReference; -public class FiveTAPIFetcher implements ArrivalsFetcher { +public class FiveTAPIFetcher implements ArrivalsFetcher{ private static final String SECRET_KEY="759C97DC7D115966C30FD9169BB200D9"; private static final String DEBUG_NAME = "FiveTAPIFetcher"; + final static LinkedList apiDays = new LinkedList<>(Arrays.asList("dom","lun","mar","mer","gio","ven","sab")); + @Override public Palina ReadArrivalTimesAll(String stopID, AtomicReference res) { //set the date for the request as now Palina p = new Palina(stopID); //request parameters String response = performAPIRequest(QueryType.ARRIVALS,stopID,res); if(response==null){ //an error has occured, details in res.get() return p; } /* Slight problem: "longName": ==> DESCRIPTION "name": "13N", "departures": [ { "arrivalTimeInt": 1272, "time": "21:12", "rt": false }] "lineType": "URBANO" ==> URBANO can be either bus or tram or METRO */ JSONArray arr; try{ arr = new JSONArray(response); String type; Route.Type routetype; for(int i =0; i getDirectionsForStop(String stopID, AtomicReference res) { + + String response = performAPIRequest(QueryType.DETAILS,stopID,res); + if(response == null) return null; + ArrayList routes = new ArrayList<>(10); + + try { + JSONArray lines =new JSONArray(response); + for(int i=0; i 1) { + String secondo = exploded[exploded.length-2]; + if (secondo.contains("festivo")) { + festivo = 1; + } else if (secondo.contains("feriale")) { + festivo = 0; + } else if(secondo.contains("lun. - ven")) { + serviceDays = Route.reduced_week; + } else if(secondo.contains("sab - fest.")){ + serviceDays = Route.weekend; + festivo = 1; + } else { + Log.d(DEBUG_NAME,"Parsing details of line "+lineName+" branchid "+branchid+":\n\t"+ + "Couldn't find a the service days\n"+ + "Description: "+secondo+","+description + ); + } + if(exploded.length>2){ + switch (exploded[exploded.length-3].trim()) { + case "bus": + t = Route.Type.BUS; + break; + case "tram": + //never happened, but if it could happen you can get it + t = Route.Type.TRAM; + break; + default: + //nothing + } + + } + } + if(lineName.trim().equals("10")|| lineName.trim().equals("15")) t= Route.Type.TRAM; + Route r = new Route(lineName.trim(),direction.trim(),t,null); + if(serviceDays.length>0) r.serviceDays = serviceDays; + r.festivo = Route.FestiveInfo.returnTypefromCode(festivo); + r.branchid = branchid; + r.description = description.trim(); + r.setStopsList(Arrays.asList(stops.split(","))); + + routes.add(r); + res.set(result.OK); + } + } catch (JSONException e) { + res.set(result.PARSER_ERROR); + e.printStackTrace(); + return null; + } + return routes; + } + /** * Create and perform the network request. This method adds parameters and returns the result * @param t type of request to be performed * @param stopID optional parameter, stop ID which you need for passages and branches * @param res result container * @return a String which contains the result of the query, to be parsed */ @Nullable - static String performAPIRequest(QueryType t,@Nullable String stopID, AtomicReference res){ + public static String performAPIRequest(QueryType t,@Nullable String stopID, AtomicReference res){ Date d = new Date(); URL u; Hashtable param = new Hashtable<>(); try { String address = getURLForOperation(t,stopID); + //Log.d(DEBUG_NAME,"The address to query is: "+address); param.put("TOKEN",getAccessToken(address,d)); param.put("TIMESTAMP",String.valueOf(d.getTime())); param.put("Accept-Encoding","gzip"); param.put("Connection","Keep-Alive"); u = new URL(address); } catch (UnsupportedEncodingException | NoSuchAlgorithmException |MalformedURLException e) { e.printStackTrace(); res.set(result.PARSER_ERROR); return null; } String response = networkTools.queryURL(u,res,param); if(response==null) { if(res.get()==result.SERVER_ERROR_404) { Log.w(DEBUG_NAME,"Got 404, either the server failed, or the stop was not found, or the hack is not working anymore"); res.set(result.EMPTY_RESULT_SET); }; } return response; } /** * Get the Token needed to access the API * @param URL the URL of the request * @return token * @throws NoSuchAlgorithmException if the system doesn't support MD5 * @throws UnsupportedEncodingException if we made mistakes in writing utf-8 */ - static String getAccessToken(String URL,Date d) throws NoSuchAlgorithmException,UnsupportedEncodingException{ + private static String getAccessToken(String URL,Date d) throws NoSuchAlgorithmException,UnsupportedEncodingException{ MessageDigest md = MessageDigest.getInstance("MD5"); String strippedQuery = URL.replace("http://www.5t.torino.it/proxyws",""); //return the time in milliseconds long timeMilli = d.getTime(); StringBuilder sb = new StringBuilder(); sb.append(strippedQuery); sb.append(timeMilli); sb.append(SECRET_KEY); String stringToBeHashed = sb.toString(); + //Log.d(DEBUG_NAME,"Hashing string: "+stringToBeHashed); md.reset(); byte[] data = md.digest(stringToBeHashed.getBytes("UTF-8")); sb = new StringBuilder(); for (byte b : data){ sb.append(String.format("%02x",b)); } String result = sb.toString(); - Log.d(DEBUG_NAME,"getting token:\n\treduced URL: "+strippedQuery+"\n\ttimestamp: "+timeMilli+"\nTOKEN:"+result.toLowerCase()); + //Log.d(DEBUG_NAME,"getting token:\n\treduced URL: "+strippedQuery+"\n\ttimestamp: "+timeMilli+"\nTOKEN:"+result.toLowerCase()); return result.toLowerCase(); } /** * Get the right url for the operation you are doing, to be fed into the queryURL method * @param t type of operation * @param stopID stop on which you are working on * @return the Url to go to * @throws UnsupportedEncodingException if it cannot be converted to utf-8 */ public static String getURLForOperation(QueryType t,@Nullable String stopID) throws UnsupportedEncodingException { final StringBuilder sb = new StringBuilder(); sb.append("http://www.5t.torino.it/proxyws/ws2.1/rest/stops/"); switch (t){ case ARRIVALS: sb.append(URLEncoder.encode(stopID,"utf-8")); sb.append("/departures"); break; case DETAILS: sb.append(URLEncoder.encode(stopID,"utf-8")); sb.append("/branches/details"); break; - case STOPS: + case STOPS_ALL: sb.append("all"); break; case STOPS_VERSION: sb.append("version"); break; } return sb.toString(); } + + enum QueryType { - ARRIVALS, DETAILS,STOPS, STOPS_VERSION + ARRIVALS, DETAILS,STOPS_ALL, STOPS_VERSION } } diff --git a/src/it/reyboz/bustorino/backend/Palina.java b/src/it/reyboz/bustorino/backend/Palina.java index 015faed..5421703 100644 --- a/src/it/reyboz/bustorino/backend/Palina.java +++ b/src/it/reyboz/bustorino/backend/Palina.java @@ -1,234 +1,289 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; -import android.support.annotation.NonNull; - import java.util.ArrayList; +import java.util.Calendar; import java.util.Collections; import java.util.List; /** * Timetable for multiple routes.
*
* Apparently "palina" and a bunch of other terms can't really be translated into English.
* Not in a way that makes sense and keeps the code readable, at least. */ public class Palina extends Stop { private ArrayList routes = new ArrayList<>(); public Palina(String stopID) { super(stopID); } /** * Adds a route to the timetable. * * @param routeID name * @param type bus, underground, railway, ... * @param destinazione end of line\terminus (underground stations have the same ID for both directions) * @return array index for this route */ public int addRoute(String routeID, String destinazione, Route.Type type) { this.routes.add(new Route(routeID, destinazione, type, new ArrayList(6))); return this.routes.size() - 1; // last inserted element and pray that direct access to ArrayList elements really is direct } public int addRoute(Route r){ this.routes.add(r); return this.routes.size()-1; } /** * Adds a timetable entry to a route. * * @param TimeGTT time in GTT format (e.g. "11:22*") * @param arrayIndex position in the array for this route (returned by addRoute) */ public void addPassaggio(String TimeGTT, int arrayIndex) { this.routes.get(arrayIndex).addPassaggio(TimeGTT); } /** * Count routes with missing directions * @return number */ public int countRoutesWithMissingDirections(){ int i = 0; for (Route r : routes){ if(r.destinazione==null||r.destinazione.equals("")) i++; } return i; } // /** // * Clears a route timetable (or creates an empty route) and returns its index // * // * @param routeID name // * @param destinazione end of line\terminus // * @return array index for this route // */ // public int updateRoute(String routeID, String destinazione) { // int s = this.routes.size(); // RouteInternal r; // // for(int i = 0; i < s; i++) { // r = routes.get(i); // if(r.name.compareTo(routeID) == 0 && r.destinazione.compareTo(destinazione) == 0) { // // capire se è possibile che ci siano stessa linea e stessa destinazione su 2 righe diverse del sito e qui una sovrascrive l'altra (probabilmente no) // r.updateFlag(); // r.deletePassaggio(); // return i; // } // } // // return this.addRoute(routeID, destinazione); // } // // /** // * Deletes routes marked as "not updated" (= disappeared from the GTT website\API\whatever). // * Sets all remaining routes to "not updated" because that's how this contraption works. // */ // public void finishUpdatingRoutes() { // RouteInternal r; // // for(Iterator itr = this.routes.iterator(); itr.hasNext(); ) { // r = itr.next(); // if(r.unupdateFlag()) { // itr.remove(); // } // } // } // /** // * Gets the current timetable for a route. Returns null if the route doesn't exist. // * This is slower than queryRouteByIndex. // * // * @return timetable (passaggi) // */ // public List queryRoute(String routeID) { // for(Route r : this.routes) { // if(routeID.equals(r.name)) { // return r.getPassaggi(); // } // } // // return null; // } // // /** // * Gets the current timetable for this route, from its index in the array. // * // * @return timetable (passaggi) // */ // public List queryRouteByIndex(int index) { // return this.routes.get(index).getPassaggi(); // } /** * Gets every route and its timetable. * * @return routes and timetables. */ public List queryAllRoutes() { return this.routes; } public void sortRoutes() { Collections.sort(this.routes); } + public int addInfoFromRoutes(List additionalRoutes){ + if(routes == null || routes.size()==0) { + this.routes = new ArrayList<>(additionalRoutes); + return routes.size(); + } + int count=0; + for(Route r:routes) { + int j = 0; + boolean correct = false; + Route selected = null; + while (!correct) { + while (j < additionalRoutes.size() && !r.name.equals(additionalRoutes.get(j).name)) { + j++; + } + if (j == additionalRoutes.size()) break; //no match has been found + //should have found the first occurrence of the line + selected = additionalRoutes.get(j); + + Calendar c = Calendar.getInstance(); + int to = c.get(Calendar.DAY_OF_WEEK); + + if (selected.serviceDays != null && selected.serviceDays.length > 0) { + //check it is in service + for (int d : selected.serviceDays) { + if (d == to) { + correct = true; + break; + } + } + } else if (r.festivo != null) { + switch (r.festivo) { + case FERIALE: + //Domenica = 1 --> Saturday=7 + if (to <= 7 && to > 1) correct = true; + break; + case FESTIVO: + if (to == 1) correct = true; //TODO: implement way to recognize all holidays + break; + case UNKNOWN: + correct = true; + } + } else { + //case a: there is no info because the line is always active + //case b: there is no info because the information is missing + correct = true; + } + } + if (correct == false || selected == null) continue; //we didn't find any match, should we point it out? + //found the correct correspondance + //MERGE INFO + + if(r.mergeRouteWithAnother(selected)) count++; + } + return count; + } + // /** // * Route with terminus (destinazione) and timetables (passaggi), internal implementation. // * // * Contains mostly the same data as the Route public class, but methods are quite different and extending Route doesn't really work, here. // */ // private final class RouteInternal { // public final String name; // public final String destinazione; // private boolean updated; // private List passaggi; // // /** // * Creates a new route and marks it as "updated", since it's new. // * // * @param routeID name // * @param destinazione end of line\terminus // */ // public RouteInternal(String routeID, String destinazione) { // this.name = routeID; // this.destinazione = destinazione; // this.passaggi = new LinkedList<>(); // this.updated = true; // } // // /** // * Adds a time (passaggio) to the timetable for this route // * // * @param TimeGTT time in GTT format (e.g. "11:22*") // */ // public void addPassaggio(String TimeGTT) { // this.passaggi.add(new Passaggio(TimeGTT)); // } // // /** // * Deletes al times (passaggi) from the timetable. // */ // public void deletePassaggio() { // this.passaggi = new LinkedList<>(); // this.updated = true; // } // // /** // * Sets the "updated" flag to false. // * // * @return previous state // */ // public boolean unupdateFlag() { // if(this.updated) { // this.updated = false; // return true; // } else { // return false; // } // } // // /** // * Sets the "updated" flag to true. // * // * @return previous state // */ // public boolean updateFlag() { // if(this.updated) { // return true; // } else { // this.updated = true; // return false; // } // } // // /** // * Exactly what it says on the tin. // * // * @return times from the timetable // */ // public List getPassaggi() { // return this.passaggi; // } // } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/Route.java b/src/it/reyboz/bustorino/backend/Route.java index ad48be7..bb1ca23 100644 --- a/src/it/reyboz/bustorino/backend/Route.java +++ b/src/it/reyboz/bustorino/backend/Route.java @@ -1,140 +1,258 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.support.annotation.NonNull; import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; import java.util.List; public class Route implements Comparable { + final static int[] reduced_week = {Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY}; + final static int[] feriali = {Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY,Calendar.SATURDAY}; + final static int[] weekend = {Calendar.SUNDAY,Calendar.SATURDAY}; + final static int BRANCHID_MISSING = -1; + public final String name; - public final String destinazione; + public String destinazione; public final List passaggi; public final Type type; - public final String description; + public String description; + //ordered list of stops, from beginning to end of line + private List stopsList = null; + public int branchid = BRANCHID_MISSING; + public int[] serviceDays ={}; + //0=>feriale, 1=>festivo -2=>unknown + public FestiveInfo festivo = FestiveInfo.UNKNOWN; + public enum Type { // "long distance" sono gli extraurbani. BUS, LONG_DISTANCE_BUS, METRO, RAILWAY, TRAM } + public enum FestiveInfo{ + FESTIVO(1),FERIALE(0),UNKNOWN(-2); + + private int code; + FestiveInfo(int code){ + this.code = code; + } + + public int getCode() { + return code; + } + public static FestiveInfo returnTypefromCode(int i){ + switch (i){ + case -2: + return UNKNOWN; + case 0: + return FERIALE; + case 1: + return FESTIVO; + default: + return UNKNOWN; + } + } + } + /** * Constructor. * * @param name route ID * @param destinazione terminus\end of line * @param type bus, long distance bus, underground, and so on * @param passaggi timetable, a good choice is an ArrayList of size 6 * @see Palina Palina.addRoute() method */ public Route(String name, String destinazione, Type type, List passaggi) { this.name = name; this.destinazione = destinazione; this.passaggi = passaggi; this.type = type; this.description = null; } /** * Constructor used by the new Api * @param name stop Name * @param t optional type * @param description line rough description */ public Route(String name,Type t,String description){ this.name = name; this.type = t; this.passaggi = new ArrayList<>(); this.destinazione = null; this.description = description; } /** * Exactly what it says on the tin. * * @return times from the timetable */ public List getPassaggi() { return this.passaggi; } + public void setStopsList(List stopsList) { + this.stopsList = Collections.unmodifiableList(stopsList); + } + public List getStopsList(){ + return this.stopsList; + } + /** * Adds a time (passaggio) to the timetable for this route * * @param TimeGTT time in GTT format (e.g. "11:22*") */ public void addPassaggio(String TimeGTT) { this.passaggi.add(new Passaggio(TimeGTT)); } public static String getPassageString(String input,boolean realtime){ String time = input.trim(); if(time.contains("*")){ if(realtime) return time; else return time.substring(0,time.length()-1); } else{ if(realtime) return time.concat("*"); else return time; } } @Override public int compareTo(@NonNull Route other) { int res; int thisAsInt, otherAsInt; // sorting by numbers alone yields a far more "natural" result (36N goes before 2024, 95B next to 95, and the like) thisAsInt = networkTools.failsafeParseInt(this.name.replaceAll("[^0-9]", "")); otherAsInt = networkTools.failsafeParseInt(other.name.replaceAll("[^0-9]", "")); // compare. - // numeric route IDs + // numeric route IDs (names) if(thisAsInt != 0 && otherAsInt != 0) { res = thisAsInt - otherAsInt; if(res != 0) { return res; } } else { // non-numeric res = this.name.compareTo(other.name); if (res != 0) { return res; } } // try comparing their destination if(this.destinazione!=null){ res = this.destinazione.compareTo(other.destinazione); if(res != 0) { return res; } } + //compare the lines + if(this.stopsList!=null && other.stopsList!=null){ + int d = this.stopsList.size()-other.stopsList.size(); + if(d!=0) return d; + else { + //the two have the same number of stops + + } + } // probably useless, but... last attempt. if(this.type != other.type) { // ordinal() is evil or whatever, who cares. return this.type.ordinal() - other.type.ordinal(); } return 0; } + + public boolean isBranchIdValid(){ + return branchid!=BRANCHID_MISSING; + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Route){ + Route r = (Route) obj; + boolean result = false; + if(this.name.equals(r.name) && this.branchid == r.branchid){ + if(this.stopsList!=null && r.stopsList!=null){ + int d = this.stopsList.size()-r.stopsList.size(); + if(d!=0) { + result = false; + } else { + result = true; + for(int j=0; j. */ package it.reyboz.bustorino.middleware; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.util.Log; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.*; import it.reyboz.bustorino.fragments.FragmentHelper; import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.atomic.AtomicReference; /** * This should be used to download data, but not to display it */ public class AsyncDataDownload extends AsyncTask{ private static final String TAG = "BusTO-DataDownload"; private boolean failedAll = false; private AtomicReference res; private RequestType t; private String query; WeakReference helperRef; public AsyncDataDownload(RequestType type,FragmentHelper fh) { t = type; helperRef = new WeakReference<>(fh); res = new AtomicReference<>(); } @Override protected Object doInBackground(String... params) { RecursionHelper r; boolean success=false; Object result; switch (t){ case ARRIVALS: r = new RecursionHelper<>(new ArrivalsFetcher[] {new FiveTAPIFetcher(),new GTTJSONFetcher(), new FiveTScraperFetcher()}); break; case STOPS: r = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); break; default: //TODO put error message cancel(true); return null; } FragmentHelper fh = helperRef.get(); //If the FragmentHelper is null, that means the activity doesn't exist anymore if (fh == null){ return null; } //Log.d(TAG,"refresh layout reference is: "+fh.isRefreshLayoutReferenceTrue()); while(r.valid()) { if(this.isCancelled()) { return null; } //get the data from the fetcher switch (t){ case ARRIVALS: ArrivalsFetcher f = (ArrivalsFetcher) r.getAndMoveForward(); Stop lastSearchedBusStop = fh.getLastSuccessfullySearchedBusStop(); Palina p; + String stopID; if(params.length>0) - p = f.ReadArrivalTimesAll(params[0],res); //(it's a Palina) + stopID=params[0]; //(it's a Palina) else if(lastSearchedBusStop!=null) - p = f.ReadArrivalTimesAll(lastSearchedBusStop.ID,res); //(it's a Palina) + stopID = lastSearchedBusStop.ID; //(it's a Palina) else { publishProgress(Fetcher.result.QUERY_TOO_SHORT); return null; } + p= f.ReadArrivalTimesAll(stopID,res); publishProgress(res.get()); //Try to find the name of the stop inside StopsDB fh.openStopsDB(); if(p.getStopDisplayName() == null){ p.setStopName(fh.getStopNamefromDB(p.ID)); } fh.closeDBIfNeeded(); + if(f instanceof FiveTAPIFetcher){ + AtomicReference gres = new AtomicReference<>(); + List branches = ((FiveTAPIFetcher) f).getDirectionsForStop(params[0],gres); + if(res.get() == Fetcher.result.OK){ + p.addInfoFromRoutes(branches); + } + //put updated values into Database + } //TODO: use ContentProvider when ready /* if(lastSearchedBusStop != null && res.get()== Fetcher.result.OK) { // check that we don't have the same stop if(!lastSearchedBusStop.ID.equals(p.ID)) { // remove it, get new name getNameOrGetRekt(); } else { // searched and it's the same String sn = lastSearchedBusStop.getStopDisplayName(); if(sn == null) { // something really bad happened, start from scratch getNameOrGetRekt(); } else { // "merge" Stop over Palina and we're good to go p.mergeNameFrom(lastSearchedBusStop); } } } else if(res.get()== Fetcher.result.OK) { // we haven't searched anything yet getNameOrGetRekt(); } */ result = p; Log.d(TAG,"Using the ArrivalsFetcher: "+f.getClass()); //TODO: find a way to avoid overloading the user with toasts break; case STOPS: StopsFinderByName finder = (StopsFinderByName) r.getAndMoveForward(); List resultList= finder.FindByName(params[0], this.res); //it's a List fh.openStopsDB(); for (Stop stop : resultList){ if(stop.location == null) stop.location = fh.getLocationFromDB(stop); stop.setRoutesThatStopHere(fh.getStopRoutesFromDB(stop.ID)); } fh.closeDBIfNeeded(); Log.d(TAG,"Using the StopFinderByName: "+finder.getClass()); query =params[0]; result = resultList; //dummy result break; default: result = null; } //find if it went well if(res.get()== Fetcher.result.OK) { return result; } } //at this point, we are sure that the result has been negative failedAll=true; return null; } @Override protected void onProgressUpdate(Fetcher.result... values) { FragmentHelper fh = helperRef.get(); if (fh!=null) for (Fetcher.result r : values){ //TODO: make Toast fh.showErrorMessage(r); } else { Log.w(TAG,"We had to show some progress but activity was destroyed"); } } @Override protected void onPostExecute(Object o) { FragmentHelper fh = helperRef.get(); if(failedAll || o == null || fh == null){ //everything went bad if(fh!=null) fh.toggleSpinner(false); cancel(true); return; } switch (t){ case ARRIVALS: Palina palina = (Palina) o; fh.createOrUpdateStopFragment(palina); break; case STOPS: //this should never be a problem List stopList = (List) o; if(query!=null) fh.createFragmentFor(stopList,query); else Log.e(TAG,"QUERY NULL, COULD NOT CREATE FRAGMENT"); break; case DBUPDATE: break; } } @Override protected void onCancelled() { FragmentHelper fh = helperRef.get(); if (fh!=null) fh.toggleSpinner(false); } @Override protected void onPreExecute() { FragmentHelper fh = helperRef.get(); if (fh!=null) fh.toggleSpinner(true); } public enum RequestType { ARRIVALS,STOPS,DBUPDATE } /** * Run this in a background thread.
* Sets a stop name for this.palina, guaranteed not to be null! **/ //TODO:Implement this /* private void getNameOrGetRekt(Palina p) { String nameMaybe; SQLiteDatabase udb = uDB.getReadableDatabase(); // does it already have a name (for fetchers that support it, or already got from favorites)? nameMaybe = p.getStopDisplayName(); if(nameMaybe != null && nameMaybe.length() > 0) { return; } // ok, let's search favorites. String usernameMaybe = UserDB.getStopUserName(udb, this.p.ID); if(usernameMaybe != null && usernameMaybe.length() > 0) { p.setStopUserName(usernameMaybe); return; } // let's try StopsDB, then. db.openIfNeeded(); nameMaybe = db.getNameFromID(this.p.ID); db.closeIfNeeded(); if(nameMaybe != null && nameMaybe.length() > 0) { p.setStopName(nameMaybe); return; } // no name to be found anywhere, don't bother searching it next time p.setStopName(""); }*/ }