Search in sources :

Example 1 with Alert

use of com.giua.objects.Alert in project Giua-App by Giua-app.

the class CheckNewsReceiver method checkAndSendNotificationForAgenda.

/**
 * Controlla e invia le notifiche riguardanti compiti e verifiche.
 *
 * @return La somma dei compiti e delle verifiche notificate. Serve a non far notificare anche gli avvisi.
 */
private int checkAndSendNotificationForAgenda() throws IOException {
    loggerManager.d("Inizio a controllare gli avvisi per le notifiche di compiti e verifiche");
    com.giua.utils.JsonParser jsonParser = new JsonParser();
    boolean canSendHomeworkNotification = SettingsData.getSettingBoolean(context, SettingKey.HOMEWORKS_NOTIFICATION);
    boolean canSendTestNotification = SettingsData.getSettingBoolean(context, SettingKey.TESTS_NOTIFICATION);
    if (!canSendTestNotification && !canSendHomeworkNotification)
        // Se non puo inviare nessuna notifica lo blocco
        return 0;
    loggerManager.d("Leggo il json per vedere gli avvisi dei compiti e delle verifiche già notificati");
    AlertsPage alertsPage = gS.getAlertsPage(false);
    File f = new File(context.getCacheDir() + "/alertsToNotify.json");
    if (!f.exists()) {
        createJsonNotificationFile(f, alertsPage);
        // Return perchè andrebbe a notificare tutti i vecchi compiti
        return 0;
    }
    BufferedReader file = new BufferedReader(new FileReader(context.getCacheDir() + "/alertsToNotify.json"));
    StringBuilder oldAlertsString = new StringBuilder();
    String read = file.readLine();
    if (read == null) {
        createJsonNotificationFile(f, alertsPage);
        return 0;
    }
    while (read != null) {
        oldAlertsString.append(read);
        read = file.readLine();
    }
    file.close();
    loggerManager.d("Faccio il parsing del json");
    // Lista con gli avvisi già notificati
    List<Alert> oldAlerts;
    if (oldAlertsString.toString().equals("")) {
        loggerManager.w("oldAlertsString è vuoto");
        oldAlerts = new Vector<>();
    } else
        oldAlerts = jsonParser.parseJsonForAlerts(oldAlertsString.toString());
    // Lista degli avvisi da notificare
    List<Alert> alertsToNotify = alertsPage.getAlertsToNotify(oldAlerts);
    // Salva gli avvisi (compresi i nuovi) nel json
    JsonBuilder jsonBuilder = new JsonBuilder(context.getCacheDir() + "/alertsToNotify.json", gS);
    jsonBuilder.writeAlerts(alertsPage.getAllAlertsWithFilters(false, "per la materia"));
    jsonBuilder.saveJson();
    loggerManager.d("Conto i compiti e le verifiche da notificare");
    // Conta i compiti da notificare
    int homeworkCounter = 0;
    // Conta le verifiche da notificare
    int testCounter = 0;
    // Lista in cui ci sono tutte le date dei compiti da notificare
    List<String> homeworkDates = new Vector<>(40);
    // Lista in cui ci sono tutte le date delle verifiche da notificare
    List<String> testDates = new Vector<>(40);
    // Lista in cui ci sono tutte le materie dei compiti da notificare
    List<String> homeworkSubjects = new Vector<>(40);
    // Lista in cui ci sono tutte le materie delle verifiche da notificare
    List<String> testSubjects = new Vector<>(40);
    for (Alert alert : alertsToNotify) {
        if (alert.object.startsWith("C")) {
            homeworkDates.add(alert.date);
            homeworkSubjects.add(alert.object.split(" per la materia ")[1]);
            homeworkCounter++;
        } else if (alert.object.startsWith("V")) {
            testDates.add(alert.date);
            testSubjects.add(alert.object.split(" per la materia ")[1]);
            testCounter++;
        }
    }
    loggerManager.d("Preparo le notifiche");
    StringBuilder homeworkNotificationText;
    StringBuilder testNotificationText;
    Notification homeworkNotification = null;
    Notification testNotification = null;
    if (canSendHomeworkNotification && homeworkCounter > 0) {
        String contentText;
        if (homeworkCounter == 1) {
            contentText = "Clicca per andare all' agenda";
            homeworkNotificationText = new StringBuilder("È stato programmato un nuovo compito di " + homeworkSubjects.get(0) + " per il giorno " + homeworkDates.get(0));
        } else {
            contentText = "Clicca per andare all' agenda";
            homeworkNotificationText = new StringBuilder("Sono stati programmati nuovi compiti:\n");
            for (int i = 0; i < homeworkCounter; i++) {
                homeworkNotificationText.append(homeworkSubjects.get(i));
                homeworkNotificationText.append(" - ");
                homeworkNotificationText.append(homeworkDates.get(i));
                if (i != homeworkCounter - 1)
                    homeworkNotificationText.append("\n");
            }
        }
        homeworkNotification = createNotificationForAgenda("Nuovi compiti", contentText, homeworkNotificationText.toString());
    }
    if (canSendTestNotification && testCounter > 0) {
        String contentText;
        if (testCounter == 1) {
            contentText = "Clicca per andare all' agenda";
            testNotificationText = new StringBuilder("È stata programmata una nuova verifica di " + testSubjects.get(0) + " per il giorno " + testDates.get(0));
        } else {
            contentText = "Clicca per andare all' agenda";
            testNotificationText = new StringBuilder("Sono state programmate nuove verifiche:\n");
            for (int i = 0; i < testCounter; i++) {
                testNotificationText.append(testSubjects.get(i));
                testNotificationText.append(" - ");
                testNotificationText.append(testDates.get(i));
                if (i != testCounter - 1)
                    testNotificationText.append("\n");
            }
        }
        testNotification = createNotificationForAgenda("Nuove verifiche", contentText, testNotificationText.toString());
    }
    loggerManager.d("Invio le notifiche");
    if (canSendHomeworkNotification && homeworkNotification != null)
        notificationManager.notify(13, homeworkNotification);
    if (canSendTestNotification && testNotification != null)
        notificationManager.notify(14, testNotification);
    return testCounter + homeworkCounter;
}
Also used : AlertsPage(com.giua.pages.AlertsPage) Notification(android.app.Notification) JsonBuilder(com.giua.utils.JsonBuilder) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Alert(com.giua.objects.Alert) JsonParser(com.giua.utils.JsonParser) File(java.io.File) Vector(java.util.Vector) JsonParser(com.giua.utils.JsonParser)

Example 2 with Alert

use of com.giua.objects.Alert in project Giua-App by Giua-app.

the class DBController method addAlerts.

public void addAlerts(List<Alert> alerts) {
    SQLiteDatabase db = getWritableDatabase();
    for (Alert alert : alerts) {
        addAlert(alert, db);
    }
    db.close();
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Alert(com.giua.objects.Alert)

Example 3 with Alert

use of com.giua.objects.Alert in project Giua-App by Giua-app.

the class AppNotifications method checkNewsForAlerts.

// endregion
// region Alerts
private void checkNewsForAlerts() {
    List<Alert> allNewAlerts;
    List<Alert> allNewAlertsOnSecondPage;
    try {
        allNewAlerts = gS.getAlertsPage(false).getAllAlerts(1);
        allNewAlertsOnSecondPage = gS.getAlertsPage(false).getAllAlerts(2);
    } catch (Exception e) {
        loggerManager.w("Controllo degli AVVISI in background non riuscito: " + e + " " + e.getMessage());
        return;
    }
    // In questa lista ci saranno gli avvisi dei compiti e delle verifiche che NON dovranno essere notificati
    List<Alert> testHomeworkAlerts = new Vector<>(10);
    List<Alert> allOldAlerts = notificationsDBController.readAlerts();
    notificationsDBController.replaceAlerts(allNewAlerts);
    notificationsDBController.addAlerts(allNewAlertsOnSecondPage);
    // Rimuovo gli avvisi vecchi da quelli nuovi
    allNewAlerts.removeAll(allOldAlerts);
    for (Alert alert : allNewAlerts) {
        if (alert.object.startsWith("V") || alert.object.startsWith("C"))
            testHomeworkAlerts.add(alert);
    }
    allNewAlerts.removeAll(testHomeworkAlerts);
    if (allNewAlerts.size() == 0 || allOldAlerts.get(0).page == -2)
        return;
    notificationManager.cancel(AppNotificationsParams.ALERTS_NOTIFICATION_ID);
    notificationManager.notify(AppNotificationsParams.ALERTS_NOTIFICATION_ID, createAlertsNotification(allNewAlerts));
    // DEBUG
    String s1 = "";
    for (Alert alert : allNewAlerts) {
        s1 += alert.getId() + "; ";
    }
    String s2 = "";
    for (Alert alert : allOldAlerts) {
        s2 += alert.getId() + "; ";
    }
    loggerManager.w("Notificati gli avvisi: " + s1);
    loggerManager.w("Avvisi vecchi: " + s2);
}
Also used : Alert(com.giua.objects.Alert) Vector(java.util.Vector) URISyntaxException(java.net.URISyntaxException) ParseException(java.text.ParseException) IOException(java.io.IOException)

Example 4 with Alert

use of com.giua.objects.Alert in project Giua-Webscraper by Giua-app.

the class AlertsPage method getAllAlerts.

/**
 * Ritorna una lista di {@code Alert} senza {@code details} e {@code creator}.
 * Per generare i dettagli {@link Alert#getDetails(GiuaScraper)}
 * ATTENZIONE: Utilizza una richiesta HTTP
 *
 * @param page La pagina da cui prendere gli avvisi. Deve essere maggiore di 0.
 * @return Lista di Alert
 * @throws IndexOutOfBoundsException Se {@code page} è minore o uguale a 0.
 */
public List<Alert> getAllAlerts(int page) throws IndexOutOfBoundsException {
    if (gS.isDemoMode()) {
        return GiuaScraperDemo.getAllAlerts();
    }
    if (page <= 0) {
        throw new IndexOutOfBoundsException("Un indice di pagina non puo essere 0 o negativo");
    }
    Document doc = gS.getPage(UrlPaths.ALERTS_PAGE + "/" + page);
    List<Alert> allAlerts = new Vector<>();
    Elements allAlertsHTML = doc.getElementsByTag("tbody");
    if (allAlertsHTML.isEmpty())
        return allAlerts;
    allAlertsHTML = allAlertsHTML.get(0).children();
    for (Element alertHTML : allAlertsHTML) {
        allAlerts.add(new Alert(alertHTML.child(0).text(), alertHTML.child(1).text(), alertHTML.child(2).text(), alertHTML.child(3).text(), alertHTML.child(4).child(0).attr("data-href"), page));
    }
    return allAlerts;
}
Also used : Element(org.jsoup.nodes.Element) Alert(com.giua.objects.Alert) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) Vector(java.util.Vector)

Example 5 with Alert

use of com.giua.objects.Alert in project Giua-App by Giua-app.

the class AlertsFragment method alertViewOnClick.

// region Listeners
private void alertViewOnClick(View view) {
    if (offlineMode) {
        alertViewOfflineOnClick(view);
        return;
    }
    pbLoadingPage.setVisibility(View.VISIBLE);
    GlobalVariables.gsThread.addTask(() -> {
        try {
            ((AlertView) view).alert.getDetails(GlobalVariables.gS);
            if (isFragmentDestroyed)
                return;
            activity.runOnUiThread(() -> {
                Alert alert = ((AlertView) view).alert;
                ((AlertView) view).markAsRead();
                TextView alertDetailsTextView = root.findViewById(R.id.alert_details_text_view);
                alertDetailsTextView.setText(Html.fromHtml(alert.details, 0));
                ((TextView) root.findViewById(R.id.alert_creator_text_view)).setText(alert.creator);
                ((TextView) root.findViewById(R.id.alert_type_text_view)).setText(alert.type);
                // Parsing per url nel html
                Linkify.addLinks(alertDetailsTextView, Linkify.WEB_URLS);
                attachmentLayout.removeAllViews();
                int urlsListLength = alert.attachmentUrls.size();
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(0, 20, 0, 0);
                for (int i = 0; i < urlsListLength; i++) {
                    TextView tvUrl = new TextView(requireActivity());
                    tvUrl.setText("Allegato " + (i + 1));
                    tvUrl.setTypeface(tvNoElements.getTypeface(), Typeface.NORMAL);
                    tvUrl.setBackground(ResourcesCompat.getDrawable(activity.getResources(), R.drawable.corner_radius_10dp, activity.getTheme()));
                    tvUrl.setBackgroundTintList(activity.getResources().getColorStateList(R.color.main_color, activity.getTheme()));
                    tvUrl.setPadding(20, 20, 20, 20);
                    tvUrl.setLayoutParams(params);
                    tvUrl.setTextColor(activity.getResources().getColorStateList(R.color.light_white_night_black, activity.getTheme()));
                    int finalI = i;
                    tvUrl.setOnClickListener((view2) -> downloadAndOpenFile(alert.attachmentUrls.get(finalI)));
                    attachmentLayout.addView(tvUrl);
                }
                detailsLayout.startAnimation(AnimationUtils.loadAnimation(requireActivity(), R.anim.visualizer_show_effect));
                detailsLayout.setVisibility(View.VISIBLE);
                obscureLayoutView.show();
                pbLoadingPage.setVisibility(View.GONE);
            });
        } catch (GiuaScraperExceptions.SiteConnectionProblems e) {
            activity.runOnUiThread(() -> {
                setErrorMessage(activity.getString(R.string.site_connection_error), root);
                finishedLoading();
                tvNoElements.setVisibility(View.VISIBLE);
            });
        } catch (GiuaScraperExceptions.YourConnectionProblems e) {
            activity.runOnUiThread(() -> {
                setErrorMessage(activity.getString(R.string.your_connection_error), root);
                finishedLoading();
                tvNoElements.setVisibility(View.VISIBLE);
            });
        } catch (GiuaScraperExceptions.MaintenanceIsActiveException e) {
            activity.runOnUiThread(() -> {
                setErrorMessage(activity.getString(R.string.maintenance_is_active_error), root);
                finishedLoading();
                tvNoElements.setVisibility(View.VISIBLE);
            });
        }
    });
}
Also used : Alert(com.giua.objects.Alert) TextView(android.widget.TextView) GiuaScraperExceptions(com.giua.webscraper.GiuaScraperExceptions) LinearLayout(android.widget.LinearLayout)

Aggregations

Alert (com.giua.objects.Alert)18 Vector (java.util.Vector)11 Cursor (android.database.Cursor)5 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 LinearLayout (android.widget.LinearLayout)3 IOException (java.io.IOException)3 TextView (android.widget.TextView)2 GiuaScraperExceptions (com.giua.webscraper.GiuaScraperExceptions)2 URISyntaxException (java.net.URISyntaxException)2 ParseException (java.text.ParseException)2 Document (org.jsoup.nodes.Document)2 Element (org.jsoup.nodes.Element)2 Elements (org.jsoup.select.Elements)2 Notification (android.app.Notification)1 AlertsPage (com.giua.pages.AlertsPage)1 JsonBuilder (com.giua.utils.JsonBuilder)1 JsonParser (com.giua.utils.JsonParser)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileReader (java.io.FileReader)1