commit f12fb1dabb1d8f921c64e73ba59d80ddde7efd43 Author: Cedric Hornberger Date: Fri Oct 16 14:53:37 2026 +0200 Initial commit: Tagesbyte prototype Flutter app that collects daily tech news from German and English RSS/Atom feeds, with a reader view, AI article summaries and daily briefings (Claude API or n8n webhook), paywall/sponsored filtering and ad/consent blocking. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..73181c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,65 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Windows +Thumbs.db +desktop.ini + +# Machine-specific editor settings (absolute paths) +.vscode/settings.json + +# Test coverage +coverage/ + +# Secrets and signing +.env +.env.* +*.keystore +*.jks +key.properties + +# Flutter version manager +.fvm/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..916bcca --- /dev/null +++ b/.metadata @@ -0,0 +1,39 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "edada7c56edf4a183c1735310e123c7f923584f1" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: edada7c56edf4a183c1735310e123c7f923584f1 + base_revision: edada7c56edf4a183c1735310e123c7f923584f1 + - platform: android + create_revision: edada7c56edf4a183c1735310e123c7f923584f1 + base_revision: edada7c56edf4a183c1735310e123c7f923584f1 + - platform: ios + create_revision: edada7c56edf4a183c1735310e123c7f923584f1 + base_revision: edada7c56edf4a183c1735310e123c7f923584f1 + - platform: web + create_revision: edada7c56edf4a183c1735310e123c7f923584f1 + base_revision: edada7c56edf4a183c1735310e123c7f923584f1 + - platform: windows + create_revision: edada7c56edf4a183c1735310e123c7f923584f1 + base_revision: edada7c56edf4a183c1735310e123c7f923584f1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f18257d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,13 @@ +## Agent skills + +### Issue tracker + +Issues live in Gitea at tea.zendric.de (Cedric/TagesByte), managed with the `tea` CLI. See `docs/agents/issue-tracker.md`. + +### Triage labels + +Default vocabulary: needs-triage, needs-info, ready-for-agent, ready-for-human, wontfix. See `docs/agents/triage-labels.md`. + +### Domain docs + +Single-context: one `GLOSSARY.md` and `docs/adr/` at the repo root. See `docs/agents/domain.md`. diff --git a/README.md b/README.md new file mode 100644 index 0000000..12765c8 --- /dev/null +++ b/README.md @@ -0,0 +1,197 @@ +# Tagesbyte + +Your daily tech news in bytes. A Flutter app that collects the day's tech news +from German and English RSS/Atom feeds and uses AI to summarize single articles +or write a daily briefing. It's meant to replace the n8n → Discord workflow. + +## Features (prototype) + +- **Today**: all articles from the enabled sources in the last 12/24/48 h, newest + first. Filter by language or source, pull to refresh. +- **Reading in the app**: tapping an article opens a clean **reader view** (text, + headings, lists, quotes, images) without ads or cookie banners. The globe icon + switches to the **original page** in an in-app WebView, for paywalls or sites + that block reader view. **Summarize with AI** uses the same downloaded text, so + the summary is based on the full article, not just the RSS teaser. Links in the + briefing open the same way. +- **Briefing**: AI picks the 6–10 most important stories of the day, merges + coverage from different outlets, and links every topic to its sources. Every + briefing is saved on the device (`briefings.json` in the app's private + storage); the history button lists them by month, tap to read, swipe to delete + (with undo). +- **Paid articles and ads hidden**: heise+ and Golem `(g+)` are recognized by + their title; SPIEGEL+ and t3n Pro by a marker in the article page, which the app + checks once per new article in the background (it reads only until the marker, + and remembers results for 14 days). Sponsored posts (`Anzeige:`) are hidden too. + The feed header shows how many were hidden; both filters can be turned off. +- **Ad and cookie-banner blocking** in the original-page view: requests to ~80 + ad/tracker hosts and the common consent managers (Sourcepoint, OneTrust, + consentmanager, Usercentrics, Didomi, Cookiebot, …) are blocked, and a + stylesheet hides leftover ad slots and banners. Nothing is accepted, so sites + treat it like a rejection. Golem redirects to a separate consent page instead + of showing a banner; with "Accept cookie walls" on (default), the app makes the + same request as Golem's own "Zustimmen" button (`/abo/setconsentcookie.php`, + valid for a day) and reuses the cookie for reader view and the in-app page. + With it off, the app shows the teaser and an "Open website anyway" option. +- **Sources**: 21 curated feeds (12 German, 9 English), toggle each one, or add any + RSS/Atom feed (it's validated before being added). +- **Dark mode**: System / Light / Dark in Settings (applies instantly). The + original-page view follows it too: when the phone is dark, sites use their own + dark design or Android darkens them; when only the app is dark, the app inverts + the page colours and keeps photos and videos as they are. +- **Settings**: AI provider (off / Claude API / n8n webhook), model, summary + language (German/English, whatever the source language), time window, paid/ad + filters, ad and cookie-banner blocking. + +## Running + +```bash +flutter pub get +flutter run # pick an Android emulator/device +flutter test # unit tests (parser, Claude request/response handling) +LIVE_FEEDS=1 flutter test test/live_feeds_test.dart # checks every real feed +``` + +Platform notes: + +- **Android / iOS**: work as-is (Android 6.0+). +- **Windows desktop**: requires Visual Studio with the "Desktop development with + C++" workload. Reader view works; "original page" opens the browser because + the WebView plugin has no Windows support. +- **Web**: browsers block cross-origin feed requests (CORS). Set a CORS proxy + prefix in Settings (only shown on web), or use the app on mobile/desktop. + +## AI setup + +### Option A: Claude API (direct) + +1. Create a key at . +2. Settings → AI summaries → **Claude API** → paste the key → Save. + +The key is stored in the platform keystore (`flutter_secure_storage`) and only +sent to `api.anthropic.com`. Model choices: + +| Model | Use it for | +|---|---| +| `claude-opus-5-5` (default) | Best briefing quality | +| `claude-sonnet-5-5` | Balanced cost and quality | +| `claude-haiku-5-5` | Cheapest; good enough for single-article summaries | + +Requests use low effort (summarizing is routine work) and, for the briefing, +structured JSON output so the result maps reliably to topics and links. On Opus +and Sonnet the app also enables Anthropic's server-side refusal fallback +(`fallbacks: "default"`): if a safety classifier declines a request, the API +retries it on a fallback model. + +> Shipping the app to other people with your key inside isn't safe. For +> personal use a key you entered yourself is fine; for distribution, route +> requests through your own backend (e.g. the n8n option below). + +### Option B: Your n8n workflow + +Settings → AI summaries → **n8n webhook** → enter the production URL of a +*Webhook* trigger node (method POST, "Respond: Using 'Respond to Webhook' node"). +The app sends JSON and expects JSON back. + +**Daily briefing** + +```jsonc +// Request +{ + "action": "daily_briefing", + "language": "de", // "de" | "en" + "articles": [ + { + "id": "a1", + "title": "…", + "url": "https://…", + "source": "heise online", + "language": "de", + "published": "2026-10-11T07:30:00.000Z", + "excerpt": "…" + } + ] +} + +// Response, option 1 (structured; topics link back to the articles) +{ + "intro": "One or two sentences on the day.", + "topics": [ + { "title": "…", "summary": "…", "article_ids": ["a1", "a7"] } + ] +} + +// Response, option 2 (plain text, e.g. your existing Discord message) +{ "text": "…" } +``` + +**Single article** + +```jsonc +// Request +{ + "action": "summarize_article", + "language": "de", + "article": { "title": "…", "url": "…", "source": "…", "published": "…", "text": "extracted article body" } +} + +// Response +{ "summary": "…" } // a plain-text body also works +``` + +Use a *Switch* node on `{{$json.body.action}}` to route the two cases to your +existing AI nodes. + +## News sources + +Every feed URL below was checked to load and parse. The ★ sources are enabled by +default. + +| | Source | Feed | Focus | +|---|---|---|---| +| 🇩🇪 ★ | heise online | `heise.de/rss/heise-atom.xml` | Broad IT news, high volume (~150/day) | +| 🇩🇪 ★ | Golem.de | `rss.golem.de/rss.php?feed=ATOM1.0` | IT news for professionals | +| 🇩🇪 ★ | t3n | `t3n.de/rss.xml` | Digital business, startups, AI | +| 🇩🇪 ★ | ComputerBase | `computerbase.de/rss/news.xml` | Hardware, software, gaming | +| 🇩🇪 | SPIEGEL Netzwelt | `spiegel.de/netzwelt/index.rss` | Mainstream news magazine view | +| 🇩🇪 | ZEIT Digital | `newsfeed.zeit.de/digital/index` | Digital policy and society | +| 🇩🇪 | netzpolitik.org | `netzpolitik.org/feed/` | Digital rights, privacy | +| 🇩🇪 | heise Security | `heise.de/security/rss/news-atom.xml` | Security vulnerabilities | +| 🇩🇪 | heise Developer | `heise.de/developer/rss/news-atom.xml` | Software development | +| 🇩🇪 | Caschys Blog | `stadt-bremerhaven.de/feed/` | Consumer tech, smartphones | +| 🇩🇪 | derStandard Web | `derstandard.at/rss/web` | Austrian daily's tech section | +| 🇩🇪 | Borns IT- und Windows-Blog | `borncity.com/blog/feed/` | Windows, patches, admin topics | +| 🇬🇧 ★ | The Verge | `theverge.com/rss/index.xml` | Consumer tech, policy | +| 🇬🇧 ★ | Ars Technica | `feeds.arstechnica.com/arstechnica/index` | In-depth tech and science | +| 🇬🇧 ★ | TechCrunch | `techcrunch.com/feed/` | Startups, funding | +| 🇬🇧 ★ | Hacker News | `news.ycombinator.com/rss` | Front page links | +| 🇬🇧 | MIT Technology Review | `technologyreview.com/feed/` | AI, biotech, climate | +| 🇬🇧 | WIRED | `wired.com/feed/rss` | Tech and culture | +| 🇬🇧 | Engadget | `engadget.com/rss.xml` | Gadgets | +| 🇬🇧 | The Register | `theregister.com/headlines.atom` | Enterprise IT | +| 🇬🇧 | BleepingComputer | `bleepingcomputer.com/feed/` | Security, malware | + +Reader view works for 20 of the 21 sources. ZEIT Digital blocks non-browser +requests, so the app shows the teaser and offers the original page. + +## Project layout + +``` +lib/ + main.dart App entry, theme + data/default_sources.dart Curated feed list + models/ Article, NewsSource, DailyBriefing, AppSettings + services/ + feed_parser.dart RSS 2.0 / RSS 1.0 / Atom parser, date parsing + feed_service.dart Parallel fetching, dedupe, time window + article_extractor.dart Article page → reader blocks + text for the AI + summarizer.dart Summarizer interface and shared prompt input + claude_summarizer.dart Claude Messages API over HTTP + n8n_summarizer.dart n8n webhook bridge + storage.dart Settings, sources, briefing persistence + paywall_service.dart Paid/sponsored detection (titles + page marker) + content_blocking.dart Ad/tracker/consent blocklists for the WebView + consent_service.dart Accepts consent walls (Golem) and keeps the cookies + state/app_state.dart ChangeNotifier holding app state + ui/ Screens (Today, Article, Briefing, Sources, Settings) +``` diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..1ee244c --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "de.dailytechnews.daily_tech_news" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "de.dailytechnews.daily_tech_news" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 23 // flutter_secure_storage needs Android 6.0+ + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..8669ffd --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/de/dailytechnews/daily_tech_news/MainActivity.kt b/android/app/src/main/kotlin/de/dailytechnews/daily_tech_news/MainActivity.kt new file mode 100644 index 0000000..2e52779 --- /dev/null +++ b/android/app/src/main/kotlin/de/dailytechnews/daily_tech_news/MainActivity.kt @@ -0,0 +1,5 @@ +package de.dailytechnews.daily_tech_news + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_background.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_background.png new file mode 100644 index 0000000..765d93a Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_background.png differ diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..1bdb7eb Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png new file mode 100644 index 0000000..52d3262 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_background.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_background.png new file mode 100644 index 0000000..8c28783 Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_background.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..d46fa96 Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png new file mode 100644 index 0000000..77c491e Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_background.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_background.png new file mode 100644 index 0000000..a912488 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_background.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..97f027b Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png new file mode 100644 index 0000000..5c4d1e0 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_background.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_background.png new file mode 100644 index 0000000..4d65e8f Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_background.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..db05061 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png new file mode 100644 index 0000000..e6ea842 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_background.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_background.png new file mode 100644 index 0000000..e86ab54 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_background.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..1a7a9ba Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png new file mode 100644 index 0000000..8c67c56 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_monochrome.png differ diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..407dab1 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..476fc6f Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..cf118f2 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..0afde87 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..db91090 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..81dc4e4 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..89176ef --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,21 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..f018a61 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac3b479 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..ab39a10 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,25 @@ +pluginManagement { + val flutterSdkPath = run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.7.3" apply false + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/assets/icon/background.png b/assets/icon/background.png new file mode 100644 index 0000000..3bbd175 Binary files /dev/null and b/assets/icon/background.png differ diff --git a/assets/icon/background.svg b/assets/icon/background.svg new file mode 100644 index 0000000..ef75c7c --- /dev/null +++ b/assets/icon/background.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/icon/foreground.png b/assets/icon/foreground.png new file mode 100644 index 0000000..90881b4 Binary files /dev/null and b/assets/icon/foreground.png differ diff --git a/assets/icon/foreground.svg b/assets/icon/foreground.svg new file mode 100644 index 0000000..defe8b5 --- /dev/null +++ b/assets/icon/foreground.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icon/icon.png b/assets/icon/icon.png new file mode 100644 index 0000000..409eb9c Binary files /dev/null and b/assets/icon/icon.png differ diff --git a/assets/icon/icon.svg b/assets/icon/icon.svg new file mode 100644 index 0000000..b6cc178 --- /dev/null +++ b/assets/icon/icon.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icon/make_icons.js b/assets/icon/make_icons.js new file mode 100644 index 0000000..f07ce80 --- /dev/null +++ b/assets/icon/make_icons.js @@ -0,0 +1,123 @@ +// Generates the Tagesbyte app icon sources (SVG) and PNG renders. +// Usage: npm install @resvg/resvg-js@2.6.2 && node make_icons.js assets/icon +// then: dart run flutter_launcher_icons +const fs = require('fs'); +const path = require('path'); +const { Resvg } = require('@resvg/resvg-js'); + +const out = process.argv[2]; +fs.mkdirSync(out, { recursive: true }); + +const BLUE = '#3355DD'; +const LINE = '#C9D3F7'; +const SPARK = '#FFB52E'; + +// Design space 1000x1000. A news page with a bite out of its top-right corner. +const page = { x: 290, y: 230, w: 420, h: 540, r: 52 }; +const corner = { x: page.x + page.w, y: page.y }; +// Two overlapping circles: together they remove the corner and leave a small +// cusp between them, which reads as a bite mark. +const biteCircles = [112, 158].map((deg) => { + const a = (deg * Math.PI) / 180; + return { cx: corner.x + 48 * Math.cos(a), cy: corner.y + 48 * Math.sin(a), r: 88 }; +}); + +const sparkle = (cx, cy, s) => + `M${cx},${cy - s} C${cx + s * 0.12},${cy - s * 0.12} ${cx + s * 0.12},${cy - s * 0.12} ${cx + s},${cy} ` + + `C${cx + s * 0.12},${cy + s * 0.12} ${cx + s * 0.12},${cy + s * 0.12} ${cx},${cy + s} ` + + `C${cx - s * 0.12},${cy + s * 0.12} ${cx - s * 0.12},${cy + s * 0.12} ${cx - s},${cy} ` + + `C${cx - s * 0.12},${cy - s * 0.12} ${cx - s * 0.12},${cy - s * 0.12} ${cx},${cy - s} Z`; + +const pageRect = (fill, extra = '') => + ``; + +const biteMask = (id) => ` + + + ${biteCircles.map((c) => ``).join('')} + `; + +// Headline bar, text lines and the AI sparkle on the page. +const contentShapes = (headline, line, spark) => ` + + + + + + `; + +function foreground(scale) { + const t = `translate(500 500) scale(${scale}) translate(-500 -500)`; + return ` + + ${biteMask('bite')} + + + + + + + + ${pageRect('#0B1460')} + + ${pageRect('#FFFFFF')} + ${contentShapes(BLUE, LINE, SPARK)} + `; +} + +const background = ` + + + + + + + `; + +const svg = (body) => + `${body}`; + +// Monochrome (Android 13 themed icons): page silhouette, content cut out. +const monochrome = svg(` + + ${biteMask('bite')} + + + ${contentShapes('#000', '#000', '#000')} + + + + ${pageRect('#FFFFFF')} + `); + +const files = { + // Full-bleed icon for iOS, web and Windows (the OS rounds the corners). + 'icon.svg': svg(background + foreground(1.1)), + // Android adaptive icon layers: content kept inside the 66dp safe zone. + 'foreground.svg': svg(foreground(0.9)), + 'background.svg': svg(background), + 'monochrome.svg': monochrome, +}; + +for (const [name, content] of Object.entries(files)) { + fs.writeFileSync(path.join(out, name), content); + const png = new Resvg(content, { fitTo: { mode: 'width', value: 1024 } }).render().asPng(); + fs.writeFileSync(path.join(out, name.replace('.svg', '.png')), png); + console.log('wrote', name, 'and', name.replace('.svg', '.png')); +} + +// Preview: the full icon at launcher size plus a circle-masked adaptive icon. +const preview = svg(` + + ${background}${foreground(0.9)}`); +fs.writeFileSync(path.join(out, '_preview_adaptive.png'), + new Resvg(preview, { fitTo: { mode: 'width', value: 512 } }).render().asPng()); + +// Monochrome preview on a dark background (the real file is transparent), and +// the full icon at a real launcher size to check it still reads when small. +const inner = (s) => s.replace(/^]*>/, '').replace(/<\/svg>$/, ''); +fs.writeFileSync(path.join(out, '_preview_monochrome.png'), + new Resvg(svg('' + inner(monochrome)), + { fitTo: { mode: 'width', value: 256 } }).render().asPng()); +fs.writeFileSync(path.join(out, '_preview_small.png'), + new Resvg(files['icon.svg'], { fitTo: { mode: 'width', value: 96 } }).render().asPng()); diff --git a/assets/icon/monochrome.png b/assets/icon/monochrome.png new file mode 100644 index 0000000..846ff08 Binary files /dev/null and b/assets/icon/monochrome.png differ diff --git a/assets/icon/monochrome.svg b/assets/icon/monochrome.svg new file mode 100644 index 0000000..58fc3ab --- /dev/null +++ b/assets/icon/monochrome.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/agents/domain.md b/docs/agents/domain.md new file mode 100644 index 0000000..4032de0 --- /dev/null +++ b/docs/agents/domain.md @@ -0,0 +1,51 @@ +# Domain Docs + +How the engineering skills should consume this repo's domain documentation when exploring the codebase. + +## Before exploring, read these + +- **`GLOSSARY.md`** at the repo root, or +- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic. +- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src//docs/adr/` for context-scoped decisions. + +If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved. + +## File structure + +Single-context repo (most repos): + +``` +/ +├── GLOSSARY.md +├── docs/adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +Multi-context repo (presence of `GLOSSARY-MAP.md` at the root): + +``` +/ +├── GLOSSARY-MAP.md +├── docs/adr/ ← system-wide decisions +└── src/ + ├── ordering/ + │ ├── GLOSSARY.md + │ └── docs/adr/ ← context-specific decisions + └── billing/ + ├── GLOSSARY.md + └── docs/adr/ +``` + +## Use the glossary's vocabulary + +When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids. + +If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`). + +## Flag ADR conflicts + +If your output contradicts an existing ADR, surface it explicitly rather than silently overriding: + +> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_ diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md new file mode 100644 index 0000000..0508e06 --- /dev/null +++ b/docs/agents/issue-tracker.md @@ -0,0 +1,40 @@ +# Issue tracker: Gitea + +Issues and specs for this repo live as issues on the self-hosted Gitea instance at https://tea.zendric.de, repo `Cedric/TagesByte`. Use the `tea` CLI for all operations. + +`tea` infers the repo from the `origin` remote (`ssh://git@tea.zendric.de:2223/Cedric/TagesByte.git`). If inference fails, add `--repo Cedric/TagesByte`. + +## Conventions + +- **Create an issue**: `tea issues create --title "..." --description "..."`. For multi-line bodies, pipe a heredoc into `--description-file -`. +- **Read an issue**: `tea api repos/{owner}/{repo}/issues/` for the issue as JSON, and `tea api repos/{owner}/{repo}/issues//comments` for its comments. +- **List issues**: `tea issues list --state open --fields index,title,body,labels -o json`, with `--labels "..."` / `--state` filters as needed. +- **Make an issue a child of a parent**: Gitea has no sub-issues. Put `Part of #` at the top of the child body, and add `- [ ] #` to a task list in the parent body. +- **Comment on an issue**: `tea comment "..."` +- **Apply / remove labels**: `tea issues edit --add-labels "..."` / `--remove-labels "..."` +- **Close**: `tea comment "..."`, then `tea issues close `. + +## Pull requests as a triage surface + +**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_ + +When set to `yes`, PRs run through the same labels and states as issues, using `tea pulls` (`tea pulls list`, `tea pulls `) and `tea api repos/{owner}/{repo}/pulls/.diff` for the diff. Gitea shares one number space across issues and PRs. + +## When a skill says "publish to the issue tracker" + +Create a Gitea issue. + +## When a skill says "fetch the relevant ticket" + +Read it as in **Read an issue** above. + +## Wayfinding operations + +Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets. + +- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `tea issues create --labels wayfinder:map ...`. +- **Child ticket**: linked to the map as in **Make an issue a child of a parent**. Labels: `wayfinder:` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev. +- **Blocking**: Gitea's native issue dependencies. Add an edge with `tea api -X POST repos/{owner}/{repo}/issues//dependencies -F index= -f owner=Cedric -f repo=TagesByte`. List a ticket's blockers with `tea api repos/{owner}/{repo}/issues//dependencies`. A ticket is unblocked when every blocker is closed. +- **Frontier query**: list the map's open children (from its task list), drop any with an open blocker or an assignee; first in map order wins. +- **Claim**: `tea issues edit --add-assignees Cedric`, the session's first write. +- **Resolve**: `tea comment ""`, then `tea issues close `, then append a context pointer (gist + link) to the map's Decisions-so-far. diff --git a/docs/agents/triage-labels.md b/docs/agents/triage-labels.md new file mode 100644 index 0000000..5276464 --- /dev/null +++ b/docs/agents/triage-labels.md @@ -0,0 +1,15 @@ +# Triage Labels + +The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker. + +| Label in mattpocock/skills | Label in our tracker | Meaning | +| -------------------------- | -------------------- | ---------------------------------------- | +| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue | +| `needs-info` | `needs-info` | Waiting on reporter for more information | +| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent | +| `ready-for-human` | `ready-for-human` | Requires human implementation | +| `wontfix` | `wontfix` | Will not be actioned | + +When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table. + +Edit the "Label in our tracker" column to match whatever vocabulary you actually use. diff --git a/instructions.md b/instructions.md new file mode 100644 index 0000000..b45f3c3 --- /dev/null +++ b/instructions.md @@ -0,0 +1,13 @@ +Hey i want to have an app that gives me daily tech news. +Please ask me questions if something is unclear/could be improved + +The app should be build using flutter. +I currently already have a n8n workflow to get daily tech news, and it send me them via discord. +I want to replace this. + +For this we need to get data from tech newspapers etc. Please provide me a list of sources. (language preferably german/english could be fine aswell) + +It would be amazing if i could integrate some ai to summarize the articles. +This is what my n8n does already currently( maybe we can depend on this workflow for the app). + +Can you develop me an inital prototype diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..02a74b0 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = de.dailytechnews.dailyTechNews; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.dailytechnews.dailyTechNews.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.dailytechnews.dailyTechNews.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.dailytechnews.dailyTechNews.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = de.dailytechnews.dailyTechNews; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = de.dailytechnews.dailyTechNews; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d0d98aa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1 @@ +{"images":[{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@3x.png","scale":"3x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@3x.png","scale":"3x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@3x.png","scale":"3x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@1x.png","scale":"1x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@3x.png","scale":"3x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@1x.png","scale":"1x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@1x.png","scale":"1x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@1x.png","scale":"1x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@2x.png","scale":"2x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@1x.png","scale":"1x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@2x.png","scale":"2x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@1x.png","scale":"1x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@2x.png","scale":"2x"},{"size":"83.5x83.5","idiom":"ipad","filename":"Icon-App-83.5x83.5@2x.png","scale":"2x"},{"size":"1024x1024","idiom":"ios-marketing","filename":"Icon-App-1024x1024@1x.png","scale":"1x"}],"info":{"version":1,"author":"xcode"}} \ No newline at end of file diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..9d48ad3 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..f112747 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..1ad2c91 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..ee025e2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..9f31ab0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..c3a0dcf Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..e8eaaf9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..1ad2c91 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..69241e7 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..14aa58e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..9674f79 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..a743cbb Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..8c464ab Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..842813e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..14aa58e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..57a1aca Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..e3189e8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..aec1186 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..8bed016 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..a239baf Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..f284738 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..7c3df04 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Tagesbyte + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + Tagesbyte + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + + + UIRequiresFullScreen + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/data/default_sources.dart b/lib/data/default_sources.dart new file mode 100644 index 0000000..fe1e6f5 --- /dev/null +++ b/lib/data/default_sources.dart @@ -0,0 +1,187 @@ +import '../models/news_source.dart'; + +/// Curated tech news feeds. All URLs were checked to return a valid RSS/Atom +/// feed. Users can toggle them and add their own in the Sources tab. +const defaultSources = [ + // --- German ------------------------------------------------------------- + NewsSource( + id: 'heise', + name: 'heise online', + feedUrl: 'https://www.heise.de/rss/heise-atom.xml', + homepage: 'https://www.heise.de', + language: SourceLanguage.de, + description: 'IT-Nachrichten, breit aufgestellt (hohes Volumen)', + enabledByDefault: true, + ), + NewsSource( + id: 'golem', + name: 'Golem.de', + feedUrl: 'https://rss.golem.de/rss.php?feed=ATOM1.0', + homepage: 'https://www.golem.de', + language: SourceLanguage.de, + description: 'IT-News für Profis', + enabledByDefault: true, + ), + NewsSource( + id: 't3n', + name: 't3n', + feedUrl: 'https://t3n.de/rss.xml', + homepage: 'https://t3n.de', + language: SourceLanguage.de, + description: 'Digitales Business, Startups, KI', + enabledByDefault: true, + checkPaywallOnPage: true, + ), + NewsSource( + id: 'computerbase', + name: 'ComputerBase', + feedUrl: 'https://www.computerbase.de/rss/news.xml', + homepage: 'https://www.computerbase.de', + language: SourceLanguage.de, + description: 'Hardware, Software, Gaming', + enabledByDefault: true, + ), + NewsSource( + id: 'spiegel-netzwelt', + name: 'SPIEGEL Netzwelt', + feedUrl: 'https://www.spiegel.de/netzwelt/index.rss', + homepage: 'https://www.spiegel.de/netzwelt/', + language: SourceLanguage.de, + description: 'Digitales aus Sicht eines Nachrichtenmagazins', + checkPaywallOnPage: true, + ), + NewsSource( + id: 'zeit-digital', + name: 'ZEIT Digital', + feedUrl: 'https://newsfeed.zeit.de/digital/index', + homepage: 'https://www.zeit.de/digital/', + language: SourceLanguage.de, + description: 'Digitalpolitik und Gesellschaft', + ), + NewsSource( + id: 'netzpolitik', + name: 'netzpolitik.org', + feedUrl: 'https://netzpolitik.org/feed/', + homepage: 'https://netzpolitik.org', + language: SourceLanguage.de, + description: 'Digitale Freiheitsrechte, Datenschutz', + ), + NewsSource( + id: 'heise-security', + name: 'heise Security', + feedUrl: 'https://www.heise.de/security/rss/news-atom.xml', + homepage: 'https://www.heise.de/security/', + language: SourceLanguage.de, + description: 'Sicherheitslücken und Security-News', + ), + NewsSource( + id: 'heise-developer', + name: 'heise Developer', + feedUrl: 'https://www.heise.de/developer/rss/news-atom.xml', + homepage: 'https://www.heise.de/developer/', + language: SourceLanguage.de, + description: 'Softwareentwicklung', + ), + NewsSource( + id: 'caschy', + name: "Caschys Blog", + feedUrl: 'https://stadt-bremerhaven.de/feed/', + homepage: 'https://stadt-bremerhaven.de', + language: SourceLanguage.de, + description: 'Consumer-Tech, Smartphones, Streaming', + ), + NewsSource( + id: 'derstandard-web', + name: 'derStandard Web', + feedUrl: 'https://www.derstandard.at/rss/web', + homepage: 'https://www.derstandard.at/web', + language: SourceLanguage.de, + description: 'Tech-Ressort der österreichischen Tageszeitung', + ), + NewsSource( + id: 'borncity', + name: 'Borns IT- und Windows-Blog', + feedUrl: 'https://www.borncity.com/blog/feed/', + homepage: 'https://www.borncity.com/blog/', + language: SourceLanguage.de, + description: 'Windows, Patches, Admin-Themen', + ), + + // --- English ------------------------------------------------------------ + NewsSource( + id: 'verge', + name: 'The Verge', + feedUrl: 'https://www.theverge.com/rss/index.xml', + homepage: 'https://www.theverge.com', + language: SourceLanguage.en, + description: 'Consumer tech, culture, policy', + enabledByDefault: true, + ), + NewsSource( + id: 'arstechnica', + name: 'Ars Technica', + feedUrl: 'https://feeds.arstechnica.com/arstechnica/index', + homepage: 'https://arstechnica.com', + language: SourceLanguage.en, + description: 'In-depth tech and science', + enabledByDefault: true, + ), + NewsSource( + id: 'techcrunch', + name: 'TechCrunch', + feedUrl: 'https://techcrunch.com/feed/', + homepage: 'https://techcrunch.com', + language: SourceLanguage.en, + description: 'Startups, funding, big tech', + enabledByDefault: true, + ), + NewsSource( + id: 'hackernews', + name: 'Hacker News', + feedUrl: 'https://news.ycombinator.com/rss', + homepage: 'https://news.ycombinator.com', + language: SourceLanguage.en, + description: 'Front page links, ranked by readers', + enabledByDefault: true, + ), + NewsSource( + id: 'mit-tr', + name: 'MIT Technology Review', + feedUrl: 'https://www.technologyreview.com/feed/', + homepage: 'https://www.technologyreview.com', + language: SourceLanguage.en, + description: 'AI, biotech, climate tech', + ), + NewsSource( + id: 'wired', + name: 'WIRED', + feedUrl: 'https://www.wired.com/feed/rss', + homepage: 'https://www.wired.com', + language: SourceLanguage.en, + description: 'Tech, science and culture', + ), + NewsSource( + id: 'engadget', + name: 'Engadget', + feedUrl: 'https://www.engadget.com/rss.xml', + homepage: 'https://www.engadget.com', + language: SourceLanguage.en, + description: 'Gadgets and consumer electronics', + ), + NewsSource( + id: 'theregister', + name: 'The Register', + feedUrl: 'https://www.theregister.com/headlines.atom', + homepage: 'https://www.theregister.com', + language: SourceLanguage.en, + description: 'Enterprise IT with attitude', + ), + NewsSource( + id: 'bleepingcomputer', + name: 'BleepingComputer', + feedUrl: 'https://www.bleepingcomputer.com/feed/', + homepage: 'https://www.bleepingcomputer.com', + language: SourceLanguage.en, + description: 'Security and malware news', + ), +]; diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..ee61a5f --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'services/storage.dart'; +import 'state/app_state.dart'; +import 'ui/common.dart'; +import 'ui/home_shell.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + // Portrait only; also set in AndroidManifest.xml and Info.plist. + await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + final state = AppState(await Storage.open()); + runApp(DailyTechNewsApp(state: state)); + state.init(); +} + +class DailyTechNewsApp extends StatelessWidget { + const DailyTechNewsApp({super.key, required this.state}); + + final AppState state; + + static const _seed = Color(0xFF3355DD); + + @override + Widget build(BuildContext context) { + ThemeData theme(Brightness brightness) => ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: _seed, brightness: brightness), + cardTheme: const CardThemeData(margin: EdgeInsets.zero), + ); + + // Rebuild when the theme setting changes; everything else listens itself. + return ListenableBuilder( + listenable: state, + builder: (context, _) => MaterialApp( + title: appName, + debugShowCheckedModeBanner: false, + theme: theme(Brightness.light), + darkTheme: theme(Brightness.dark), + themeMode: state.settings.themeMode, + home: HomeShell(state: state), + ), + ); + } +} diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart new file mode 100644 index 0000000..42514a8 --- /dev/null +++ b/lib/models/app_settings.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart' show ThemeMode; + +import 'news_source.dart'; + +enum AiProvider { + none('Off'), + claude('Claude API'), + n8n('n8n webhook'); + + const AiProvider(this.label); + + final String label; +} + +const claudeModels = { + 'claude-opus-5-5': 'Claude Opus 5.5 (best quality)', + 'claude-sonnet-5-5': 'Claude Sonnet 5.5 (balanced)', + 'claude-haiku-5-5': 'Claude Haiku 5.5 (cheapest, fastest)', +}; + +class AppSettings { + const AppSettings({ + this.aiProvider = AiProvider.none, + this.claudeApiKey = '', + this.claudeModel = 'claude-opus-5-5', + this.n8nWebhookUrl = '', + this.summaryLanguage = SourceLanguage.de, + this.maxAgeHours = 24, + this.corsProxy = '', + this.hidePaid = true, + this.hideSponsored = true, + this.blockAds = true, + this.hideCookieBanners = true, + this.acceptConsentWalls = true, + this.themeMode = ThemeMode.system, + }); + + final AiProvider aiProvider; + final String claudeApiKey; + final String claudeModel; + final String n8nWebhookUrl; + final SourceLanguage summaryLanguage; + final int maxAgeHours; + + /// Web only: prefix for feed/article URLs to get around browser CORS. + final String corsProxy; + + /// Hide paywalled articles (heise+, SPIEGEL+, Golem Plus, t3n Pro). + final bool hidePaid; + + /// Hide sponsored posts ("Anzeige:"). + final bool hideSponsored; + + /// Original-page view: block ad/tracker requests and hide ad slots. + final bool blockAds; + + /// Original-page view: block consent managers and hide their banners. + final bool hideCookieBanners; + + /// Accept consent on sites that only show articles after accepting (Golem). + final bool acceptConsentWalls; + + /// Light, dark, or follow the phone's setting. + final ThemeMode themeMode; + + bool get aiConfigured => switch (aiProvider) { + AiProvider.none => false, + AiProvider.claude => claudeApiKey.isNotEmpty, + AiProvider.n8n => n8nWebhookUrl.startsWith('http'), + }; + + AppSettings copyWith({ + AiProvider? aiProvider, + String? claudeApiKey, + String? claudeModel, + String? n8nWebhookUrl, + SourceLanguage? summaryLanguage, + int? maxAgeHours, + String? corsProxy, + bool? hidePaid, + bool? hideSponsored, + bool? blockAds, + bool? hideCookieBanners, + bool? acceptConsentWalls, + ThemeMode? themeMode, + }) => + AppSettings( + aiProvider: aiProvider ?? this.aiProvider, + claudeApiKey: claudeApiKey ?? this.claudeApiKey, + claudeModel: claudeModel ?? this.claudeModel, + n8nWebhookUrl: n8nWebhookUrl ?? this.n8nWebhookUrl, + summaryLanguage: summaryLanguage ?? this.summaryLanguage, + maxAgeHours: maxAgeHours ?? this.maxAgeHours, + corsProxy: corsProxy ?? this.corsProxy, + hidePaid: hidePaid ?? this.hidePaid, + hideSponsored: hideSponsored ?? this.hideSponsored, + blockAds: blockAds ?? this.blockAds, + hideCookieBanners: hideCookieBanners ?? this.hideCookieBanners, + acceptConsentWalls: acceptConsentWalls ?? this.acceptConsentWalls, + themeMode: themeMode ?? this.themeMode, + ); +} diff --git a/lib/models/article.dart b/lib/models/article.dart new file mode 100644 index 0000000..08de71b --- /dev/null +++ b/lib/models/article.dart @@ -0,0 +1,30 @@ +import 'news_source.dart'; + +class Article { + const Article({ + required this.title, + required this.link, + required this.source, + this.published, + this.excerpt = '', + this.contentHtml = '', + this.imageUrl, + this.author, + }); + + final String title; + final String link; + final NewsSource source; + final DateTime? published; + + /// Short plain-text teaser from the feed (description / summary). + final String excerpt; + + /// Full article HTML if the feed ships it (content:encoded / atom content). + final String contentHtml; + final String? imageUrl; + final String? author; + + /// The link is unique enough to identify an article across refreshes. + String get id => link; +} diff --git a/lib/models/briefing.dart b/lib/models/briefing.dart new file mode 100644 index 0000000..220ac5f --- /dev/null +++ b/lib/models/briefing.dart @@ -0,0 +1,81 @@ +/// An AI generated digest of the day's news, grouped into topics. +class DailyBriefing { + const DailyBriefing({ + required this.createdAt, + required this.intro, + required this.topics, + required this.generatedBy, + }); + + final DateTime createdAt; + final String intro; + final List topics; + + /// Human readable name of the summarizer, e.g. "Claude (claude-opus-5-5)". + final String generatedBy; + + Map toJson() => { + 'createdAt': createdAt.toIso8601String(), + 'intro': intro, + 'generatedBy': generatedBy, + 'topics': topics.map((t) => t.toJson()).toList(), + }; + + factory DailyBriefing.fromJson(Map json) => DailyBriefing( + createdAt: DateTime.parse(json['createdAt'] as String), + intro: json['intro'] as String? ?? '', + generatedBy: json['generatedBy'] as String? ?? '', + topics: (json['topics'] as List? ?? []) + .map((t) => BriefingTopic.fromJson(t as Map)) + .toList(), + ); +} + +class BriefingTopic { + const BriefingTopic({ + required this.title, + required this.summary, + required this.sources, + }); + + final String title; + final String summary; + final List sources; + + Map toJson() => { + 'title': title, + 'summary': summary, + 'sources': sources.map((s) => s.toJson()).toList(), + }; + + factory BriefingTopic.fromJson(Map json) => BriefingTopic( + title: json['title'] as String? ?? '', + summary: json['summary'] as String? ?? '', + sources: (json['sources'] as List? ?? []) + .map((s) => ArticleRef.fromJson(s as Map)) + .toList(), + ); +} + +/// A lightweight pointer to an article, stored with the briefing so links +/// still work after the feed has been refreshed. +class ArticleRef { + const ArticleRef({ + required this.title, + required this.url, + required this.sourceName, + }); + + final String title; + final String url; + final String sourceName; + + Map toJson() => + {'title': title, 'url': url, 'sourceName': sourceName}; + + factory ArticleRef.fromJson(Map json) => ArticleRef( + title: json['title'] as String? ?? '', + url: json['url'] as String? ?? '', + sourceName: json['sourceName'] as String? ?? '', + ); +} diff --git a/lib/models/news_source.dart b/lib/models/news_source.dart new file mode 100644 index 0000000..63d47b5 --- /dev/null +++ b/lib/models/news_source.dart @@ -0,0 +1,55 @@ +enum SourceLanguage { + de('Deutsch', '🇩🇪'), + en('English', '🇬🇧'); + + const SourceLanguage(this.label, this.flag); + + final String label; + final String flag; +} + +class NewsSource { + const NewsSource({ + required this.id, + required this.name, + required this.feedUrl, + required this.homepage, + required this.language, + this.description = '', + this.enabledByDefault = false, + this.isCustom = false, + this.checkPaywallOnPage = false, + }); + + final String id; + final String name; + final String feedUrl; + final String homepage; + final SourceLanguage language; + final String description; + final bool enabledByDefault; + final bool isCustom; + + /// Paid articles are only marked inside the page (schema.org), not in the + /// feed, so each new article page is checked once. + final bool checkPaywallOnPage; + + Map toJson() => { + 'id': id, + 'name': name, + 'feedUrl': feedUrl, + 'homepage': homepage, + 'language': language.name, + 'description': description, + }; + + factory NewsSource.custom(Map json) => NewsSource( + id: json['id'] as String, + name: json['name'] as String, + feedUrl: json['feedUrl'] as String, + homepage: json['homepage'] as String? ?? '', + language: SourceLanguage.values.byName(json['language'] as String? ?? 'en'), + description: json['description'] as String? ?? '', + isCustom: true, + ); +} diff --git a/lib/services/article_extractor.dart b/lib/services/article_extractor.dart new file mode 100644 index 0000000..41ad6ac --- /dev/null +++ b/lib/services/article_extractor.dart @@ -0,0 +1,250 @@ +import 'package:flutter/foundation.dart'; +import 'package:html/dom.dart' as dom; +import 'package:html/parser.dart' as html_parser; +import 'package:http/http.dart' as http; + +import '../models/article.dart'; +import 'consent_service.dart'; +import 'content_blocking.dart'; +import 'feed_service.dart'; + +enum BlockType { heading, paragraph, listItem, quote, code, image, caption } + +/// One piece of an article in reader view. For images [text] is the URL. +class ReaderBlock { + const ReaderBlock(this.type, this.text); + + final BlockType type; + final String text; + + bool get isText => type != BlockType.image && type != BlockType.caption; +} + +class ArticleContent { + ArticleContent(this.blocks, {this.consentWall = false}) + : plainText = blocks.where((b) => b.isText).map((b) => b.text).join('\n\n'); + + static final empty = ArticleContent(const []); + + final List blocks; + + /// Text handed to the AI summarizer. + final String plainText; + + /// The site redirected to a consent page (accept tracking or subscribe) + /// instead of serving the article. + final bool consentWall; +} + +/// Turns an article page into reader-view blocks so it can be read inside the +/// app, and gives the AI more to work with than the feed teaser. +class ArticleExtractor { + ArticleExtractor({http.Client? client, ConsentService? consent}) + : _client = client ?? http.Client(), + _consent = consent; + + final http.Client _client; + final ConsentService? _consent; + + /// Hard cap on what we send to the model per article (~10k tokens). + static const maxChars = 40000; + + /// Loads the article page and returns whichever is longer: the extracted + /// page or the full content some feeds ship. Never throws; on failure + /// (paywall, bot protection, CORS on web) it falls back to feed content. + /// + /// With [acceptConsentWalls], a redirect to a consent page the + /// [ConsentService] knows is accepted once and the article fetched again. + Future load( + Article article, { + String corsProxy = '', + bool acceptConsentWalls = false, + }) async { + final base = Uri.parse(article.link); + final fromFeed = article.contentHtml.isEmpty + ? ArticleContent.empty + : parse(article.contentHtml, base, isFragment: true); + + if (kIsWeb && corsProxy.isEmpty) return fromFeed; + try { + final url = Uri.parse( + kIsWeb ? '$corsProxy${Uri.encodeComponent(article.link)}' : article.link); + var page = await _fetch(url); + final consent = _consent; + if (page.wallUrl != null && + acceptConsentWalls && + consent != null && + consent.canAccept(page.wallUrl!) && + await consent.accept(page.wallUrl!, wallHtml: FeedService.decodeBody(page.bytes))) { + page = await _fetch(url); + } + if (page.wallUrl != null) return ArticleContent(fromFeed.blocks, consentWall: true); + if (page.status != 200) return fromFeed; + final fromPage = parse(FeedService.decodeBody(page.bytes), base); + return fromPage.plainText.length > fromFeed.plainText.length ? fromPage : fromFeed; + } catch (_) { + return fromFeed; + } + } + + /// [wallUrl] is set when the request ended on a consent page. + Future<({int status, List bytes, Uri? wallUrl})> _fetch(Uri url) async { + final request = http.Request('GET', url); + if (!kIsWeb) { + request.headers['User-Agent'] = 'Mozilla/5.0 (DailyTechNews)'; + final cookie = _consent?.cookieHeader(url); + if (cookie != null) request.headers['Cookie'] = cookie; + } + // send() (unlike get()) keeps the final URL after redirects. + final response = await _client.send(request).timeout(const Duration(seconds: 20)); + final finalUrl = response is http.BaseResponseWithUrl + ? (response as http.BaseResponseWithUrl).url + : null; + final onWall = + finalUrl != null && ContentBlocking.consentWall.hasMatch(finalUrl.toString()); + if (response.statusCode != 200) { + await response.stream.listen(null).cancel(); + return (status: response.statusCode, bytes: const [], wallUrl: null); + } + final bytes = await response.stream.toBytes().timeout(const Duration(seconds: 20)); + return (status: 200, bytes: bytes, wallUrl: onWall ? finalUrl : null); + } + + static const _junkTags = + 'script, style, nav, header, footer, aside, form, noscript, button, svg, iframe, ' + 'template, dialog, ' + // Screen-reader-only text such as "(öffnet im neuen Fenster)". + '.sr-only, .visually-hidden, .visuallyhidden, .screen-reader-text, .go-vh'; + + /// Class/id fragments of page furniture that sits inside article bodies. + static final _junkMarker = RegExp( + r'comment|related|newsletter|share|social|promo|advert|paywall|subscribe|' + r'recommend|author-box|byline|breadcrumb|tags|toolbar|consent|cookie|card|native-ad', + caseSensitive: false, + ); + + static const _containerTags = {'div', 'section', 'ul', 'ol', 'span', 'aside'}; + + static ArticleContent parse(String html, Uri base, {bool isFragment = false}) { + final root = isFragment + ? (html_parser.parse('$html').body!) + : html_parser.parse(html).documentElement!; + root.querySelectorAll(_junkTags).forEach((dom.Element e) => e.remove()); + for (final e in root.querySelectorAll('*').toList()) { + if (!_containerTags.contains(e.localName)) continue; + final marker = '${e.className} ${e.id}'; + if (_junkMarker.hasMatch(marker)) e.remove(); + } + + // Many sites wrap every teaser in its own
, so pick whichever + // candidate container holds the most paragraph text. + dom.Element? best; + var bestScore = 0; + for (final candidate + in root.querySelectorAll('article, main, [itemprop="articleBody"]')) { + final score = _score(candidate); + if (score > bestScore) { + best = candidate; + bestScore = score; + } + } + // The body includes navigation and comments; only use it as a last resort. + best ??= isFragment ? root : root.querySelector('body'); + if (best == null) return ArticleContent.empty; + + final blocks = []; + final seenImages = {}; + var chars = 0; + void add(BlockType type, String text) { + if (chars > maxChars) return; + if (type == BlockType.image) { + if (!seenImages.add(text)) return; + } else { + chars += text.length; + } + blocks.add(ReaderBlock(type, text)); + } + + void walk(dom.Element el) { + switch (el.localName) { + case 'h1': + return; // The title is shown from the feed. + case 'h2' || 'h3' || 'h4': + final t = _clean(el.text); + if (t.isNotEmpty) add(BlockType.heading, t); + return; + case 'p': + final t = _clean(el.text); + if (t.length >= 25) add(BlockType.paragraph, t); + el.querySelectorAll('img').forEach((img) => _addImage(img, base, add)); + return; + case 'li': + // Nested lists: emit the inner items individually. + if (el.querySelector('ul, ol') != null) break; + final t = _clean(el.text); + // Items that are nothing but a link are tables of contents or nav. + final linkText = _clean(el.querySelectorAll('a').map((a) => a.text).join(' ')); + if (linkText == t) return; + if (t.length >= 20) add(BlockType.listItem, t); + return; + case 'blockquote': + final t = _clean(el.text); + if (t.isNotEmpty) add(BlockType.quote, t); + return; + case 'pre': + final t = el.text.trimRight(); + if (t.isNotEmpty) add(BlockType.code, t); + return; + case 'figcaption': + final t = _clean(el.text); + if (t.isNotEmpty) add(BlockType.caption, t); + return; + case 'img': + _addImage(el, base, add); + return; + } + for (final child in el.children) { + walk(child); + } + } + + walk(best); + return ArticleContent(blocks); + } + + static int _score(dom.Element root) => root + .querySelectorAll('p') + .map((e) => _clean(e.text).length) + .where((l) => l > 40) + .fold(0, (a, b) => a + b); + + static String _clean(String s) => s.replaceAll(RegExp(r'\s+'), ' ').trim(); + + static void _addImage( + dom.Element img, Uri base, void Function(BlockType, String) add) { + // Lazy-loading sites keep the real URL in data attributes. + final raw = img.attributes['data-src'] ?? + img.attributes['data-lazy-src'] ?? + img.attributes['src'] ?? + img.attributes['srcset']?.split(',').first.trim().split(' ').first; + if (raw == null || raw.isEmpty || raw.startsWith('data:') || raw.endsWith('.svg')) { + return; + } + final width = int.tryParse(img.attributes['width'] ?? ''); + if (width != null && width < 120) return; // icons, avatars, tracking pixels + // Images linking to another page are author avatars or related-story + // thumbnails; links to the full-size image file are fine. + for (var p = img.parent; p != null; p = p.parent) { + if (p.localName == 'a') { + final href = p.attributes['href'] ?? ''; + if (!RegExp(r'\.(jpe?g|png|webp|gif|avif)(\?|$)', caseSensitive: false) + .hasMatch(href)) { + return; + } + break; + } + } + final url = base.resolve(raw).toString(); + if (url.startsWith('http')) add(BlockType.image, url); + } +} diff --git a/lib/services/claude_summarizer.dart b/lib/services/claude_summarizer.dart new file mode 100644 index 0000000..4a919c4 --- /dev/null +++ b/lib/services/claude_summarizer.dart @@ -0,0 +1,175 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import '../models/article.dart'; +import '../models/briefing.dart'; +import '../models/news_source.dart'; +import 'summarizer.dart'; + +/// Calls the Claude Messages API directly over HTTP (there is no official +/// Dart SDK). +class ClaudeSummarizer implements Summarizer { + ClaudeSummarizer({required this.apiKey, required this.model, http.Client? client}) + : _client = client ?? http.Client(); + + final String apiKey; + final String model; + final http.Client _client; + + static final _endpoint = Uri.parse('https://api.anthropic.com/v1/messages'); + + /// Models that support the server-side refusal fallback (`fallbacks: "default"`). + static const _fallbackModels = {'claude-opus-5-5', 'claude-sonnet-5-5'}; + + static const _retryStatus = {429, 500, 502, 503, 529}; + + @override + String get name => 'Claude ($model)'; + + @override + Future summarizeArticle( + Article article, String text, SourceLanguage language) async { + final system = 'You summarize tech news articles for a busy reader. ' + 'Write in ${languageName(language)}, regardless of the article language. ' + 'Start with a single-sentence TL;DR line prefixed with "TL;DR:", then 3-5 ' + 'short bullet points starting with "• " covering the key facts, numbers and ' + 'why it matters. Plain text only, no markdown headings or bold. If the text ' + 'is only a teaser, summarize what is there and say that the full article ' + 'was not available.'; + final user = 'Source: ${article.source.name}\n' + 'Title: ${article.title}\n' + 'URL: ${article.link}\n\n' + 'Article text:\n$text'; + return _send(system: system, user: user); + } + + @override + Future createBriefing( + List
articles, SourceLanguage language) async { + final input = BriefingInput(articles); + final system = 'You are the editor of a daily tech news briefing. You receive ' + "today's headlines from several German and English tech news sites, each " + 'with an id in square brackets. Pick the 6-10 most important stories for a ' + 'software developer interested in tech, merging coverage of the same story ' + 'from different sources into one topic. Prefer substantial news (releases, ' + 'security incidents, regulation, big business moves, AI) over deals, ' + 'reviews and opinion pieces. Write all text in ${languageName(language)}. ' + 'For each topic give a short title, a 2-4 sentence summary, and the ids of ' + 'the articles it is based on. The intro is one or two sentences about the ' + "day's overall picture."; + final user = "Today's headlines:\n\n${input.toPromptList()}"; + + final raw = await _send(system: system, user: user, schema: _briefingSchema); + try { + return input.toBriefing(jsonDecode(raw) as Map, name); + } on FormatException { + throw SummarizerException('Claude returned an unexpected briefing format.'); + } + } + + static const _briefingSchema = { + 'type': 'object', + 'properties': { + 'intro': {'type': 'string'}, + 'topics': { + 'type': 'array', + 'items': { + 'type': 'object', + 'properties': { + 'title': {'type': 'string'}, + 'summary': {'type': 'string'}, + 'article_ids': { + 'type': 'array', + 'items': {'type': 'string'}, + }, + }, + 'required': ['title', 'summary', 'article_ids'], + 'additionalProperties': false, + }, + }, + }, + 'required': ['intro', 'topics'], + 'additionalProperties': false, + }; + + Future _send({ + required String system, + required String user, + Map? schema, + }) async { + final useFallbacks = _fallbackModels.contains(model); + final body = jsonEncode({ + 'model': model, + 'max_tokens': 16000, + 'system': system, + 'messages': [ + {'role': 'user', 'content': user}, + ], + // Summarizing is a routine task; low effort keeps it fast and cheap. + 'output_config': { + 'effort': 'low', + if (schema != null) 'format': {'type': 'json_schema', 'schema': schema}, + }, + // If a safety classifier declines, retry server-side on a fallback model. + if (useFallbacks) 'fallbacks': 'default', + }); + final headers = { + 'content-type': 'application/json', + 'x-api-key': apiKey, + 'anthropic-version': '2023-06-01', + if (useFallbacks) 'anthropic-beta': 'server-side-fallback-2026-07-01', + if (kIsWeb) 'anthropic-dangerous-direct-browser-access': 'true', + }; + + http.Response response; + var attempt = 0; + while (true) { + try { + response = await _client + .post(_endpoint, headers: headers, body: body) + .timeout(const Duration(minutes: 3)); + } on Exception catch (e) { + if (attempt++ < 2) { + await Future.delayed(Duration(seconds: 2 * attempt)); + continue; + } + throw SummarizerException('Could not reach the Claude API: $e'); + } + if (_retryStatus.contains(response.statusCode) && attempt++ < 2) { + final retryAfter = int.tryParse(response.headers['retry-after'] ?? ''); + await Future.delayed(Duration(seconds: retryAfter ?? 3 * attempt)); + continue; + } + break; + } + + final json = jsonDecode(utf8.decode(response.bodyBytes)) as Map; + if (response.statusCode != 200) { + final error = json['error'] as Map?; + final message = error?['message'] ?? 'Unknown error'; + throw SummarizerException(switch (response.statusCode) { + 401 => 'Invalid Claude API key. Check it in Settings.', + 429 => 'Rate limited by the Claude API. Try again in a minute.', + 529 => 'The Claude API is overloaded right now. Try again shortly.', + _ => 'Claude API error ${response.statusCode}: $message', + }); + } + + switch (json['stop_reason']) { + case 'refusal': + throw SummarizerException('Claude declined to summarize this content.'); + case 'max_tokens' when schema != null: + throw SummarizerException('The briefing was cut off. Try fewer sources.'); + } + + final text = (json['content'] as List) + .where((block) => block['type'] == 'text') + .map((block) => block['text'] as String) + .join() + .trim(); + if (text.isEmpty) throw SummarizerException('Claude returned an empty response.'); + return text; + } +} diff --git a/lib/services/consent_service.dart b/lib/services/consent_service.dart new file mode 100644 index 0000000..94ae6f4 --- /dev/null +++ b/lib/services/consent_service.dart @@ -0,0 +1,104 @@ +import 'package:http/http.dart' as http; + +/// Gets past consent walls: sites that redirect to a separate consent page +/// instead of showing the article (currently Golem). +/// +/// Accepting makes the same request the site's own "accept" button makes and +/// keeps the resulting cookies in memory, so both the reader view (via +/// [cookieHeader]) and the in-app web view (via [cookiesFor]) can send them. +/// Ads and trackers stay blocked separately. +class ConsentService { + ConsentService({http.Client? client}) : _client = client ?? http.Client(); + + final http.Client _client; + + /// Domain (e.g. "golem.de") -> cookie name -> value. + final Map> _cookies = {}; + + static final _walls = <_ConsentWall>[_GolemWall()]; + + static String domainOf(Uri url) { + final parts = url.host.split('.'); + return parts.length <= 2 ? url.host : parts.sublist(parts.length - 2).join('.'); + } + + /// True if [url] is a consent page this service knows how to accept. + bool canAccept(Uri url) => _walls.any((w) => w.matches(url)); + + Map cookiesFor(Uri url) => _cookies[domainOf(url)] ?? const {}; + + /// Value for a `Cookie` request header, or null if nothing was accepted. + String? cookieHeader(Uri url) { + final cookies = cookiesFor(url); + if (cookies.isEmpty) return null; + return cookies.entries.map((e) => '${e.key}=${e.value}').join('; '); + } + + /// Accepts the consent wall at [wallUrl]. [wallHtml] is the consent page, + /// fetched if not given. Returns true if consent cookies were obtained. + Future accept(Uri wallUrl, {String? wallHtml}) async { + final wall = _walls.where((w) => w.matches(wallUrl)).firstOrNull; + if (wall == null) return false; + try { + wallHtml ??= (await _client.get(wallUrl, headers: _headers) + .timeout(const Duration(seconds: 15))) + .body; + final response = await _client + .get(wall.acceptUrl(wallUrl, wallHtml), headers: _headers) + .timeout(const Duration(seconds: 15)); + if (response.statusCode != 200) return false; + final cookies = parseSetCookie(response.headers['set-cookie'] ?? ''); + if (!cookies.containsKey(wall.requiredCookie)) return false; + _cookies.putIfAbsent(domainOf(wallUrl), () => {}).addAll(cookies); + return true; + } catch (_) { + return false; + } + } + + static const _headers = {'User-Agent': 'Mozilla/5.0 (DailyTechNews)'}; + + /// package:http joins multiple Set-Cookie headers with commas. Split only on + /// commas that start a new `name=` pair, not those inside `expires=` dates. + static Map parseSetCookie(String header) { + final cookies = {}; + for (final cookie in header.split(RegExp(r',(?=\s*[^;,=\s]+=)'))) { + final pair = cookie.split(';').first.trim(); + final eq = pair.indexOf('='); + if (eq > 0) cookies[pair.substring(0, eq)] = pair.substring(eq + 1); + } + return cookies; + } +} + +abstract class _ConsentWall { + bool matches(Uri url); + + /// The cookie that proves consent was stored. + String get requiredCookie; + + Uri acceptUrl(Uri wallUrl, String wallHtml); +} + +/// Golem redirects to /sonstiges/zustimmung/auswahl.html. Its consent script +/// stores the choice by calling /abo/setconsentcookie.php; "simple" is the +/// plain "Zustimmen" button Golem shows when its consent manager doesn't load. +class _GolemWall implements _ConsentWall { + static final _version = RegExp(r'"cookieVersion"\s*:\s*"([^"]+)"'); + + @override + bool matches(Uri url) => + url.host.endsWith('golem.de') && url.path.startsWith('/sonstiges/zustimmung/'); + + @override + String get requiredCookie => 'golem_consent20'; + + @override + Uri acceptUrl(Uri wallUrl, String wallHtml) => Uri.https('www.golem.de', '/abo/setconsentcookie.php', { + 'type': 'simple', + // Golem bumps this when its consent text changes; read it from the page. + 'version': _version.firstMatch(wallHtml)?.group(1) ?? '|250101', + 'expire': '1', + 'referer': wallUrl.queryParameters['from'] ?? 'https://www.golem.de/', + }); +} diff --git a/lib/services/content_blocking.dart b/lib/services/content_blocking.dart new file mode 100644 index 0000000..3f1954e --- /dev/null +++ b/lib/services/content_blocking.dart @@ -0,0 +1,136 @@ +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; + +/// Ad, tracker and cookie-banner blocking for the in-app "original page" view. +/// +/// Two layers: requests to known ad/tracker/consent hosts are blocked before +/// they load, and a stylesheet injected at page start hides whatever slots and +/// banners are left. Hiding a consent banner gives no consent, so sites treat +/// it like a rejection. +class ContentBlocking { + /// Sites that redirect to a separate consent page instead of showing a + /// banner. Nothing can be hidden there; it's accept, pay, or leave. + static final consentWall = RegExp(r'golem\.de/sonstiges/zustimmung/|consent\.yahoo\.com/'); + + static const adHosts = [ + // Ad exchanges and networks + 'doubleclick.net', 'googlesyndication.com', 'googleadservices.com', + 'googletagservices.com', 'adservice.google.com', 'adservice.google.de', + 'amazon-adsystem.com', 'criteo.com', 'criteo.net', 'taboola.com', 'outbrain.com', + 'adnxs.com', 'rubiconproject.com', 'pubmatic.com', 'openx.net', 'casalemedia.com', + 'indexww.com', 'smartadserver.com', 'sascdn.com', 'yieldlab.net', 'adform.net', + 'adition.com', 'teads.tv', 'seedtag.com', '3lift.com', 'sharethrough.com', + '33across.com', 'media.net', 'mgid.com', 'zemanta.com', 'yieldmo.com', + 'onetag-sys.com', 'bidswitch.net', 'lijit.com', 'sonobi.com', 'gumgum.com', + 'adsrvr.org', 'plista.com', 'ligatus.com', 'nativendo.de', 'traffective.com', + 'btloader.com', 'ad-delivery.net', 'adsafeprotected.com', 'moatads.com', + 'confiant-integrations.net', 'flashtalking.com', 'servedby-buysellads.com', + // Tracking and analytics + 'google-analytics.com', 'googletagmanager.com', 'scorecardresearch.com', + 'chartbeat.com', 'chartbeat.net', 'ioam.de', 'iocnt.net', 'hotjar.com', + 'facebook.net', 'ads-twitter.com', 'analytics.tiktok.com', 'bat.bing.com', + 'quantserve.com', 'krxd.net', 'demdex.net', 'omtrdc.net', 'adobedtm.com', + 'permutive.com', 'permutive.app', 'cxense.com', 'id5-sync.com', 'rlcdn.com', + 'bluekai.com', 'everesttech.net', 'parsely.com', 'newrelic.com', 'nr-data.net', + ]; + + static const consentHosts = [ + 'privacy-mgmt.com', 'sp-prod.net', 'sourcepoint.com', // Sourcepoint + 'cookielaw.org', 'onetrust.com', 'onetrust.io', // OneTrust + 'usercentrics.eu', 'usercentrics.com', 'privacy-center.org', 'didomi.io', + 'consensu.org', 'cookiebot.com', 'consentmanager.net', 'trustarc.com', + 'truste.com', 'cookieinformation.com', 'iubenda.com', 'cookie-script.com', + 'termly.io', 'osano.com', 'contentpass.net', 'contentpass.de', 'fundingchoicesmessages.google.com', + ]; + + static const _adSelectors = [ + 'ins.adsbygoogle', '.adsbygoogle', '[id^="google_ads_iframe"]', '[id^="div-gpt-ad"]', + '[data-google-query-id]', 'iframe[src*="doubleclick"]', '[id*="taboola"]', + '[class*="taboola"]', '[id*="outbrain"]', '.OUTBRAIN', '[data-ad-slot]', + '[data-ad-unit]', '.ad-container', '.ad-slot', '.ad-wrapper', '.ad-label', + '.advertisement', '.advert', '.adzone', '.adunit', '.sponsored-content', + '[aria-label="Advertisement"]', '[data-testid*="ad-slot"]', + // Reserved slots that would otherwise stay as empty gaps (e.g. ComputerBase). + '[class*="adbox"]', '[class*="adslot"]', '[class*="ad-slot"]', '[class*="ad_slot"]', + '[id*="adslot"]', r'[class$="-ad"]', '[class*="-ad "]', '[class*="ad-container"]', + ]; + + static const _consentSelectors = [ + '[id^="sp_message_container"]', '.sp_veil', '#onetrust-consent-sdk', + '#onetrust-banner-sdk', '.onetrust-pc-dark-filter', '#usercentrics-root', + '#usercentrics-cmp-ui', '#didomi-host', '#CybotCookiebotDialog', + '#CybotCookiebotDialogBodyUnderlay', '#cmpbox', '#cmpbox2', '.cmpboxBG', + '#qc-cmp2-container', '.qc-cmp2-container', '#truste-consent-track', + '.truste_overlay', '.truste_box_overlay', '#iubenda-cs-banner', '.fc-consent-root', + '.fc-dialog-overlay', '#cookie-banner', '#cookiebanner', '#cookie-consent', + '.cookie-banner', '.cookie-consent', '.cc-window', '.cc-banner', + ]; + + static String _hostPattern(List hosts) => + r'^https?://([^/:]+\.)?(' + hosts.map(RegExp.escape).join('|') + r')([:/?]|$)'; + + /// Network-level blocking. One combined regex per category keeps the + /// per-request check cheap. + static List blockers({required bool ads, required bool cookies}) => [ + if (ads) _block(_hostPattern(adHosts)), + if (cookies) ...[ + _block(_hostPattern(consentHosts)), + // Sourcepoint is often served from the site itself, e.g. cmp.heise.de. + _block(r'^https?://cmp\.[^/]+/'), + ], + ]; + + static ContentBlocker _block(String pattern) => ContentBlocker( + trigger: ContentBlockerTrigger(urlFilter: pattern), + action: ContentBlockerAction(type: ContentBlockerActionType.BLOCK), + ); + + /// A script for page start that injects the hiding stylesheet and keeps it + /// in place. Returns null when nothing is enabled. + static String? cosmeticScript({required bool ads, required bool cookies}) { + final selectors = [if (ads) ..._adSelectors, if (cookies) ..._consentSelectors]; + if (selectors.isEmpty) return null; + final css = StringBuffer('${selectors.join(',')}{display:none!important}'); + if (cookies) { + // Consent dialogs lock scrolling on /; undo that. + css.write('html,body{overflow:auto!important;overflow-y:auto!important}'); + } + final cssLiteral = css.toString().replaceAll(r'\', r'\\').replaceAll("'", r"\'"); + return ''' +(function () { + var css = '$cssLiteral'; + var unlockConsent = $cookies; + var consentPattern = /consent|cookie|cmp|gdpr|sp-message|didomi|onetrust|usercentrics/i; + function apply() { + if (document.getElementById('tagesbyte-blocker')) return; + var style = document.createElement('style'); + style.id = 'tagesbyte-blocker'; + style.textContent = css; + (document.head || document.documentElement).appendChild(style); + } + // Some sites (e.g. ComputerBase) build their own consent wall as a modal + // , which makes the rest of the page inert even when hidden. + function unlock() { + if (!unlockConsent) return; + document.querySelectorAll('dialog').forEach(function (d) { + if (consentPattern.test(d.className + ' ' + d.id)) { + try { d.close(); } catch (e) {} + d.remove(); + } + }); + [document.documentElement, document.body].forEach(function (el) { + if (!el) return; + Array.prototype.slice.call(el.classList).forEach(function (c) { + if (consentPattern.test(c)) el.classList.remove(c); + }); + }); + } + apply(); + document.addEventListener('DOMContentLoaded', function () { apply(); unlock(); }); + window.addEventListener('load', function () { apply(); unlock(); }); + // Consent scripts often open their dialog a moment after load. + var runs = 0; + var timer = setInterval(function () { unlock(); if (++runs > 30) clearInterval(timer); }, 500); +})(); +'''; + } +} diff --git a/lib/services/feed_parser.dart b/lib/services/feed_parser.dart new file mode 100644 index 0000000..00091c5 --- /dev/null +++ b/lib/services/feed_parser.dart @@ -0,0 +1,198 @@ +import 'package:html/dom.dart' as dom; +import 'package:html/parser.dart' as html_parser; +import 'package:xml/xml.dart'; + +import '../models/article.dart'; +import '../models/news_source.dart'; + +/// Parses RSS 2.0, RSS 1.0 (RDF) and Atom feeds into [Article]s. +class FeedParser { + static const excerptLength = 400; + + static List
parse(String body, NewsSource source) { + final doc = XmlDocument.parse(body); + final root = doc.rootElement; + if (root.name.local == 'feed') { + return root.childElements + .where((e) => e.name.local == 'entry') + .map((e) => _parseAtomEntry(e, source)) + .whereType
() + .toList(); + } + // RSS 2.0 nests in , RSS 1.0 puts them at the root. + return root.descendantElements + .where((e) => e.name.local == 'item') + .map((e) => _parseRssItem(e, source)) + .whereType
() + .toList(); + } + + static Article? _parseRssItem(XmlElement item, NewsSource source) { + final title = htmlToText(_text(item, 'title')); + final link = _text(item, 'link').trim().isNotEmpty + ? _text(item, 'link').trim() + : _text(item, 'guid').trim(); + if (title.isEmpty || !link.startsWith('http')) return null; + + final descriptionHtml = _text(item, 'description'); + final contentHtml = _text(item, 'encoded', prefix: 'content'); + final date = _text(item, 'pubDate').isNotEmpty + ? _text(item, 'pubDate') + : _text(item, 'date', prefix: 'dc'); + + return Article( + title: title, + link: link, + source: source, + published: parseDate(date), + excerpt: _excerpt(descriptionHtml.isNotEmpty ? descriptionHtml : contentHtml), + contentHtml: contentHtml, + imageUrl: _imageFrom(item) ?? _firstImg(contentHtml) ?? _firstImg(descriptionHtml), + author: _nonEmpty(htmlToText(_text(item, 'creator', prefix: 'dc'))) ?? + _nonEmpty(_text(item, 'author')), + ); + } + + static Article? _parseAtomEntry(XmlElement entry, NewsSource source) { + final title = htmlToText(_text(entry, 'title')); + final links = entry.childElements.where((e) => e.name.local == 'link'); + final link = links + .where((l) => (l.getAttribute('rel') ?? 'alternate') == 'alternate') + .map((l) => l.getAttribute('href')) + .firstWhere((h) => h != null, orElse: () => null) ?? + links.map((l) => l.getAttribute('href')).firstWhere((h) => h != null, orElse: () => null); + if (title.isEmpty || link == null || !link.startsWith('http')) return null; + + final summaryHtml = _text(entry, 'summary'); + final contentHtml = _text(entry, 'content'); + final date = _text(entry, 'published').isNotEmpty + ? _text(entry, 'published') + : _text(entry, 'updated'); + final authorEl = _child(entry, 'author'); + + return Article( + title: title, + link: link, + source: source, + published: parseDate(date), + excerpt: _excerpt(summaryHtml.isNotEmpty ? summaryHtml : contentHtml), + contentHtml: contentHtml, + imageUrl: _imageFrom(entry) ?? _firstImg(contentHtml) ?? _firstImg(summaryHtml), + author: authorEl == null ? null : _nonEmpty(_text(authorEl, 'name')), + ); + } + + static XmlElement? _child(XmlElement parent, String local, {String? prefix}) { + for (final e in parent.childElements) { + if (e.name.local == local && (prefix == null || e.name.prefix == prefix)) { + return e; + } + } + return null; + } + + static String _text(XmlElement parent, String local, {String? prefix}) => + _child(parent, local, prefix: prefix)?.innerText.trim() ?? ''; + + static String? _nonEmpty(String s) => s.trim().isEmpty ? null : s.trim(); + + static String? _imageFrom(XmlElement item) { + for (final e in item.descendantElements) { + final local = e.name.local; + final url = e.getAttribute('url'); + if (url == null) continue; + if (local == 'thumbnail') return url; + if (local == 'content' && e.name.prefix == 'media') { + final medium = e.getAttribute('medium') ?? e.getAttribute('type') ?? 'image'; + if (medium.startsWith('image')) return url; + } + if (local == 'enclosure' && (e.getAttribute('type') ?? '').startsWith('image')) { + return url; + } + } + return null; + } + + static String? _firstImg(String html) { + if (!html.contains(' 0 ? lastSpace : excerptLength)}…'; + } + + /// Converts an HTML snippet to whitespace-normalized plain text. + static String htmlToText(String html) { + if (html.isEmpty) return ''; + final fragment = html_parser.parseFragment(html); + fragment.querySelectorAll('script, style').forEach((dom.Element e) => e.remove()); + return (fragment.text ?? '').replaceAll(RegExp(r'\s+'), ' ').trim(); + } + + static const _months = { + 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, + 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, + }; + + static const _zones = { + 'UT': 0, 'GMT': 0, 'Z': 0, 'UTC': 0, + 'EST': -5, 'EDT': -4, 'CST': -6, 'CDT': -5, + 'MST': -7, 'MDT': -6, 'PST': -8, 'PDT': -7, + 'CET': 1, 'CEST': 2, + }; + + static final _rfc822 = RegExp( + r'^(?:\w{3},\s*)?(\d{1,2})\s+(\w{3})\w*\s+(\d{2,4})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?\s*([+-]\d{4}|[A-Za-z]+)?', + ); + + /// Parses ISO 8601 (Atom) and RFC 822 (RSS) dates. Returns UTC. + static DateTime? parseDate(String raw) { + final s = raw.trim(); + if (s.isEmpty) return null; + final iso = DateTime.tryParse(s); + if (iso != null) return iso.toUtc(); + + final m = _rfc822.firstMatch(s); + if (m == null) return null; + final month = _months[m.group(2)!.toLowerCase()]; + if (month == null) return null; + var year = int.parse(m.group(3)!); + if (year < 100) year += 2000; + final utc = DateTime.utc( + year, + month, + int.parse(m.group(1)!), + int.parse(m.group(4)!), + int.parse(m.group(5)!), + int.parse(m.group(6) ?? '0'), + ); + + final zone = m.group(7); + var offset = Duration.zero; + if (zone != null && (zone.startsWith('+') || zone.startsWith('-'))) { + final sign = zone.startsWith('-') ? -1 : 1; + offset = Duration( + hours: int.parse(zone.substring(1, 3)), + minutes: int.parse(zone.substring(3, 5)), + ) * sign; + } else if (zone != null) { + offset = Duration(hours: _zones[zone.toUpperCase()] ?? 0); + } + return utc.subtract(offset); + } +} diff --git a/lib/services/feed_service.dart b/lib/services/feed_service.dart new file mode 100644 index 0000000..7d4c631 --- /dev/null +++ b/lib/services/feed_service.dart @@ -0,0 +1,98 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import '../models/article.dart'; +import '../models/news_source.dart'; +import 'feed_parser.dart'; + +class FeedResult { + const FeedResult(this.articles, this.errors); + + final List
articles; + + /// Source name -> error message for feeds that failed to load. + final Map errors; +} + +class FeedService { + FeedService({http.Client? client}) : _client = client ?? http.Client(); + + final http.Client _client; + + static const _timeout = Duration(seconds: 20); + + /// Fetches all [sources] in parallel. Failing feeds are reported in + /// [FeedResult.errors] instead of failing the whole refresh. + /// + /// [corsProxy] is only used on web, where browsers block cross-origin feed + /// requests. It is prepended to the feed URL, e.g. `https://proxy/?url=`. + Future fetchAll( + List sources, { + required Duration maxAge, + String corsProxy = '', + }) async { + final errors = {}; + final results = await Future.wait(sources.map((source) async { + try { + return await fetchSource(source, corsProxy: corsProxy); + } catch (e) { + errors[source.name] = _describe(e); + return
[]; + } + })); + + final cutoff = DateTime.now().toUtc().subtract(maxAge); + final seen = {}; + final articles =
[ + for (final list in results) + for (final a in list) + if ((a.published == null || a.published!.isAfter(cutoff)) && seen.add(a.id)) a, + ]; + articles.sort((a, b) { + final pa = a.published, pb = b.published; + if (pa == null && pb == null) return 0; + if (pa == null) return 1; + if (pb == null) return -1; + return pb.compareTo(pa); + }); + return FeedResult(articles, errors); + } + + Future> fetchSource(NewsSource source, {String corsProxy = ''}) async { + final url = kIsWeb && corsProxy.isNotEmpty + ? '$corsProxy${Uri.encodeComponent(source.feedUrl)}' + : source.feedUrl; + final response = await _client.get( + Uri.parse(url), + headers: { + 'Accept': 'application/rss+xml, application/atom+xml, application/xml, text/xml, */*', + if (!kIsWeb) 'User-Agent': 'DailyTechNews/0.1 (Flutter RSS reader)', + }, + ).timeout(_timeout); + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}'); + } + return FeedParser.parse(decodeBody(response.bodyBytes), source); + } + + /// Decodes feed bytes honoring the XML declaration's encoding; defaults to UTF-8. + static String decodeBody(List bytes) { + final head = latin1.decode(bytes.take(200).toList()).toLowerCase(); + final match = RegExp(r'''encoding=["']([\w-]+)["']''').firstMatch(head); + final encoding = match?.group(1); + if (encoding == 'iso-8859-1' || encoding == 'latin1' || encoding == 'windows-1252') { + return latin1.decode(bytes); + } + return utf8.decode(bytes, allowMalformed: true); + } + + static String _describe(Object e) { + final text = e.toString(); + if (kIsWeb && text.contains('ClientException')) { + return 'Blocked by the browser (CORS). Set a CORS proxy in Settings.'; + } + return text.replaceFirst('Exception: ', ''); + } +} diff --git a/lib/services/n8n_summarizer.dart b/lib/services/n8n_summarizer.dart new file mode 100644 index 0000000..983629b --- /dev/null +++ b/lib/services/n8n_summarizer.dart @@ -0,0 +1,91 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +import '../models/article.dart'; +import '../models/briefing.dart'; +import '../models/news_source.dart'; +import 'summarizer.dart'; + +/// Delegates summarizing to an existing n8n workflow via a Webhook trigger. +/// The request/response contract is documented in README.md. +class N8nSummarizer implements Summarizer { + N8nSummarizer({required this.webhookUrl, http.Client? client}) + : _client = client ?? http.Client(); + + final String webhookUrl; + final http.Client _client; + + @override + String get name => 'n8n workflow'; + + @override + Future summarizeArticle( + Article article, String text, SourceLanguage language) async { + final body = await _post({ + 'action': 'summarize_article', + 'language': language.name, + 'article': { + 'title': article.title, + 'url': article.link, + 'source': article.source.name, + 'published': article.published?.toIso8601String(), + 'text': text, + }, + }); + if (body is Map && body['summary'] is String) return body['summary'] as String; + if (body is String && body.trim().isNotEmpty) return body.trim(); + throw SummarizerException('n8n response has no "summary" field.'); + } + + @override + Future createBriefing( + List
articles, SourceLanguage language) async { + final input = BriefingInput(articles); + final body = await _post({ + 'action': 'daily_briefing', + 'language': language.name, + 'articles': input.toJsonList(), + }); + if (body is Map && body['topics'] is List) { + return input.toBriefing(body, name); + } + // Accept a plain text digest (e.g. the message the workflow posts to Discord). + final text = body is Map ? body['text'] ?? body['summary'] : body; + if (text is String && text.trim().isNotEmpty) { + return DailyBriefing( + createdAt: DateTime.now(), + intro: text.trim(), + topics: const [], + generatedBy: name, + ); + } + throw SummarizerException('n8n response has neither "topics" nor "text".'); + } + + Future _post(Map payload) async { + final http.Response response; + try { + response = await _client + .post( + Uri.parse(webhookUrl), + headers: {'content-type': 'application/json'}, + body: jsonEncode(payload), + ) + .timeout(const Duration(minutes: 3)); + } on Exception catch (e) { + throw SummarizerException('Could not reach the n8n webhook: $e'); + } + if (response.statusCode != 200) { + throw SummarizerException('n8n webhook returned HTTP ${response.statusCode}.'); + } + final text = utf8.decode(response.bodyBytes); + try { + final json = jsonDecode(text); + // "Respond to Webhook" with "All Incoming Items" wraps results in a list. + return json is List && json.isNotEmpty ? json.first : json; + } on FormatException { + return text; + } + } +} diff --git a/lib/services/paywall_service.dart b/lib/services/paywall_service.dart new file mode 100644 index 0000000..c4d9e7d --- /dev/null +++ b/lib/services/paywall_service.dart @@ -0,0 +1,105 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +import '../models/article.dart'; +import 'storage.dart'; + +/// Recognizes paid and sponsored articles so the feed can hide them. +/// +/// Most paid articles are marked in the title (heise+, Golem's "(g+)"). +/// SPIEGEL and t3n only mark them in the page's schema.org data +/// (`"isAccessibleForFree": false`), so for those sources each new article is +/// checked once in the background and the result is remembered. +class PaywallService { + PaywallService(this._storage, {http.Client? client}) + : _client = client ?? http.Client(), + _checks = _storage.loadPaywallChecks(); + + final Storage _storage; + final http.Client _client; + + /// Article URL -> (paid, checked at). + final Map _checks; + + static final paidTitle = RegExp( + r'^\s*(heise\+|\(g\+\)|SPIEGEL\+|Z\+|t3n Pro\b|c.t\+)', + caseSensitive: false, + ); + + static final sponsoredTitle = RegExp( + r'^\s*(Anzeige|Sponsored|Advertorial|Werbung|Promotion)\s*[:|]', + caseSensitive: false, + ); + + static final _marker = + RegExp(r'''"isAccessibleForFree"\s*:\s*"?(true|false)"?''', caseSensitive: false); + + /// Stop reading a page after this much without finding the marker. + static const _maxBytes = 1500000; + static const _concurrency = 6; + static const _keepFor = Duration(days: 14); + + bool isPaid(Article a) => paidTitle.hasMatch(a.title) || (_checks[a.link]?.paid ?? false); + + bool isSponsored(Article a) => sponsoredTitle.hasMatch(a.title); + + /// Checks articles from page-checked sources that haven't been seen yet. + /// Returns true if any new paid article was found. + Future checkPages(Iterable
articles) async { + final queue = articles + .where((a) => + a.source.checkPaywallOnPage && + !_checks.containsKey(a.link) && + !paidTitle.hasMatch(a.title)) + .toList(); + if (queue.isEmpty) return false; + + var foundPaid = false; + Future worker() async { + while (queue.isNotEmpty) { + final article = queue.removeLast(); + final paid = await _fetchIsPaid(article.link); + if (paid == null) continue; // network error: try again next refresh + _checks[article.link] = (paid: paid, checkedAt: DateTime.now()); + foundPaid |= paid; + } + } + + await Future.wait(List.generate(_concurrency, (_) => worker())); + final cutoff = DateTime.now().subtract(_keepFor); + _checks.removeWhere((_, v) => v.checkedAt.isBefore(cutoff)); + await _storage.savePaywallChecks(_checks); + return foundPaid; + } + + /// Streams the page and stops as soon as the schema.org marker shows up. + /// Returns null on network errors, false if the page has no marker. + Future _fetchIsPaid(String url) async { + try { + final request = http.Request('GET', Uri.parse(url)) + ..headers['User-Agent'] = 'Mozilla/5.0 (DailyTechNews)'; + final response = await _client.send(request).timeout(const Duration(seconds: 15)); + if (response.statusCode != 200) { + await response.stream.listen(null).cancel(); + return null; + } + var tail = ''; + var read = 0; + await for (final chunk in response.stream.timeout(const Duration(seconds: 15))) { + read += chunk.length; + // The marker is ASCII, so latin1 avoids errors on split UTF-8 sequences. + // Keep a little overlap in case the marker spans two chunks. + final text = tail + latin1.decode(chunk); + final match = _marker.firstMatch(text); + if (match != null) return match.group(1)!.toLowerCase() == 'false'; + if (read > _maxBytes) break; + tail = text.length > 64 ? text.substring(text.length - 64) : text; + } + return false; + } catch (_) { + return null; + } + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart new file mode 100644 index 0000000..dab305a --- /dev/null +++ b/lib/services/storage.dart @@ -0,0 +1,165 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/material.dart' show ThemeMode; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/app_settings.dart'; +import '../models/briefing.dart'; +import '../models/news_source.dart'; + +/// Persists settings, source selection and the last briefing. +/// The Claude API key goes to the platform keystore, everything else to +/// shared preferences. +class Storage { + Storage(this._prefs); + + static Future open() async => Storage(await SharedPreferences.getInstance()); + + final SharedPreferences _prefs; + final _secure = const FlutterSecureStorage(); + + static const _apiKey = 'claude_api_key'; + + Future loadSettings() async { + String apiKey = ''; + try { + apiKey = await _secure.read(key: _apiKey) ?? ''; + } catch (_) { + // Keystore unavailable (e.g. some web/desktop setups) -> user re-enters it. + } + return AppSettings( + aiProvider: AiProvider.values.byName(_prefs.getString('ai_provider') ?? 'none'), + claudeApiKey: apiKey, + claudeModel: _prefs.getString('claude_model') ?? 'claude-opus-5-5', + n8nWebhookUrl: _prefs.getString('n8n_webhook_url') ?? '', + summaryLanguage: + SourceLanguage.values.byName(_prefs.getString('summary_language') ?? 'de'), + maxAgeHours: _prefs.getInt('max_age_hours') ?? 24, + corsProxy: _prefs.getString('cors_proxy') ?? '', + hidePaid: _prefs.getBool('hide_paid') ?? true, + hideSponsored: _prefs.getBool('hide_sponsored') ?? true, + blockAds: _prefs.getBool('block_ads') ?? true, + hideCookieBanners: _prefs.getBool('hide_cookie_banners') ?? true, + acceptConsentWalls: _prefs.getBool('accept_consent_walls') ?? true, + themeMode: ThemeMode.values.asNameMap()[_prefs.getString('theme_mode')] ?? ThemeMode.system, + ); + } + + Future saveSettings(AppSettings s) async { + await _prefs.setString('ai_provider', s.aiProvider.name); + await _prefs.setString('claude_model', s.claudeModel); + await _prefs.setString('n8n_webhook_url', s.n8nWebhookUrl); + await _prefs.setString('summary_language', s.summaryLanguage.name); + await _prefs.setInt('max_age_hours', s.maxAgeHours); + await _prefs.setString('cors_proxy', s.corsProxy); + await _prefs.setBool('hide_paid', s.hidePaid); + await _prefs.setBool('hide_sponsored', s.hideSponsored); + await _prefs.setBool('block_ads', s.blockAds); + await _prefs.setBool('hide_cookie_banners', s.hideCookieBanners); + await _prefs.setBool('accept_consent_walls', s.acceptConsentWalls); + await _prefs.setString('theme_mode', s.themeMode.name); + try { + await _secure.write(key: _apiKey, value: s.claudeApiKey); + } catch (_) {} + } + + /// Null means "never configured" -> use each source's default. + Set? loadEnabledSourceIds() => + _prefs.getStringList('enabled_sources')?.toSet(); + + Future saveEnabledSourceIds(Set ids) => + _prefs.setStringList('enabled_sources', ids.toList()); + + List loadCustomSources() { + final raw = _prefs.getString('custom_sources'); + if (raw == null) return []; + return (jsonDecode(raw) as List) + .map((j) => NewsSource.custom(j as Map)) + .toList(); + } + + Future saveCustomSources(List sources) => _prefs.setString( + 'custom_sources', jsonEncode(sources.map((s) => s.toJson()).toList())); + + /// Article URL -> whether its page said it's paid, and when that was checked. + Map loadPaywallChecks() { + final raw = _prefs.getString('paywall_checks'); + if (raw == null) return {}; + try { + return (jsonDecode(raw) as Map).map((url, v) { + final entry = v as List; + return MapEntry(url, ( + paid: entry[0] as bool, + checkedAt: DateTime.fromMillisecondsSinceEpoch(entry[1] as int), + )); + }); + } catch (_) { + return {}; + } + } + + Future savePaywallChecks(Map checks) => + _prefs.setString( + 'paywall_checks', + jsonEncode(checks.map( + (url, v) => MapEntry(url, [v.paid, v.checkedAt.millisecondsSinceEpoch]))), + ); + + /// All saved briefings, newest first. Stored as a JSON file in the app's + /// private storage (preferences on web), since the history keeps growing. + Future> loadBriefingHistory() async { + List history; + try { + String? raw; + if (kIsWeb) { + raw = _prefs.getString(_historyKey); + } else { + final file = await _historyFile(); + if (await file.exists()) raw = await file.readAsString(); + } + history = raw == null + ? [] + : (jsonDecode(raw) as List) + .map((j) => DailyBriefing.fromJson(j as Map)) + .toList(); + } catch (_) { + history = []; + } + + // Earlier versions kept only the last briefing in preferences. + final legacy = _prefs.getString('last_briefing'); + if (legacy != null) { + try { + final briefing = DailyBriefing.fromJson(jsonDecode(legacy) as Map); + if (!history.any((b) => b.createdAt == briefing.createdAt)) history.add(briefing); + await saveBriefingHistory(history); + } catch (_) {} + await _prefs.remove('last_briefing'); + } + + history.sort((a, b) => b.createdAt.compareTo(a.createdAt)); + return history; + } + + Future saveBriefingHistory(List history) async { + final json = jsonEncode(history.map((b) => b.toJson()).toList()); + if (kIsWeb) { + await _prefs.setString(_historyKey, json); + return; + } + // Write to a temp file and rename, so a crash mid-write can't corrupt it. + final file = await _historyFile(); + final temp = File('${file.path}.tmp'); + await temp.writeAsString(json, flush: true); + await temp.rename(file.path); + } + + static const _historyKey = 'briefing_history'; + + Future _historyFile() async => + File('${(await getApplicationSupportDirectory()).path}/briefings.json'); +} diff --git a/lib/services/summarizer.dart b/lib/services/summarizer.dart new file mode 100644 index 0000000..2a0760a --- /dev/null +++ b/lib/services/summarizer.dart @@ -0,0 +1,88 @@ +import '../models/article.dart'; +import '../models/briefing.dart'; +import '../models/news_source.dart'; + +class SummarizerException implements Exception { + SummarizerException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// Something that can turn articles into summaries. Implemented by the +/// direct Claude API client and by the n8n webhook bridge. +abstract class Summarizer { + String get name; + + Future summarizeArticle(Article article, String text, SourceLanguage language); + + Future createBriefing(List
articles, SourceLanguage language); +} + +/// Shared prompt material and response mapping for all summarizers. +class BriefingInput { + BriefingInput(List
articles) + : byId = {for (var i = 0; i < articles.length; i++) 'a${i + 1}': articles[i]}; + + /// Short ids keep the prompt compact and are easy for the model to cite. + final Map byId; + + static const excerptChars = 220; + + String toPromptList() { + final buffer = StringBuffer(); + byId.forEach((id, a) { + final excerpt = a.excerpt.length > excerptChars + ? '${a.excerpt.substring(0, excerptChars)}…' + : a.excerpt; + buffer.writeln('[$id] (${a.source.name}) ${a.title}' + '${excerpt.isEmpty ? '' : ' — $excerpt'}'); + }); + return buffer.toString(); + } + + List> toJsonList() => [ + for (final e in byId.entries) + { + 'id': e.key, + 'title': e.value.title, + 'url': e.value.link, + 'source': e.value.source.name, + 'language': e.value.source.language.name, + 'published': e.value.published?.toIso8601String(), + 'excerpt': e.value.excerpt, + } + ]; + + /// Maps `{intro, topics: [{title, summary, article_ids}]}` onto a briefing. + DailyBriefing toBriefing(Map json, String generatedBy) { + final topics = (json['topics'] as List? ?? []).map((t) { + final topic = t as Map; + final ids = (topic['article_ids'] as List? ?? []).cast(); + return BriefingTopic( + title: topic['title'] as String? ?? '', + summary: topic['summary'] as String? ?? '', + sources: [ + for (final id in ids) + if (byId[id] != null) + ArticleRef( + title: byId[id]!.title, + url: byId[id]!.link, + sourceName: byId[id]!.source.name, + ), + ], + ); + }).toList(); + return DailyBriefing( + createdAt: DateTime.now(), + intro: json['intro'] as String? ?? '', + topics: topics, + generatedBy: generatedBy, + ); + } +} + +String languageName(SourceLanguage language) => + language == SourceLanguage.de ? 'German' : 'English'; diff --git a/lib/services/web_dark_mode.dart b/lib/services/web_dark_mode.dart new file mode 100644 index 0000000..ef2d74d --- /dev/null +++ b/lib/services/web_dark_mode.dart @@ -0,0 +1,26 @@ +/// Dark mode for the in-app "original page" view. +/// +/// When the phone itself is in dark mode, Android darkens pages on its own +/// (algorithmic darkening, plus `prefers-color-scheme: dark` for sites with a +/// dark design). When only the app is set to dark, Android doesn't, so this +/// stylesheet inverts the page and flips photos and videos back. +class WebDarkMode { + static const _css = 'html{filter:invert(1) hue-rotate(180deg)!important;' + 'background:#fff!important}' + 'img,picture,video,canvas,iframe,svg image,[style*="background-image"]' + '{filter:invert(1) hue-rotate(180deg)!important}'; + + static const script = ''' +(function () { + function apply() { + if (document.getElementById('tagesbyte-dark')) return; + var style = document.createElement('style'); + style.id = 'tagesbyte-dark'; + style.textContent = '$_css'; + (document.head || document.documentElement).appendChild(style); + } + apply(); + document.addEventListener('DOMContentLoaded', apply); +})(); +'''; +} diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart new file mode 100644 index 0000000..ae25723 --- /dev/null +++ b/lib/state/app_state.dart @@ -0,0 +1,267 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../data/default_sources.dart'; +import '../models/app_settings.dart'; +import '../models/article.dart'; +import '../models/briefing.dart'; +import '../models/news_source.dart'; +import '../services/article_extractor.dart'; +import '../services/claude_summarizer.dart'; +import '../services/consent_service.dart'; +import '../services/feed_service.dart'; +import '../services/n8n_summarizer.dart'; +import '../services/paywall_service.dart'; +import '../services/storage.dart'; +import '../services/summarizer.dart'; + +/// The result of an on-demand article summary. +class SummaryState { + const SummaryState.loading() : text = null, error = null; + const SummaryState.done(this.text) : error = null; + const SummaryState.failed(this.error) : text = null; + + final String? text; + final String? error; + + bool get isLoading => text == null && error == null; +} + +class AppState extends ChangeNotifier { + AppState(this._storage, {FeedService? feedService, ArticleExtractor? extractor}) + : _feeds = feedService ?? FeedService(), + consent = ConsentService(), + paywall = PaywallService(_storage) { + _extractor = extractor ?? ArticleExtractor(consent: consent); + } + + final Storage _storage; + final FeedService _feeds; + late final ArticleExtractor _extractor; + final PaywallService paywall; + + /// Consent cookies for sites with consent walls, shared with the web view. + final ConsentService consent; + + AppSettings settings = const AppSettings(); + List customSources = []; + Set enabledSourceIds = {}; + + /// Everything the feeds returned; see [visibleArticles] for what is shown. + List
articles = []; + Map feedErrors = {}; + bool loading = false; + DateTime? lastRefresh; + + /// Saved briefings, newest first. + List briefings = []; + DailyBriefing? get briefing => briefings.firstOrNull; + bool briefingLoading = false; + String? briefingError; + + final Map summaries = {}; + + /// Reader content per article id, shared by the reader view and the AI. + final Map> _content = {}; + + bool _isHidden(Article a) => + (settings.hidePaid && paywall.isPaid(a)) || + (settings.hideSponsored && paywall.isSponsored(a)); + + /// Articles after the paid/sponsored filters. The feed and the briefing use these. + List
get visibleArticles => articles.where((a) => !_isHidden(a)).toList(); + + int get hiddenCount => articles.where(_isHidden).length; + + List get allSources => [...defaultSources, ...customSources]; + + List get enabledSources => + allSources.where((s) => enabledSourceIds.contains(s.id)).toList(); + + Future init() async { + settings = await _storage.loadSettings(); + customSources = _storage.loadCustomSources(); + enabledSourceIds = _storage.loadEnabledSourceIds() ?? + defaultSources.where((s) => s.enabledByDefault).map((s) => s.id).toSet(); + briefings = await _storage.loadBriefingHistory(); + notifyListeners(); + await refresh(); + } + + Future refresh() async { + if (loading) return; + loading = true; + notifyListeners(); + final result = await _feeds.fetchAll( + enabledSources, + maxAge: Duration(hours: settings.maxAgeHours), + corsProxy: settings.corsProxy, + ); + articles = result.articles; + feedErrors = result.errors; + lastRefresh = DateTime.now(); + loading = false; + notifyListeners(); + // Runs in the background; hides newly found paid articles as they turn up. + unawaited(paywall.checkPages(articles).then((foundPaid) { + if (foundPaid) notifyListeners(); + })); + } + + // --- Sources ------------------------------------------------------------- + + Future setSourceEnabled(NewsSource source, bool enabled) async { + enabled ? enabledSourceIds.add(source.id) : enabledSourceIds.remove(source.id); + notifyListeners(); + await _storage.saveEnabledSourceIds(enabledSourceIds); + } + + /// Validates the feed by fetching it before adding. Returns an error message + /// or null on success. + Future addCustomSource({ + required String name, + required String feedUrl, + required SourceLanguage language, + }) async { + final uri = Uri.tryParse(feedUrl); + final source = NewsSource( + id: 'custom-${DateTime.now().millisecondsSinceEpoch}', + name: name, + feedUrl: feedUrl, + homepage: uri == null ? '' : '${uri.scheme}://${uri.host}', + language: language, + isCustom: true, + ); + try { + final items = await _feeds.fetchSource(source, corsProxy: settings.corsProxy); + if (items.isEmpty) return 'The feed loaded but contains no articles.'; + } catch (e) { + return 'Could not load feed: $e'; + } + customSources = [...customSources, source]; + enabledSourceIds.add(source.id); + await _storage.saveCustomSources(customSources); + await _storage.saveEnabledSourceIds(enabledSourceIds); + notifyListeners(); + return null; + } + + Future removeCustomSource(NewsSource source) async { + customSources = customSources.where((s) => s.id != source.id).toList(); + enabledSourceIds.remove(source.id); + await _storage.saveCustomSources(customSources); + await _storage.saveEnabledSourceIds(enabledSourceIds); + notifyListeners(); + } + + // --- Settings ------------------------------------------------------------ + + Future updateSettings(AppSettings updated) async { + final previous = settings; + final windowChanged = updated.maxAgeHours != settings.maxAgeHours || + updated.corsProxy != settings.corsProxy; + final aiChanged = updated.aiProvider != settings.aiProvider || + updated.claudeModel != settings.claudeModel || + updated.summaryLanguage != settings.summaryLanguage; + settings = updated; + if (aiChanged) summaries.clear(); + // Cached reader content may be a consent-wall teaser; reload it. + if (updated.acceptConsentWalls != previous.acceptConsentWalls) _content.clear(); + notifyListeners(); + await _storage.saveSettings(updated); + if (windowChanged) await refresh(); + } + + // --- Reading ------------------------------------------------------------- + + Future loadArticle(Article article) => _content.putIfAbsent( + article.id, + () => _extractor.load(article, + corsProxy: settings.corsProxy, acceptConsentWalls: settings.acceptConsentWalls)); + + /// Finds a loaded article by URL, or builds a minimal one (e.g. for links in + /// an older briefing whose articles have dropped out of the feed). + Article articleFor({required String url, required String title, required String sourceName}) { + for (final a in articles) { + if (a.link == url) return a; + } + final source = allSources.firstWhere( + (s) => s.name == sourceName, + orElse: () => NewsSource( + id: sourceName, + name: sourceName, + feedUrl: '', + homepage: '', + language: SourceLanguage.en, + ), + ); + return Article(title: title, link: url, source: source); + } + + // --- AI ------------------------------------------------------------------ + + Summarizer? get _summarizer => switch (settings.aiProvider) { + _ when !settings.aiConfigured => null, + AiProvider.claude => ClaudeSummarizer( + apiKey: settings.claudeApiKey, model: settings.claudeModel), + AiProvider.n8n => N8nSummarizer(webhookUrl: settings.n8nWebhookUrl), + AiProvider.none => null, + }; + + Future summarize(Article article) async { + final summarizer = _summarizer; + if (summarizer == null) return; + summaries[article.id] = const SummaryState.loading(); + notifyListeners(); + try { + final content = await loadArticle(article); + final text = content.plainText.length > article.excerpt.length + ? content.plainText + : article.excerpt; + final summary = + await summarizer.summarizeArticle(article, text, settings.summaryLanguage); + summaries[article.id] = SummaryState.done(summary); + } catch (e) { + summaries[article.id] = SummaryState.failed(e.toString()); + } + notifyListeners(); + } + + Future deleteBriefing(DailyBriefing briefing) async { + briefings = briefings.where((b) => !identical(b, briefing)).toList(); + notifyListeners(); + await _storage.saveBriefingHistory(briefings); + } + + /// Puts a deleted briefing back (undo). + Future restoreBriefing(DailyBriefing briefing) async { + briefings = [...briefings, briefing] + ..sort((a, b) => b.createdAt.compareTo(a.createdAt)); + notifyListeners(); + await _storage.saveBriefingHistory(briefings); + } + + Future generateBriefing() async { + final summarizer = _summarizer; + if (summarizer == null || briefingLoading) return; + final articles = visibleArticles; + if (articles.isEmpty) { + briefingError = 'No articles loaded yet. Pull to refresh the feed first.'; + notifyListeners(); + return; + } + briefingLoading = true; + briefingError = null; + notifyListeners(); + try { + final created = await summarizer.createBriefing(articles, settings.summaryLanguage); + briefings = [created, ...briefings]; + await _storage.saveBriefingHistory(briefings); + } catch (e) { + briefingError = e.toString(); + } + briefingLoading = false; + notifyListeners(); + } +} diff --git a/lib/ui/article_screen.dart b/lib/ui/article_screen.dart new file mode 100644 index 0000000..65dbbb9 --- /dev/null +++ b/lib/ui/article_screen.dart @@ -0,0 +1,546 @@ +import 'dart:collection'; +import 'dart:math'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; + +import '../models/article.dart'; +import '../services/article_extractor.dart'; +import '../services/consent_service.dart'; +import '../services/content_blocking.dart'; +import '../services/web_dark_mode.dart'; +import '../state/app_state.dart'; +import 'common.dart'; + +Future openArticle(BuildContext context, AppState state, Article article) { + // Otherwise the previous screen restores its focus (and keyboard) on return. + FocusManager.instance.primaryFocus?.unfocus(); + return Navigator.of(context).push(MaterialPageRoute( + builder: (_) => ArticleScreen(state: state, article: article), + )); +} + +enum _Mode { reader, original } + +/// Shows an article inside the app: a clean reader view by default, or the +/// original page in a WebView. +class ArticleScreen extends StatefulWidget { + const ArticleScreen({super.key, required this.state, required this.article}); + + final AppState state; + final Article article; + + @override + State createState() => _ArticleScreenState(); +} + +class _ArticleScreenState extends State { + late final Future _content = widget.state.loadArticle(widget.article); + _Mode _mode = _Mode.reader; + bool _webStarted = false; + InAppWebViewController? _web; + int _webProgress = 0; + + /// Only Android, iOS and macOS are set up; Windows would need WebView2 tooling. + static bool get webViewSupported => + !kIsWeb && + (defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS); + + /// Set when the user chooses "Open anyway" on a consent wall. + bool _allowConsentWall = false; + bool _stoppedAtWall = false; + bool _triedAccepting = false; + + Future _showOriginal() async { + if (!webViewSupported) { + openUrl(context, widget.article.link); + return; + } + // Reader view usually accepted the wall already; give the page its cookies. + await _syncConsentCookies(); + if (_stoppedAtWall) { + _stoppedAtWall = false; + _web?.loadUrl(urlRequest: URLRequest(url: WebUri(widget.article.link))); + } + if (!mounted) return; + setState(() { + _webStarted = true; + _mode = _Mode.original; + }); + } + + Future _syncConsentCookies() async { + final url = Uri.parse(widget.article.link); + final cookies = widget.state.consent.cookiesFor(url); + // Consent from Golem's simple button is valid for a day. + final expires = DateTime.now().add(const Duration(days: 1)).millisecondsSinceEpoch; + for (final cookie in cookies.entries) { + await CookieManager.instance().setCookie( + url: WebUri(widget.article.link), + name: cookie.key, + value: cookie.value, + domain: '.${ConsentService.domainOf(url)}', + isSecure: true, + expiresDate: expires, + ); + } + } + + void _openAnyway() { + _allowConsentWall = true; + _showOriginal(); + } + + Future _checkConsentWall(InAppWebViewController controller, WebUri? url) async { + if (url == null || + _stoppedAtWall || + _allowConsentWall || + !ContentBlocking.consentWall.hasMatch(url.toString())) { + return; + } + final settings = widget.state.settings; + final consent = widget.state.consent; + if (settings.acceptConsentWalls && !_triedAccepting && consent.canAccept(url)) { + _triedAccepting = true; + await controller.stopLoading(); + if (await consent.accept(url)) { + await _syncConsentCookies(); + await controller.loadUrl(urlRequest: URLRequest(url: WebUri(widget.article.link))); + return; + } + } + if (!settings.hideCookieBanners) return; + await controller.stopLoading(); + _stoppedAtWall = true; + if (!mounted) return; + setState(() => _mode = _Mode.reader); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + duration: const Duration(seconds: 8), + content: Text('${widget.article.source.name} only opens its website after you accept ' + 'tracking or subscribe. Showing reader view instead.'), + action: SnackBarAction( + label: 'Open anyway', + onPressed: _openAnyway, + ), + )); + } + + Widget _buildWebView() { + final settings = widget.state.settings; + final script = ContentBlocking.cosmeticScript( + ads: settings.blockAds, cookies: settings.hideCookieBanners); + final appDark = Theme.of(context).brightness == Brightness.dark; + final systemDark = MediaQuery.platformBrightnessOf(context) == Brightness.dark; + return InAppWebView( + initialUrlRequest: URLRequest(url: WebUri(widget.article.link)), + initialSettings: InAppWebViewSettings( + contentBlockers: ContentBlocking.blockers( + ads: settings.blockAds, cookies: settings.hideCookieBanners), + // Only takes effect when the phone is in dark mode; see WebDarkMode. + algorithmicDarkeningAllowed: appDark, + ), + initialUserScripts: UnmodifiableListView([ + if (script != null) + UserScript(source: script, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START), + if (appDark && !systemDark) + UserScript( + source: WebDarkMode.script, + injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START), + ]), + onWebViewCreated: (controller) => _web = controller, + // Redirects don't reliably fire every callback, so check them all. + onLoadStart: _checkConsentWall, + onLoadStop: _checkConsentWall, + onUpdateVisitedHistory: (controller, url, _) => _checkConsentWall(controller, url), + onProgressChanged: (_, progress) { + if (mounted) setState(() => _webProgress = progress); + }, + ); + } + + Future _handleBack() async { + // In the original page, back walks the page's own history first. + final web = _web; + if (_mode == _Mode.original && web != null && await web.canGoBack()) { + await web.goBack(); + } else if (mounted) { + Navigator.of(context).pop(); + } + } + + @override + Widget build(BuildContext context) { + final article = widget.article; + final original = _mode == _Mode.original; + return PopScope( + canPop: !original, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _handleBack(); + }, + child: Scaffold( + appBar: AppBar( + title: Text(article.source.name), + actions: [ + if (webViewSupported) + IconButton( + tooltip: original ? 'Reader view' : 'Original page', + icon: Icon(original ? Icons.article_outlined : Icons.public), + onPressed: original + ? () => setState(() => _mode = _Mode.reader) + : _showOriginal, + ), + PopupMenuButton( + onSelected: (_) => openUrl(context, article.link), + itemBuilder: (_) => const [ + PopupMenuItem(value: 'browser', child: Text('Open in browser')), + ], + ), + ], + bottom: PreferredSize( + preferredSize: const Size.fromHeight(2), + child: original && _webProgress < 100 + ? LinearProgressIndicator(value: _webProgress / 100, minHeight: 2) + : const SizedBox(height: 2), + ), + ), + // IndexedStack keeps the reader's scroll position and the loaded page + // when switching back and forth. + body: IndexedStack( + index: original ? 1 : 0, + children: [ + _ReaderView( + state: widget.state, + article: article, + content: _content, + onShowOriginal: _showOriginal, + onOpenAnyway: _openAnyway, + ), + if (_webStarted) _buildWebView() else const SizedBox(), + ], + ), + floatingActionButton: original && widget.state.settings.aiConfigured + ? FloatingActionButton.extended( + onPressed: () => showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (_) => SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(20, 0, 20, 24), + child: AiSummaryCard(state: widget.state, article: article), + ), + ), + ), + icon: const Icon(Icons.auto_awesome), + label: const Text('AI summary'), + ) + : null, + ), + ); + } +} + +class _ReaderView extends StatelessWidget { + const _ReaderView({ + required this.state, + required this.article, + required this.content, + required this.onShowOriginal, + required this.onOpenAnyway, + }); + + final AppState state; + final Article article; + final Future content; + final VoidCallback onShowOriginal; + + /// Opens the original page even if it is a consent wall. + final VoidCallback onOpenAnyway; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final muted = theme.colorScheme.onSurfaceVariant; + final meta = [ + if (article.published != null) formatDateTime(article.published!), + if (article.author != null) article.author!, + ].join(' · '); + + return SelectionArea( + child: FutureBuilder( + future: content, + builder: (context, snapshot) { + final loaded = snapshot.data; + var blocks = loaded?.blocks ?? const []; + // The page's own hero image duplicates the feed image shown on top. + if (article.imageUrl != null) { + blocks = blocks.skipWhile((b) => b.type == BlockType.image).toList(); + } + final isFull = loaded != null && + loaded.plainText.length >= max(400, article.excerpt.length * 2); + // Skip the lead if the body already starts with it. + final firstText = blocks.where((b) => b.type == BlockType.paragraph).firstOrNull; + final showLead = article.excerpt.isNotEmpty && + (firstText == null || + !firstText.text.startsWith( + article.excerpt.substring(0, min(40, article.excerpt.length)))); + + return ListView( + padding: const EdgeInsets.only(bottom: 48), + children: [ + if (article.imageUrl != null) + Image.network( + article.imageUrl!, + fit: BoxFit.cover, + webHtmlElementStrategy: WebHtmlElementStrategy.prefer, + // Take up space only once the image has loaded, so a broken + // image leaves no gap. + frameBuilder: (_, child, frame, __) => frame == null + ? const SizedBox.shrink() + : AspectRatio(aspectRatio: 16 / 9, child: child), + errorBuilder: (_, __, ___) => const SizedBox.shrink(), + ), + Padding( + padding: const EdgeInsets.fromLTRB(20, 20, 20, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (meta.isNotEmpty) + Text(meta, + style: theme.textTheme.labelMedium + ?.copyWith(color: theme.colorScheme.primary)), + const SizedBox(height: 8), + Text(article.title, style: theme.textTheme.headlineSmall), + if (showLead) ...[ + const SizedBox(height: 12), + Text(article.excerpt, + style: theme.textTheme.titleMedium + ?.copyWith(color: muted, height: 1.5)), + ], + const SizedBox(height: 20), + AiSummaryCard(state: state, article: article), + const SizedBox(height: 20), + if (loaded == null) + const Padding( + padding: EdgeInsets.symmetric(vertical: 32), + child: Center(child: CircularProgressIndicator()), + ) + else if (!isFull) + _TeaserOnlyNotice( + sourceName: article.source.name, + consentWall: loaded.consentWall, + onShowOriginal: loaded.consentWall ? onOpenAnyway : onShowOriginal, + ), + if (isFull) + for (final block in blocks) + if (block.text != article.imageUrl) _BlockView(block: block), + if (loaded != null) ...[ + const SizedBox(height: 24), + const Divider(), + TextButton.icon( + onPressed: onShowOriginal, + icon: const Icon(Icons.public, size: 18), + label: Text( + 'Original article on ${Uri.parse(article.link).host.replaceFirst('www.', '')}'), + ), + ], + ], + ), + ), + ], + ); + }, + ), + ); + } +} + +class _BlockView extends StatelessWidget { + const _BlockView({required this.block}); + + final ReaderBlock block; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final body = theme.textTheme.bodyLarge?.copyWith(height: 1.65); + return switch (block.type) { + BlockType.heading => Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Text(block.text, + style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600)), + ), + BlockType.paragraph => Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Text(block.text, style: body), + ), + BlockType.listItem => Padding( + padding: const EdgeInsets.only(bottom: 8, left: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('• ', style: body), + Expanded(child: Text(block.text, style: body)), + ], + ), + ), + BlockType.quote => Container( + margin: const EdgeInsets.only(bottom: 16), + padding: const EdgeInsets.only(left: 16), + decoration: BoxDecoration( + border: Border(left: BorderSide(color: theme.colorScheme.primary, width: 3)), + ), + child: Text(block.text, style: body?.copyWith(fontStyle: FontStyle.italic)), + ), + BlockType.code => Container( + margin: const EdgeInsets.only(bottom: 16), + padding: const EdgeInsets.all(12), + width: double.infinity, + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(8), + ), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Text(block.text, + style: const TextStyle(fontFamily: 'monospace', fontSize: 13)), + ), + ), + BlockType.image => Padding( + padding: const EdgeInsets.only(bottom: 8, top: 4), + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.network( + block.text, + width: double.infinity, + fit: BoxFit.fitWidth, + webHtmlElementStrategy: WebHtmlElementStrategy.prefer, + errorBuilder: (_, __, ___) => const SizedBox(), + ), + ), + ), + BlockType.caption => Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Text(block.text, + style: theme.textTheme.bodySmall + ?.copyWith(color: theme.colorScheme.onSurfaceVariant)), + ), + }; + } +} + +class _TeaserOnlyNotice extends StatelessWidget { + const _TeaserOnlyNotice({ + required this.sourceName, + required this.consentWall, + required this.onShowOriginal, + }); + + final String sourceName; + final bool consentWall; + final VoidCallback onShowOriginal; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: theme.colorScheme.secondaryContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + consentWall + ? '$sourceName only shows its articles after you accept tracking or ' + 'subscribe, so only the teaser is available here.' + : "The full text couldn't be loaded in reader view. It may be behind a " + 'paywall or the site blocks it.', + style: TextStyle(color: theme.colorScheme.onSecondaryContainer), + ), + const SizedBox(height: 8), + FilledButton.tonalIcon( + onPressed: onShowOriginal, + icon: const Icon(Icons.public), + label: Text(consentWall ? 'Open website anyway' : 'Show original page'), + ), + ], + ), + ); + } +} + +/// The "Summarize with AI" button and its result. +class AiSummaryCard extends StatelessWidget { + const AiSummaryCard({super.key, required this.state, required this.article}); + + final AppState state; + final Article article; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: state, + builder: (context, _) { + final theme = Theme.of(context); + final summary = state.summaries[article.id]; + + if (!state.settings.aiConfigured) { + return Text( + 'Tip: set up Claude or your n8n workflow in Settings to get AI summaries.', + style: theme.textTheme.bodySmall + ?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ); + } + if (summary == null) { + return FilledButton.tonalIcon( + onPressed: () => state.summarize(article), + icon: const Icon(Icons.auto_awesome), + label: const Text('Summarize with AI'), + ); + } + + return Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.auto_awesome, size: 18, color: theme.colorScheme.tertiary), + const SizedBox(width: 8), + Text('AI summary', style: theme.textTheme.titleSmall), + ], + ), + const SizedBox(height: 12), + if (summary.isLoading) + const Row(children: [ + SizedBox( + width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)), + SizedBox(width: 12), + Text('Reading the article…'), + ]) + else if (summary.error != null) ...[ + Text(summary.error!, style: TextStyle(color: theme.colorScheme.error)), + TextButton( + onPressed: () => state.summarize(article), child: const Text('Try again')), + ] else + Text(summary.text!, + style: theme.textTheme.bodyMedium?.copyWith(height: 1.5)), + ], + ), + ); + }, + ); + } +} diff --git a/lib/ui/briefing_history_screen.dart b/lib/ui/briefing_history_screen.dart new file mode 100644 index 0000000..f7403eb --- /dev/null +++ b/lib/ui/briefing_history_screen.dart @@ -0,0 +1,191 @@ +import 'package:flutter/material.dart'; + +import '../models/briefing.dart'; +import '../state/app_state.dart'; +import 'briefing_screen.dart'; +import 'common.dart'; + +/// All saved briefings, newest first, grouped by month. +class BriefingHistoryScreen extends StatelessWidget { + const BriefingHistoryScreen({super.key, required this.state}); + + final AppState state; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: state, + builder: (context, _) { + final briefings = state.briefings; + return Scaffold( + appBar: AppBar( + title: const Text('Briefing history'), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(24), + child: Container( + alignment: AlignmentDirectional.centerStart, + padding: const EdgeInsetsDirectional.only(start: 16, bottom: 8), + child: Text( + '${briefings.length} saved · swipe left to delete', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + ), + body: briefings.isEmpty + ? const EmptyState( + icon: Icons.history, + title: 'No briefings yet', + message: 'Every briefing you generate is saved here.', + ) + : ListView( + padding: const EdgeInsets.only(bottom: 24), + children: [ + for (final (i, briefing) in briefings.indexed) ...[ + if (i == 0 || !_sameMonth(briefings[i - 1].createdAt, briefing.createdAt)) + _MonthHeader(date: briefing.createdAt), + _HistoryTile(state: state, briefing: briefing, isLatest: i == 0), + ], + ], + ), + ); + }, + ); + } + + static bool _sameMonth(DateTime a, DateTime b) { + final la = a.toLocal(), lb = b.toLocal(); + return la.year == lb.year && la.month == lb.month; + } +} + +class _MonthHeader extends StatelessWidget { + const _MonthHeader({required this.date}); + + final DateTime date; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final d = date.toLocal(); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 20, 16, 4), + child: Text('${monthNames[d.month - 1]} ${d.year}', + style: theme.textTheme.titleSmall?.copyWith(color: theme.colorScheme.primary)), + ); + } +} + +class _HistoryTile extends StatelessWidget { + const _HistoryTile({required this.state, required this.briefing, required this.isLatest}); + + final AppState state; + final DailyBriefing briefing; + final bool isLatest; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final d = briefing.createdAt.toLocal(); + final time = '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}'; + return Dismissible( + key: ObjectKey(briefing), + direction: DismissDirection.endToStart, + background: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: 24), + color: theme.colorScheme.errorContainer, + child: Icon(Icons.delete_outline, color: theme.colorScheme.onErrorContainer), + ), + onDismissed: (_) { + state.deleteBriefing(briefing); + final messenger = ScaffoldMessenger.of(context); + messenger.hideCurrentSnackBar(); + messenger.showSnackBar(SnackBar( + content: Text('Briefing from ${formatDateTime(briefing.createdAt)} deleted'), + action: SnackBarAction( + label: 'Undo', + onPressed: () => state.restoreBriefing(briefing), + ), + )); + }, + child: ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + leading: _DateBadge(date: d), + title: Text( + '${weekdayNames[d.weekday - 1]} · $time${isLatest ? ' · latest' : ''}', + style: theme.textTheme.titleSmall, + ), + subtitle: Text( + briefing.intro.isNotEmpty + ? briefing.intro + : briefing.topics.map((t) => t.title).join(' · '), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + trailing: briefing.topics.isEmpty + ? null + : Text( + '${briefing.topics.length}\n${briefing.topics.length == 1 ? 'topic' : 'topics'}', + textAlign: TextAlign.center, + style: theme.textTheme.labelSmall + ?.copyWith(color: theme.colorScheme.onSurfaceVariant)), + onTap: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => BriefingDetailScreen(state: state, briefing: briefing), + )), + ), + ); + } +} + +class _DateBadge extends StatelessWidget { + const _DateBadge({required this.date}); + + final DateTime date; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + width: 48, + padding: const EdgeInsets.symmetric(vertical: 6), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${date.day}', + style: theme.textTheme.titleMedium?.copyWith( + color: theme.colorScheme.onPrimaryContainer, fontWeight: FontWeight.w600)), + Text(monthNames[date.month - 1].substring(0, 3), + style: theme.textTheme.labelSmall + ?.copyWith(color: theme.colorScheme.onPrimaryContainer)), + ], + ), + ); + } +} + +/// One saved briefing, read-only. +class BriefingDetailScreen extends StatelessWidget { + const BriefingDetailScreen({super.key, required this.state, required this.briefing}); + + final AppState state; + final DailyBriefing briefing; + + @override + Widget build(BuildContext context) { + final d = briefing.createdAt.toLocal(); + return Scaffold( + appBar: AppBar( + title: Text( + '${weekdayNames[d.weekday - 1]}, ${d.day} ${monthNames[d.month - 1]} ${d.year}')), + body: ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 32), + children: briefingContent(context, state, briefing), + ), + ); + } +} diff --git a/lib/ui/briefing_screen.dart b/lib/ui/briefing_screen.dart new file mode 100644 index 0000000..f9a01aa --- /dev/null +++ b/lib/ui/briefing_screen.dart @@ -0,0 +1,211 @@ +import 'package:flutter/material.dart'; + +import '../models/briefing.dart'; +import '../state/app_state.dart'; +import 'article_screen.dart'; +import 'briefing_history_screen.dart'; +import 'common.dart'; + +class BriefingScreen extends StatelessWidget { + const BriefingScreen({super.key, required this.state, required this.openSettings}); + + final AppState state; + final VoidCallback openSettings; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: state, + builder: (context, _) { + final briefing = state.briefing; + final canGenerate = + state.settings.aiConfigured && !state.briefingLoading && !state.loading; + return Scaffold( + appBar: AppBar( + title: const Text('Daily Briefing'), + actions: [ + if (state.briefings.isNotEmpty) + IconButton( + tooltip: 'History', + icon: const Icon(Icons.history), + onPressed: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => BriefingHistoryScreen(state: state), + )), + ), + if (briefing != null && state.settings.aiConfigured) + IconButton( + tooltip: 'Regenerate', + onPressed: canGenerate ? state.generateBriefing : null, + icon: const Icon(Icons.refresh), + ), + ], + ), + body: _body(context, briefing, canGenerate), + ); + }, + ); + } + + Widget _body(BuildContext context, DailyBriefing? briefing, bool canGenerate) { + if (!state.settings.aiConfigured) { + return EmptyState( + icon: Icons.auto_awesome, + title: 'AI is not set up yet', + message: 'Add a Claude API key or your n8n webhook to get a daily briefing ' + 'of the most important stories.', + action: FilledButton(onPressed: openSettings, child: const Text('Open Settings')), + ); + } + if (state.briefingLoading) { + return EmptyState( + icon: Icons.hourglass_top, + title: 'Reading ${state.visibleArticles.length} headlines…', + message: 'This usually takes 10-60 seconds.', + action: const SizedBox(width: 160, child: LinearProgressIndicator()), + ); + } + final generateButton = FilledButton.icon( + onPressed: canGenerate ? state.generateBriefing : null, + icon: const Icon(Icons.auto_awesome), + label: Text(state.loading + ? 'Waiting for feeds…' + : 'Generate from ${state.visibleArticles.length} articles'), + ); + if (briefing == null) { + return EmptyState( + icon: Icons.summarize_outlined, + title: 'No briefing yet', + message: state.briefingError ?? + 'Let the AI pick and summarize the most important stories of the day.', + action: generateButton, + ); + } + + final theme = Theme.of(context); + final outdated = !isSameDay(briefing.createdAt, DateTime.now()); + return ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 32), + children: [ + if (state.briefingError != null) + _Notice(text: state.briefingError!, color: theme.colorScheme.errorContainer), + if (outdated) + _Notice( + text: 'This briefing is from ${formatDateTime(briefing.createdAt)}.', + color: theme.colorScheme.secondaryContainer, + action: TextButton( + onPressed: canGenerate ? state.generateBriefing : null, + child: const Text('Update')), + ), + ...briefingContent(context, state, briefing), + ], + ); + } +} + +/// Date line, intro and topic cards of a briefing. Shared by today's briefing +/// and the history. +List briefingContent(BuildContext context, AppState state, DailyBriefing briefing) { + final theme = Theme.of(context); + return [ + Text( + '${formatDateTime(briefing.createdAt)} · ${briefing.generatedBy}', + style: theme.textTheme.labelMedium?.copyWith(color: theme.colorScheme.primary), + ), + const SizedBox(height: 8), + Text(briefing.intro, style: theme.textTheme.titleMedium?.copyWith(height: 1.4)), + const SizedBox(height: 16), + for (final (i, topic) in briefing.topics.indexed) ...[ + _TopicCard(state: state, number: i + 1, topic: topic), + const SizedBox(height: 12), + ], + ]; +} + +class _TopicCard extends StatelessWidget { + const _TopicCard({required this.state, required this.number, required this.topic}); + + final AppState state; + final int number; + final BriefingTopic topic; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CircleAvatar( + radius: 14, + backgroundColor: theme.colorScheme.primaryContainer, + child: Text('$number', + style: theme.textTheme.labelLarge + ?.copyWith(color: theme.colorScheme.onPrimaryContainer)), + ), + const SizedBox(width: 12), + Expanded(child: Text(topic.title, style: theme.textTheme.titleMedium)), + ], + ), + const SizedBox(height: 10), + Text(topic.summary, style: theme.textTheme.bodyMedium?.copyWith(height: 1.5)), + if (topic.sources.isNotEmpty) ...[ + const SizedBox(height: 12), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + for (final ref in topic.sources) + Tooltip( + message: ref.title, + child: ActionChip( + avatar: const Icon(Icons.article_outlined, size: 16), + label: Text(ref.sourceName), + onPressed: () => openArticle( + context, + state, + state.articleFor( + url: ref.url, title: ref.title, sourceName: ref.sourceName), + ), + ), + ), + ], + ), + ], + ], + ), + ), + ); + } +} + +class _Notice extends StatelessWidget { + const _Notice({required this.text, required this.color, this.action}); + + final String text; + final Color color; + final Widget? action; + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(8)), + child: Row( + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Text(text), + )), + if (action != null) action!, + ], + ), + ); + } +} diff --git a/lib/ui/common.dart b/lib/ui/common.dart new file mode 100644 index 0000000..1cc0669 --- /dev/null +++ b/lib/ui/common.dart @@ -0,0 +1,86 @@ +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +/// User-facing app name. Platform launcher labels (AndroidManifest, Info.plist, +/// web/manifest.json, windows/runner) are set separately. +const appName = 'Tagesbyte'; + +String timeAgo(DateTime? date) { + if (date == null) return ''; + final diff = DateTime.now().difference(date.toLocal()); + if (diff.inMinutes < 1) return 'just now'; + if (diff.inMinutes < 60) return '${diff.inMinutes} min ago'; + if (diff.inHours < 24) return '${diff.inHours} h ago'; + if (diff.inDays == 1) return 'yesterday'; + return '${diff.inDays} days ago'; +} + +String formatDateTime(DateTime date) { + final d = date.toLocal(); + String two(int n) => n.toString().padLeft(2, '0'); + return '${two(d.day)}.${two(d.month)}.${d.year} ${two(d.hour)}:${two(d.minute)}'; +} + +const weekdayNames = [ + 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', +]; + +const monthNames = [ + 'January', 'February', 'March', 'April', 'May', 'June', + 'July', 'August', 'September', 'October', 'November', 'December', +]; + +bool isSameDay(DateTime a, DateTime b) => + a.year == b.year && a.month == b.month && a.day == b.day; + +Future openUrl(BuildContext context, String url) async { + final ok = await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication); + if (!ok && context.mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('Could not open $url'))); + } +} + +/// Centered icon + text + optional action, used for empty and error states. +class EmptyState extends StatelessWidget { + const EmptyState({ + super.key, + required this.icon, + required this.title, + this.message, + this.action, + }); + + final IconData icon; + final String title; + final String? message; + final Widget? action; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 56, color: theme.colorScheme.primary), + const SizedBox(height: 16), + Text(title, style: theme.textTheme.titleMedium, textAlign: TextAlign.center), + if (message != null) ...[ + const SizedBox(height: 8), + Text( + message!, + style: theme.textTheme.bodyMedium + ?.copyWith(color: theme.colorScheme.onSurfaceVariant), + textAlign: TextAlign.center, + ), + ], + if (action != null) ...[const SizedBox(height: 20), action!], + ], + ), + ), + ); + } +} diff --git a/lib/ui/feed_screen.dart b/lib/ui/feed_screen.dart new file mode 100644 index 0000000..2440006 --- /dev/null +++ b/lib/ui/feed_screen.dart @@ -0,0 +1,322 @@ +import 'package:flutter/material.dart'; + +import '../models/article.dart'; +import '../models/news_source.dart'; +import '../state/app_state.dart'; +import 'article_screen.dart'; +import 'common.dart'; + +class FeedScreen extends StatefulWidget { + const FeedScreen({super.key, required this.state}); + + final AppState state; + + @override + State createState() => _FeedScreenState(); +} + +class _FeedScreenState extends State { + SourceLanguage? _language; + String? _sourceId; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: widget.state, + builder: (context, _) { + final state = widget.state; + final all = state.visibleArticles; + final visible = all + .where((a) => _language == null || a.source.language == _language) + .where((a) => _sourceId == null || a.source.id == _sourceId) + .toList(); + final sourcesInFeed = {for (final a in all) a.source.id: a.source}; + final hidden = state.hiddenCount; + + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text(appName), + Text( + state.loading + ? 'Loading feeds…' + : '${all.length} articles · last ${state.settings.maxAgeHours} h' + '${hidden > 0 ? ' · $hidden paid/ads hidden' : ''}', + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + actions: [ + IconButton( + tooltip: 'Refresh', + onPressed: state.loading ? null : state.refresh, + icon: const Icon(Icons.refresh), + ), + ], + bottom: PreferredSize( + preferredSize: const Size.fromHeight(52), + child: _filterBar(sourcesInFeed.values.toList()), + ), + ), + body: Column( + children: [ + if (state.loading) const LinearProgressIndicator(), + if (state.feedErrors.isNotEmpty && !state.loading) + _ErrorBanner(errors: state.feedErrors), + Expanded( + child: RefreshIndicator( + onRefresh: state.refresh, + child: _list(state, visible), + ), + ), + ], + ), + ); + }, + ); + } + + Widget _list(AppState state, List
visible) { + if (visible.isEmpty) { + // ListView keeps pull-to-refresh working on the empty state. + return ListView( + children: [ + const SizedBox(height: 80), + EmptyState( + icon: state.loading ? Icons.hourglass_top : Icons.inbox_outlined, + title: state.loading + ? 'Fetching the latest news…' + : state.enabledSources.isEmpty + ? 'No sources enabled' + : 'No articles found', + message: state.loading + ? null + : state.enabledSources.isEmpty + ? 'Turn on some feeds in the Sources tab.' + : 'Pull down to refresh or change the filter.', + ), + ], + ); + } + return ListView.separated( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), + itemCount: visible.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, i) => ArticleCard( + article: visible[i], + hasSummary: state.summaries[visible[i].id]?.text != null, + isPaid: state.paywall.isPaid(visible[i]), + onTap: () => openArticle(context, state, visible[i]), + ), + ); + } + + Widget _filterBar(List sources) { + sources.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + return SizedBox( + height: 52, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + children: [ + ChoiceChip( + label: const Text('All'), + selected: _language == null, + onSelected: (_) => setState(() => _language = null), + ), + for (final lang in SourceLanguage.values) ...[ + const SizedBox(width: 8), + ChoiceChip( + label: Text('${lang.flag} ${lang.label}'), + selected: _language == lang, + onSelected: (_) => setState(() => _language = lang), + ), + ], + const SizedBox(width: 8), + PopupMenuButton( + tooltip: 'Filter by source', + onSelected: (id) => setState(() => _sourceId = id), + itemBuilder: (_) => [ + const PopupMenuItem(value: null, child: Text('All sources')), + for (final s in sources) PopupMenuItem(value: s.id, child: Text(s.name)), + ], + child: Chip( + avatar: const Icon(Icons.filter_list, size: 18), + label: Text(_sourceId == null + ? 'All sources' + : sources + .firstWhere((s) => s.id == _sourceId, + orElse: () => sources.isEmpty ? _placeholder : sources.first) + .name), + ), + ), + ], + ), + ); + } + + static const _placeholder = NewsSource( + id: '', name: 'All sources', feedUrl: '', homepage: '', language: SourceLanguage.en); +} + +class ArticleCard extends StatelessWidget { + const ArticleCard({ + super.key, + required this.article, + required this.onTap, + this.hasSummary = false, + this.isPaid = false, + }); + + final Article article; + final VoidCallback onTap; + final bool hasSummary; + + /// Only shown when paid articles aren't hidden. + final bool isPaid; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final muted = theme.colorScheme.onSurfaceVariant; + return Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text(article.source.language.flag), + const SizedBox(width: 6), + Flexible( + child: Text( + article.source.name, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w600), + ), + ), + if (article.published != null) + Text(' · ${timeAgo(article.published)}', + style: theme.textTheme.labelMedium?.copyWith(color: muted)), + if (isPaid) ...[ + const SizedBox(width: 6), + Tooltip( + message: 'Paid article', + child: Icon(Icons.lock_outline, size: 14, color: muted), + ), + ], + if (hasSummary) ...[ + const SizedBox(width: 6), + Icon(Icons.auto_awesome, size: 14, color: theme.colorScheme.tertiary), + ], + ], + ), + const SizedBox(height: 6), + Text( + article.title, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleSmall?.copyWith(height: 1.3), + ), + if (article.excerpt.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + article.excerpt, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall?.copyWith(color: muted), + ), + ], + ], + ), + ), + if (article.imageUrl != null) ...[ + const SizedBox(width: 12), + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.network( + article.imageUrl!, + width: 84, + height: 84, + fit: BoxFit.cover, + webHtmlElementStrategy: WebHtmlElementStrategy.prefer, + errorBuilder: (_, __, ___) => const SizedBox(width: 84, height: 84), + ), + ), + ], + ], + ), + ), + ), + ); + } +} + +class _ErrorBanner extends StatelessWidget { + const _ErrorBanner({required this.errors}); + + final Map errors; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Material( + color: theme.colorScheme.errorContainer, + child: InkWell( + onTap: () => showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Some feeds failed'), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final e in errors.entries) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text.rich(TextSpan(children: [ + TextSpan( + text: '${e.key}: ', + style: const TextStyle(fontWeight: FontWeight.bold)), + TextSpan(text: e.value), + ])), + ), + ], + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK')), + ], + ), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Icon(Icons.warning_amber, size: 18, color: theme.colorScheme.onErrorContainer), + const SizedBox(width: 8), + Expanded( + child: Text( + '${errors.length} feed(s) could not be loaded. Tap for details.', + style: TextStyle(color: theme.colorScheme.onErrorContainer), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/ui/home_shell.dart b/lib/ui/home_shell.dart new file mode 100644 index 0000000..386bcf3 --- /dev/null +++ b/lib/ui/home_shell.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; + +import '../state/app_state.dart'; +import 'briefing_screen.dart'; +import 'feed_screen.dart'; +import 'settings_screen.dart'; +import 'sources_screen.dart'; + +class HomeShell extends StatefulWidget { + const HomeShell({super.key, required this.state}); + + final AppState state; + + @override + State createState() => _HomeShellState(); +} + +class _HomeShellState extends State { + int _index = 0; + bool _sourcesChanged = false; + + void _select(int index) { + // A text field left focused in Settings would otherwise get focus back + // (and open the keyboard) when returning from an article. + FocusManager.instance.primaryFocus?.unfocus(); + // Source toggles only take effect on the next refresh; do it when the + // user leaves the Sources tab. + if (_index == 2 && index != 2 && _sourcesChanged) { + _sourcesChanged = false; + widget.state.refresh(); + } + setState(() => _index = index); + } + + @override + Widget build(BuildContext context) { + final state = widget.state; + return Scaffold( + body: IndexedStack( + index: _index, + children: [ + FeedScreen(state: state), + BriefingScreen(state: state, openSettings: () => _select(3)), + SourcesScreen(state: state, onChanged: () => _sourcesChanged = true), + SettingsScreen(state: state), + ].indexed + // Hidden tabs stay alive but must not hold or regain focus. + .map((e) => ExcludeFocus(excluding: e.$1 != _index, child: e.$2)) + .toList(), + ), + bottomNavigationBar: NavigationBar( + selectedIndex: _index, + onDestinationSelected: _select, + destinations: const [ + NavigationDestination( + icon: Icon(Icons.newspaper_outlined), + selectedIcon: Icon(Icons.newspaper), + label: 'Today'), + NavigationDestination( + icon: Icon(Icons.auto_awesome_outlined), + selectedIcon: Icon(Icons.auto_awesome), + label: 'Briefing'), + NavigationDestination( + icon: Icon(Icons.rss_feed_outlined), + selectedIcon: Icon(Icons.rss_feed), + label: 'Sources'), + NavigationDestination( + icon: Icon(Icons.settings_outlined), + selectedIcon: Icon(Icons.settings), + label: 'Settings'), + ], + ), + ); + } +} diff --git a/lib/ui/settings_screen.dart b/lib/ui/settings_screen.dart new file mode 100644 index 0000000..ba1be46 --- /dev/null +++ b/lib/ui/settings_screen.dart @@ -0,0 +1,271 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../models/app_settings.dart'; +import '../models/news_source.dart'; +import '../state/app_state.dart'; +import 'common.dart'; + +class SettingsScreen extends StatefulWidget { + const SettingsScreen({super.key, required this.state}); + + final AppState state; + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + late AppSettings _draft; + final _apiKey = TextEditingController(); + final _webhook = TextEditingController(); + final _proxy = TextEditingController(); + bool _showKey = false; + + @override + void initState() { + super.initState(); + _loadFrom(widget.state.settings); + // Settings load asynchronously at startup; pick them up once they arrive. + widget.state.addListener(_syncIfPristine); + } + + void _loadFrom(AppSettings s) { + _draft = s; + _apiKey.text = s.claudeApiKey; + _webhook.text = s.n8nWebhookUrl; + _proxy.text = s.corsProxy; + } + + bool _touched = false; + + void _syncIfPristine() { + if (!_touched && mounted) setState(() => _loadFrom(widget.state.settings)); + } + + @override + void dispose() { + widget.state.removeListener(_syncIfPristine); + _apiKey.dispose(); + _webhook.dispose(); + _proxy.dispose(); + super.dispose(); + } + + void _edit(AppSettings Function(AppSettings) change) { + setState(() { + _touched = true; + _draft = change(_draft); + }); + } + + Future _save() async { + await widget.state.updateSettings(_draft.copyWith( + claudeApiKey: _apiKey.text.trim(), + n8nWebhookUrl: _webhook.text.trim(), + corsProxy: _proxy.text.trim(), + )); + _touched = false; + if (mounted) { + FocusScope.of(context).unfocus(); + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text('Settings saved'))); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + Widget header(String text) => Padding( + padding: const EdgeInsets.fromLTRB(0, 24, 0, 8), + child: Text(text, + style: theme.textTheme.titleSmall?.copyWith(color: theme.colorScheme.primary)), + ); + Widget hint(String text) => Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(text, + style: theme.textTheme.bodySmall + ?.copyWith(color: theme.colorScheme.onSurfaceVariant)), + ); + + return Scaffold( + appBar: AppBar(title: const Text('Settings')), + floatingActionButton: FloatingActionButton.extended( + onPressed: _save, + icon: const Icon(Icons.save_outlined), + label: const Text('Save'), + ), + body: ListView( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 96), + children: [ + header('Appearance'), + SegmentedButton( + segments: const [ + ButtonSegment( + value: ThemeMode.system, + icon: Icon(Icons.brightness_auto_outlined), + label: Text('System')), + ButtonSegment( + value: ThemeMode.light, + icon: Icon(Icons.light_mode_outlined), + label: Text('Light')), + ButtonSegment( + value: ThemeMode.dark, + icon: Icon(Icons.dark_mode_outlined), + label: Text('Dark')), + ], + selected: {_draft.themeMode}, + // Applies right away (no Save needed) so the change is visible. + onSelectionChanged: (s) { + setState(() => _draft = _draft.copyWith(themeMode: s.first)); + widget.state + .updateSettings(widget.state.settings.copyWith(themeMode: s.first)); + }, + ), + header('AI summaries'), + SegmentedButton( + segments: [ + for (final p in AiProvider.values) ButtonSegment(value: p, label: Text(p.label)), + ], + selected: {_draft.aiProvider}, + onSelectionChanged: (s) => _edit((d) => d.copyWith(aiProvider: s.first)), + ), + if (_draft.aiProvider == AiProvider.claude) ...[ + const SizedBox(height: 16), + TextField( + onTapOutside: (_) => FocusManager.instance.primaryFocus?.unfocus(), + controller: _apiKey, + obscureText: !_showKey, + onChanged: (_) => _touched = true, + decoration: InputDecoration( + labelText: 'Claude API key', + hintText: 'sk-ant-…', + border: const OutlineInputBorder(), + suffixIcon: IconButton( + icon: Icon(_showKey ? Icons.visibility_off : Icons.visibility), + onPressed: () => setState(() => _showKey = !_showKey), + ), + ), + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: claudeModels.containsKey(_draft.claudeModel) + ? _draft.claudeModel + : claudeModels.keys.first, + decoration: + const InputDecoration(labelText: 'Model', border: OutlineInputBorder()), + items: [ + for (final e in claudeModels.entries) + DropdownMenuItem(value: e.key, child: Text(e.value)), + ], + onChanged: (v) => _edit((d) => d.copyWith(claudeModel: v)), + ), + Row( + children: [ + Expanded( + child: hint('The key is stored in the device keystore and only sent ' + 'to api.anthropic.com.'), + ), + TextButton( + onPressed: () => + openUrl(context, 'https://console.anthropic.com/settings/keys'), + child: const Text('Get a key'), + ), + ], + ), + ], + if (_draft.aiProvider == AiProvider.n8n) ...[ + const SizedBox(height: 16), + TextField( + onTapOutside: (_) => FocusManager.instance.primaryFocus?.unfocus(), + controller: _webhook, + keyboardType: TextInputType.url, + onChanged: (_) => _touched = true, + decoration: const InputDecoration( + labelText: 'n8n webhook URL', + hintText: 'https://n8n.example.com/webhook/tech-news', + border: OutlineInputBorder(), + ), + ), + hint('The app POSTs articles to this webhook and expects JSON back. ' + 'See README.md for the request/response format.'), + ], + header('Summary language'), + SegmentedButton( + segments: [ + for (final l in SourceLanguage.values) + ButtonSegment(value: l, label: Text('${l.flag} ${l.label}')), + ], + selected: {_draft.summaryLanguage}, + onSelectionChanged: (s) => _edit((d) => d.copyWith(summaryLanguage: s.first)), + ), + hint('Summaries are written in this language, whatever language the source uses.'), + header('Feed'), + SegmentedButton( + segments: const [ + ButtonSegment(value: 12, label: Text('12 h')), + ButtonSegment(value: 24, label: Text('24 h')), + ButtonSegment(value: 48, label: Text('48 h')), + ], + selected: {_draft.maxAgeHours}, + onSelectionChanged: (s) => _edit((d) => d.copyWith(maxAgeHours: s.first)), + ), + hint('Only show articles published within this time window.'), + const SizedBox(height: 8), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Hide paid articles'), + subtitle: const Text('heise+, SPIEGEL+, Golem Plus, t3n Pro'), + value: _draft.hidePaid, + onChanged: (v) => _edit((d) => d.copyWith(hidePaid: v)), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Hide sponsored posts'), + subtitle: const Text('Posts marked as ads, e.g. "Anzeige:" on Golem'), + value: _draft.hideSponsored, + onChanged: (v) => _edit((d) => d.copyWith(hideSponsored: v)), + ), + header('Original page view'), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Block ads and trackers'), + value: _draft.blockAds, + onChanged: (v) => _edit((d) => d.copyWith(blockAds: v)), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Hide cookie banners'), + subtitle: const Text('Nothing is accepted; sites treat it like a rejection'), + value: _draft.hideCookieBanners, + onChanged: (v) => _edit((d) => d.copyWith(hideCookieBanners: v)), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Accept cookie walls'), + subtitle: const Text('For sites that only show articles after you accept ' + '(Golem). Ads and trackers stay blocked.'), + value: _draft.acceptConsentWalls, + onChanged: (v) => _edit((d) => d.copyWith(acceptConsentWalls: v)), + ), + if (kIsWeb) ...[ + header('Web (CORS proxy)'), + TextField( + onTapOutside: (_) => FocusManager.instance.primaryFocus?.unfocus(), + controller: _proxy, + keyboardType: TextInputType.url, + onChanged: (_) => _touched = true, + decoration: const InputDecoration( + labelText: 'Proxy prefix', + hintText: 'https://corsproxy.example/?url=', + border: OutlineInputBorder(), + ), + ), + hint('Browsers block cross-origin feed requests. The feed URL is URL-encoded ' + 'and appended to this prefix. Not needed on Android, iOS or Windows.'), + ], + ], + ), + ); + } +} diff --git a/lib/ui/sources_screen.dart b/lib/ui/sources_screen.dart new file mode 100644 index 0000000..a7927c3 --- /dev/null +++ b/lib/ui/sources_screen.dart @@ -0,0 +1,223 @@ +import 'package:flutter/material.dart'; + +import '../models/news_source.dart'; +import '../state/app_state.dart'; + +class SourcesScreen extends StatelessWidget { + const SourcesScreen({super.key, required this.state, required this.onChanged}); + + final AppState state; + + /// Called when the selection changes so the feed can refresh later. + final VoidCallback onChanged; + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: state, + builder: (context, _) { + final theme = Theme.of(context); + return Scaffold( + appBar: AppBar( + title: const Text('Sources'), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(24), + child: Container( + alignment: AlignmentDirectional.centerStart, + padding: const EdgeInsetsDirectional.only(start: 16, bottom: 8), + child: Text( + '${state.enabledSourceIds.length} of ${state.allSources.length} enabled', + style: theme.textTheme.bodySmall, + ), + ), + ), + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () => _addFeed(context), + icon: const Icon(Icons.add), + label: const Text('Add feed'), + ), + body: ListView( + padding: const EdgeInsets.only(bottom: 96), + children: [ + for (final lang in SourceLanguage.values) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Text('${lang.flag} ${lang.label}', + style: theme.textTheme.titleSmall + ?.copyWith(color: theme.colorScheme.primary)), + ), + for (final source in state.allSources.where((s) => s.language == lang)) + _SourceTile( + source: source, + enabled: state.enabledSourceIds.contains(source.id), + onToggle: (v) { + state.setSourceEnabled(source, v); + onChanged(); + }, + onDelete: source.isCustom + ? () { + state.removeCustomSource(source); + onChanged(); + } + : null, + ), + ], + ], + ), + ); + }, + ); + } + + Future _addFeed(BuildContext context) async { + final added = await showDialog( + context: context, + builder: (_) => _AddFeedDialog(state: state), + ); + if (added == true) { + onChanged(); + if (context.mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text('Feed added'))); + } + } + } +} + +class _SourceTile extends StatelessWidget { + const _SourceTile({ + required this.source, + required this.enabled, + required this.onToggle, + this.onDelete, + }); + + final NewsSource source; + final bool enabled; + final ValueChanged onToggle; + final VoidCallback? onDelete; + + @override + Widget build(BuildContext context) { + final host = Uri.tryParse(source.homepage)?.host ?? ''; + final subtitle = [ + if (source.description.isNotEmpty) source.description, + host.replaceFirst('www.', ''), + ].join(' · '); + return SwitchListTile( + value: enabled, + onChanged: onToggle, + title: Text(source.name), + subtitle: Text(subtitle), + secondary: onDelete == null + ? null + : IconButton( + tooltip: 'Remove', + icon: const Icon(Icons.delete_outline), + onPressed: onDelete, + ), + ); + } +} + +class _AddFeedDialog extends StatefulWidget { + const _AddFeedDialog({required this.state}); + + final AppState state; + + @override + State<_AddFeedDialog> createState() => _AddFeedDialogState(); +} + +class _AddFeedDialogState extends State<_AddFeedDialog> { + final _name = TextEditingController(); + final _url = TextEditingController(); + SourceLanguage _language = SourceLanguage.de; + bool _busy = false; + String? _error; + + @override + void dispose() { + _name.dispose(); + _url.dispose(); + super.dispose(); + } + + Future _submit() async { + final name = _name.text.trim(); + final url = _url.text.trim(); + if (name.isEmpty || !url.startsWith('http')) { + setState(() => _error = 'Enter a name and a feed URL starting with http.'); + return; + } + setState(() { + _busy = true; + _error = null; + }); + final error = await widget.state + .addCustomSource(name: name, feedUrl: url, language: _language); + if (!mounted) return; + if (error == null) { + Navigator.pop(context, true); + } else { + setState(() { + _busy = false; + _error = error; + }); + } + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('Add RSS / Atom feed'), + content: SizedBox( + width: 400, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: _name, + decoration: const InputDecoration(labelText: 'Name'), + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 12), + TextField( + controller: _url, + decoration: const InputDecoration( + labelText: 'Feed URL', hintText: 'https://example.com/feed.xml'), + keyboardType: TextInputType.url, + onSubmitted: (_) => _submit(), + ), + const SizedBox(height: 16), + SegmentedButton( + segments: [ + for (final l in SourceLanguage.values) + ButtonSegment(value: l, label: Text('${l.flag} ${l.label}')), + ], + selected: {_language}, + onSelectionChanged: (s) => setState(() => _language = s.first), + ), + if (_error != null) ...[ + const SizedBox(height: 12), + Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: _busy ? null : () => Navigator.pop(context, false), + child: const Text('Cancel')), + FilledButton( + onPressed: _busy ? null : _submit, + child: _busy + ? const SizedBox( + width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)) + : const Text('Add'), + ), + ], + ); + } +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..061f98d --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,682 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: "58c8d17d8d589c4259f773522815115de873c397b977a29993588487d3f9acb4" + url: "https://pub.dev" + source: hosted + version: "4.5.0" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_inappwebview: + dependency: "direct main" + description: + name: flutter_inappwebview + sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5" + url: "https://pub.dev" + source: hosted + version: "6.1.5" + flutter_inappwebview_android: + dependency: transitive + description: + name: flutter_inappwebview_android + sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba" + url: "https://pub.dev" + source: hosted + version: "1.1.3" + flutter_inappwebview_internal_annotations: + dependency: transitive + description: + name: flutter_inappwebview_internal_annotations + sha256: e30fba942e3debea7b7e6cdd4f0f59ce89dd403a9865193e3221293b6d1544c6 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + flutter_inappwebview_ios: + dependency: transitive + description: + name: flutter_inappwebview_ios + sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_macos: + dependency: transitive + description: + name: flutter_inappwebview_macos + sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_platform_interface: + dependency: transitive + description: + name: flutter_inappwebview_platform_interface + sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500 + url: "https://pub.dev" + source: hosted + version: "1.3.0+1" + flutter_inappwebview_web: + dependency: transitive + description: + name: flutter_inappwebview_web + sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_windows: + dependency: transitive + description: + name: flutter_inappwebview_windows + sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7" + url: "https://pub.dev" + source: hosted + version: "0.14.4" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: fe638107c5f69119156ada2db5a57734385fac3f64430bd7252a00d3ead2ca4b + url: "https://pub.dev" + source: hosted + version: "10.3.4" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: "82329fa5cdf343773b1b6897dea959105a29f092454259edff92f9f6637e8149" + url: "https://pub.dev" + source: hosted + version: "0.3.2" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea + url: "https://pub.dev" + source: hosted + version: "3.0.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + html: + dependency: "direct main" + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" + url: "https://pub.dev" + source: hosted + version: "10.0.9" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "3b4c1fc3aa55ddc9cd4aa6759984330d5c8e66aa7702a6223c61540dc6380c37" + url: "https://pub.dev" + source: hosted + version: "2.2.19" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: "direct dev" + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: "direct dev" + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e + url: "https://pub.dev" + source: hosted + version: "6.5.2" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + url: "https://pub.dev" + source: hosted + version: "2.5.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e + url: "https://pub.dev" + source: hosted + version: "2.4.13" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" + source: hosted + version: "0.7.4" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "81777b08c498a292d93ff2feead633174c386291e35612f8da438d6e92c4447e" + url: "https://pub.dev" + source: hosted + version: "6.3.20" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: d80b3f567a617cb923546034cc94bfe44eb15f989fe670b37f26abdb9d939cb7 + url: "https://pub.dev" + source: hosted + version: "6.3.4" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: c043a77d6600ac9c38300567f33ef12b0ef4f4783a2c1f00231d2b1941fea13f + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02 + url: "https://pub.dev" + source: hosted + version: "15.0.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: "direct main" + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.8.1 <4.0.0" + flutter: ">=3.32.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..626ea41 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,123 @@ +name: daily_tech_news +description: "Daily tech news with AI summaries" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.8.1 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + http: ^1.6.0 + xml: ^6.6.1 + html: ^0.15.7 + shared_preferences: ^2.5.3 + url_launcher: ^6.3.2 + flutter_secure_storage: ^10.3.4 + flutter_inappwebview: ^6.1.5 + path_provider: ^2.1.5 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + flutter_launcher_icons: ^0.14.4 + path_provider_platform_interface: ^2.1.2 + plugin_platform_interface: ^2.1.8 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package + +# App icon. Sources live in assets/icon (SVG + generator script); regenerate the +# platform icons with: dart run flutter_launcher_icons +flutter_launcher_icons: + image_path: "assets/icon/icon.png" + android: "ic_launcher" + adaptive_icon_background: "assets/icon/background.png" + adaptive_icon_foreground: "assets/icon/foreground.png" + adaptive_icon_monochrome: "assets/icon/monochrome.png" + # The artwork already sits inside the safe zone; skip the default 16% inset. + adaptive_icon_foreground_inset: 0 + min_sdk_android: 23 + ios: true + remove_alpha_ios: true + web: + generate: true + image_path: "assets/icon/icon.png" + background_color: "#2231A6" + theme_color: "#3355DD" + windows: + generate: true + image_path: "assets/icon/icon.png" + icon_size: 256 diff --git a/test/article_extractor_test.dart b/test/article_extractor_test.dart new file mode 100644 index 0000000..252a73a --- /dev/null +++ b/test/article_extractor_test.dart @@ -0,0 +1,124 @@ +import 'dart:convert'; + +import 'package:daily_tech_news/models/article.dart'; +import 'package:daily_tech_news/models/news_source.dart'; +import 'package:daily_tech_news/services/article_extractor.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; + +final _base = Uri.parse('https://news.example.com/2026/10/story.html'); + +const _longText = 'This paragraph is long enough to count as real article text for the reader.'; + +void main() { + test('picks the main article, not teaser
s, and drops page furniture', () { + const html = ''' + + +

Short teaser that is not the story at all, just a link.

+
+

Title shown from the feed

+

$_longText one

+

Background

+

$_longText two

+
  • First point with enough characters
  • short
+
We are very happy with the result.
+
flutter pub add webview_flutter
+
A chart
+ + +

$_longText comment

+
+

$_longText footer

+'''; + + final content = ArticleExtractor.parse(html, _base); + final types = content.blocks.map((b) => b.type).toList(); + expect(types, [ + BlockType.paragraph, + BlockType.heading, + BlockType.paragraph, + BlockType.image, + BlockType.listItem, + BlockType.quote, + BlockType.code, + BlockType.image, + BlockType.caption, + ]); + expect(content.blocks[3].text, 'https://news.example.com/img/photo.jpg', + reason: 'lazy-load src is resolved against the page URL'); + expect(content.plainText, isNot(contains('related'))); + expect(content.plainText, isNot(contains('comment'))); + expect(content.plainText, isNot(contains('footer'))); + expect(content.plainText, isNot(contains('Title shown'))); + }); + + test('skips link-only tables of contents and flattens nested lists', () { + const html = ''' +'''; + final items = ArticleExtractor.parse(html, _base) + .blocks + .where((b) => b.type == BlockType.listItem) + .map((b) => b.text) + .toList(); + expect(items, ['Inner point with a link inside it']); + }); + + test('a redirect to a consent page is reported, not shown as the article', () async { + const consentHtml = '

Besuchen Sie Golem.de wie gewohnt mit Werbung und Tracking, ' + 'indem Sie der Nutzung aller Cookies zustimmen.

'; + final extractor = ArticleExtractor( + client: _RedirectingClient( + Uri.parse('https://www.golem.de/sonstiges/zustimmung/auswahl.html?from=x'), + consentHtml), + ); + const article = Article( + title: 'Story', + link: 'https://www.golem.de/news/story.html', + excerpt: 'Teaser', + source: NewsSource( + id: 'golem', name: 'Golem.de', feedUrl: '', homepage: '', language: SourceLanguage.de), + ); + final content = await extractor.load(article); + expect(content.consentWall, isTrue); + expect(content.plainText, isNot(contains('Cookies'))); + }); + + test('feed content fragments are parsed as a whole', () { + final content = ArticleExtractor.parse( + '

$_longText

$_longText again

', _base, + isFragment: true); + expect(content.blocks, hasLength(2)); + }); +} + +/// Answers every request as if the server had redirected to [finalUrl]. +class _RedirectingClient extends http.BaseClient { + _RedirectingClient(this.finalUrl, this.body); + + final Uri finalUrl; + final String body; + + @override + Future send(http.BaseRequest request) async => + _UrlStreamedResponse(finalUrl, Stream.value(utf8.encode(body)), 200); +} + +class _UrlStreamedResponse extends http.StreamedResponse implements http.BaseResponseWithUrl { + _UrlStreamedResponse(this.url, super.stream, super.statusCode); + + @override + final Uri url; +} diff --git a/test/briefing_history_test.dart b/test/briefing_history_test.dart new file mode 100644 index 0000000..c61796c --- /dev/null +++ b/test/briefing_history_test.dart @@ -0,0 +1,78 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:daily_tech_news/models/briefing.dart'; +import 'package:daily_tech_news/services/storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _FakePathProvider extends PathProviderPlatform with MockPlatformInterfaceMixin { + _FakePathProvider(this.dir); + + final String dir; + + @override + Future getApplicationSupportPath() async => dir; +} + +DailyBriefing _briefing(DateTime at, String intro) => DailyBriefing( + createdAt: at, + intro: intro, + generatedBy: 'test', + topics: const [ + BriefingTopic(title: 'Topic', summary: 'Summary', sources: [ + ArticleRef(title: 'A', url: 'https://example.com/a', sourceName: 'Example'), + ]), + ], + ); + +void main() { + late Directory dir; + + setUp(() { + dir = Directory.systemTemp.createTempSync('tagesbyte_test'); + PathProviderPlatform.instance = _FakePathProvider(dir.path); + }); + + tearDown(() => dir.deleteSync(recursive: true)); + + test('saves and loads the history, newest first', () async { + SharedPreferences.setMockInitialValues({}); + final storage = await Storage.open(); + final older = _briefing(DateTime(2026, 10, 10, 8), 'Older'); + final newer = _briefing(DateTime(2026, 10, 11, 8), 'Newer'); + + await storage.saveBriefingHistory([older, newer]); + final loaded = await storage.loadBriefingHistory(); + + expect(loaded.map((b) => b.intro), ['Newer', 'Older']); + expect(loaded.first.topics.single.sources.single.url, 'https://example.com/a'); + expect(File('${dir.path}/briefings.json').existsSync(), isTrue); + }); + + test('moves the briefing saved by earlier versions into the history', () async { + final legacy = _briefing(DateTime(2026, 10, 9, 8), 'From before the update'); + SharedPreferences.setMockInitialValues( + {'last_briefing': jsonEncode(legacy.toJson())}); + final storage = await Storage.open(); + + final loaded = await storage.loadBriefingHistory(); + expect(loaded.single.intro, 'From before the update'); + + // Migrated once: the old key is gone and loading again doesn't duplicate. + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getString('last_briefing'), isNull); + expect((await storage.loadBriefingHistory()), hasLength(1)); + }); + + test('a missing or broken file means an empty history', () async { + SharedPreferences.setMockInitialValues({}); + final storage = await Storage.open(); + expect(await storage.loadBriefingHistory(), isEmpty); + + File('${dir.path}/briefings.json').writeAsStringSync('{not json'); + expect(await storage.loadBriefingHistory(), isEmpty); + }); +} diff --git a/test/claude_summarizer_test.dart b/test/claude_summarizer_test.dart new file mode 100644 index 0000000..8fe8055 --- /dev/null +++ b/test/claude_summarizer_test.dart @@ -0,0 +1,119 @@ +import 'dart:convert'; + +import 'package:daily_tech_news/models/article.dart'; +import 'package:daily_tech_news/models/news_source.dart'; +import 'package:daily_tech_news/services/claude_summarizer.dart'; +import 'package:daily_tech_news/services/summarizer.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +const _source = NewsSource( + id: 'verge', + name: 'The Verge', + feedUrl: 'https://example.com/feed', + homepage: 'https://example.com', + language: SourceLanguage.en, +); + +const _articles = [ + Article(title: 'Chip launch', link: 'https://example.com/1', source: _source), + Article(title: 'Big outage', link: 'https://example.com/2', source: _source), +]; + +http.Response _ok(Map body) => + http.Response.bytes(utf8.encode(jsonEncode(body)), 200); + +void main() { + test('briefing request uses structured output and maps article ids', () async { + late Map sent; + late Map headers; + final client = MockClient((request) async { + sent = jsonDecode(request.body) as Map; + headers = request.headers; + return _ok({ + 'stop_reason': 'end_turn', + 'content': [ + {'type': 'thinking', 'thinking': ''}, + { + 'type': 'text', + 'text': jsonEncode({ + 'intro': 'Ein ruhiger Tag.', + 'topics': [ + { + 'title': 'Neuer Chip', + 'summary': 'Details', + 'article_ids': ['a1', 'a99'], + }, + ], + }), + }, + ], + }); + }); + + final summarizer = + ClaudeSummarizer(apiKey: 'sk-test', model: 'claude-opus-5-5', client: client); + final briefing = await summarizer.createBriefing(_articles, SourceLanguage.de); + + expect(headers['x-api-key'], 'sk-test'); + expect(headers['anthropic-version'], '2023-06-01'); + expect(headers['anthropic-beta'], 'server-side-fallback-2026-07-01'); + expect(sent['model'], 'claude-opus-5-5'); + expect(sent['fallbacks'], 'default'); + expect(sent['output_config']['format']['type'], 'json_schema'); + expect(sent['messages'][0]['content'], contains('[a2] (The Verge) Big outage')); + expect(sent['system'], contains('German')); + + expect(briefing.intro, 'Ein ruhiger Tag.'); + expect(briefing.topics.single.sources.single.url, 'https://example.com/1', + reason: 'unknown ids are dropped'); + }); + + test('haiku requests skip the fallback beta', () async { + late http.Request req; + final client = MockClient((request) async { + req = request; + return _ok({ + 'stop_reason': 'end_turn', + 'content': [ + {'type': 'text', 'text': 'TL;DR: ok'}, + ], + }); + }); + final summarizer = + ClaudeSummarizer(apiKey: 'k', model: 'claude-haiku-5-5', client: client); + final text = + await summarizer.summarizeArticle(_articles.first, 'body', SourceLanguage.en); + expect(text, 'TL;DR: ok'); + expect(req.headers.containsKey('anthropic-beta'), isFalse); + expect((jsonDecode(req.body) as Map).containsKey('fallbacks'), isFalse); + }); + + test('refusals and auth errors become readable messages', () async { + final refusal = ClaudeSummarizer( + apiKey: 'k', + model: 'claude-opus-5-5', + client: MockClient((_) async => _ok({'stop_reason': 'refusal', 'content': []})), + ); + await expectLater( + refusal.summarizeArticle(_articles.first, 'x', SourceLanguage.en), + throwsA(isA()), + ); + + final unauthorized = ClaudeSummarizer( + apiKey: 'bad', + model: 'claude-opus-5-5', + client: MockClient((_) async => http.Response( + jsonEncode({ + 'type': 'error', + 'error': {'type': 'authentication_error', 'message': 'invalid x-api-key'}, + }), + 401)), + ); + await expectLater( + unauthorized.summarizeArticle(_articles.first, 'x', SourceLanguage.en), + throwsA(predicate((e) => e.toString().contains('Invalid Claude API key'))), + ); + }); +} diff --git a/test/consent_service_test.dart b/test/consent_service_test.dart new file mode 100644 index 0000000..edca0e7 --- /dev/null +++ b/test/consent_service_test.dart @@ -0,0 +1,101 @@ +import 'dart:convert'; + +import 'package:daily_tech_news/models/article.dart'; +import 'package:daily_tech_news/models/news_source.dart'; +import 'package:daily_tech_news/services/article_extractor.dart'; +import 'package:daily_tech_news/services/consent_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; + +const _articleUrl = 'https://www.golem.de/news/story-2610-1.html'; +final _wallUrl = Uri.parse('https://www.golem.de/sonstiges/zustimmung/auswahl.html' + '?from=${Uri.encodeComponent(_articleUrl)}'); +const _wallHtml = '

Cookies zustimmen

'; +const _articleHtml = '

Die Forscher analysierten aggregierte Daten von über ' + '300 Millionen Arbeitsereignissen in Softwareteams.

'; + +/// Behaves like golem.de: articles redirect to the consent page unless the +/// consent cookie is sent; the accept endpoint sets that cookie. +class _FakeGolem extends http.BaseClient { + final requests = []; + + @override + Future send(http.BaseRequest request) async { + requests.add(request); + final url = request.url; + if (url.path == '/abo/setconsentcookie.php') { + return http.StreamedResponse(Stream.value(utf8.encode('ok')), 200, headers: { + 'set-cookie': 'golem_consent20=simple${url.queryParameters['version']}; ' + 'expires=Mon, 12-Oct-2026 10:43:36 GMT; Max-Age=86400; path=/; domain=golem.de; ' + 'secure,golem_c20date=1791715416; expires=Mon, 12-Oct-2026 10:43:36 GMT; path=/', + }); + } + if (url.path.startsWith('/sonstiges/zustimmung/')) { + return _Page(url, _wallHtml); + } + final consented = (request.headers['Cookie'] ?? '').contains('golem_consent20=simple'); + return consented ? _Page(url, _articleHtml) : _Page(_wallUrl, _wallHtml); + } +} + +class _Page extends http.StreamedResponse implements http.BaseResponseWithUrl { + _Page(this.url, String body) : super(Stream.value(utf8.encode(body)), 200); + + @override + final Uri url; +} + +const _article = Article( + title: 'Story', + link: _articleUrl, + excerpt: 'Teaser', + source: NewsSource( + id: 'golem', name: 'Golem.de', feedUrl: '', homepage: '', language: SourceLanguage.de), +); + +void main() { + test('parseSetCookie splits joined headers without breaking on expires dates', () { + final cookies = ConsentService.parseSetCookie( + 'a=1; expires=Mon, 12-Oct-2026 10:43:36 GMT; path=/,b=two|x; path=/, c=3'); + expect(cookies, {'a': '1', 'b': 'two|x', 'c': '3'}); + }); + + test('accepting Golem uses the version from the consent page', () async { + final golem = _FakeGolem(); + final consent = ConsentService(client: golem); + expect(consent.canAccept(_wallUrl), isTrue); + expect(await consent.accept(_wallUrl, wallHtml: _wallHtml), isTrue); + + final acceptRequest = golem.requests.single.url; + expect(acceptRequest.queryParameters['type'], 'simple'); + expect(acceptRequest.queryParameters['version'], '|260301'); + expect(acceptRequest.queryParameters['referer'], _articleUrl); + expect(consent.cookieHeader(Uri.parse(_articleUrl)), + 'golem_consent20=simple|260301; golem_c20date=1791715416'); + }); + + test('reader view accepts the wall once and then gets the article', () async { + final golem = _FakeGolem(); + final consent = ConsentService(client: golem); + final extractor = ArticleExtractor(client: golem, consent: consent); + + final content = await extractor.load(_article, acceptConsentWalls: true); + expect(content.consentWall, isFalse); + expect(content.plainText, contains('300 Millionen')); + + // The next article reuses the cookie: no second accept request. + golem.requests.clear(); + await extractor.load(_article, acceptConsentWalls: true); + expect(golem.requests.map((r) => r.url.path), ['/news/story-2610-1.html']); + }); + + test('without the setting the wall is reported, not accepted', () async { + final golem = _FakeGolem(); + final extractor = + ArticleExtractor(client: golem, consent: ConsentService(client: golem)); + final content = await extractor.load(_article); + expect(content.consentWall, isTrue); + expect(golem.requests.where((r) => r.url.path.contains('setconsentcookie')), isEmpty); + }); +} diff --git a/test/content_blocking_test.dart b/test/content_blocking_test.dart new file mode 100644 index 0000000..01eee90 --- /dev/null +++ b/test/content_blocking_test.dart @@ -0,0 +1,46 @@ +import 'package:daily_tech_news/services/content_blocking.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + RegExp pattern(int index, {bool ads = true, bool cookies = true}) => RegExp( + ContentBlocking.blockers(ads: ads, cookies: cookies)[index].trigger.urlFilter); + + test('ad pattern blocks ad hosts and their subdomains only', () { + final ads = pattern(0); + expect(ads.hasMatch('https://securepubads.g.doubleclick.net/tag/js/gpt.js'), isTrue); + expect(ads.hasMatch('https://static.criteo.net/js/ld/publishertag.js'), isTrue); + expect(ads.hasMatch('https://connect.facebook.net/en_US/fbevents.js'), isTrue); + expect(ads.hasMatch('https://www.googletagmanager.com/gtm.js?id=1'), isTrue); + + expect(ads.hasMatch('https://www.heise.de/news/doubleclick.net-story.html'), isFalse, + reason: 'the host must match, not the path'); + expect(ads.hasMatch('https://notdoubleclick.net/x'), isFalse); + expect(ads.hasMatch('https://www.facebook.com/heiseonline'), isFalse); + expect(ads.hasMatch('https://www.spiegel.de/netzwelt/'), isFalse); + }); + + test('consent patterns block CMP hosts including first-party cmp. subdomains', () { + final consent = pattern(1); + final firstParty = pattern(2); + expect(consent.hasMatch('https://cdn.privacy-mgmt.com/wrapperMessagingWithoutDetection.js'), + isTrue); + expect(consent.hasMatch('https://cdn.cookielaw.org/scripttemplates/otSDKStub.js'), isTrue); + expect(consent.hasMatch('https://cdn.consentmanager.net/delivery/cmp.min.js'), isTrue); + expect(firstParty.hasMatch('https://cmp.heise.de/unified/wrapperMessagingWithoutDetection.js'), + isTrue); + expect(firstParty.hasMatch('https://www.heise.de/cmp.js'), isFalse); + }); + + test('toggles control which blockers and styles are produced', () { + expect(ContentBlocking.blockers(ads: false, cookies: false), isEmpty); + expect(ContentBlocking.blockers(ads: true, cookies: false), hasLength(1)); + expect(ContentBlocking.cosmeticScript(ads: false, cookies: false), isNull); + + final script = ContentBlocking.cosmeticScript(ads: false, cookies: true)!; + expect(script, contains('#onetrust-consent-sdk')); + expect(script, contains('overflow:auto!important')); + expect(script, isNot(contains('adsbygoogle'))); + // Double-quoted selectors are safe inside the single-quoted JS literal. + expect(script, contains('[id^="sp_message_container"]')); + }); +} diff --git a/test/feed_parser_test.dart b/test/feed_parser_test.dart new file mode 100644 index 0000000..ac06f01 --- /dev/null +++ b/test/feed_parser_test.dart @@ -0,0 +1,98 @@ +import 'package:daily_tech_news/models/news_source.dart'; +import 'package:daily_tech_news/services/feed_parser.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _source = NewsSource( + id: 'test', + name: 'Test', + feedUrl: 'https://example.com/feed', + homepage: 'https://example.com', + language: SourceLanguage.de, +); + +void main() { + test('parses RSS 2.0 items, strips html, finds images and dates', () { + const rss = ''' + + + Test + + <![CDATA[Neue GPU & mehr]]> + https://example.com/a + Sun, 11 Oct 2026 06:18:59 +0200 + Jane Doe + Die neue Grafikkarte ist da und sie ist schneller als je zuvor.

]]>
+ Volltext

]]>
+
+ + HN style + https://example.com/b + Sat, 10 Oct 2026 22:50:10 GMT + Comments]]> + + + No link +
+
'''; + + final items = FeedParser.parse(rss, _source); + expect(items, hasLength(2)); + + final a = items[0]; + expect(a.title, 'Neue GPU & mehr'); + expect(a.link, 'https://example.com/a'); + expect(a.excerpt, startsWith('Die neue Grafikkarte')); + expect(a.contentHtml, contains('

Volltext

')); + expect(a.imageUrl, 'https://example.com/img.jpg'); + expect(a.author, 'Jane Doe'); + expect(a.published, DateTime.utc(2026, 10, 11, 4, 18, 59)); + + final b = items[1]; + expect(b.excerpt, isEmpty, reason: 'bare "Comments" links are dropped'); + expect(b.imageUrl, 'https://example.com/thumb.jpg'); + expect(b.published, DateTime.utc(2026, 10, 10, 22, 50, 10)); + }); + + test('parses Atom entries', () { + const atom = ''' + + heise + + Patchday: Microsoft schließt Lücken + + + 2026-10-11T09:30:00+02:00 + 2026-10-11T10:00:00+02:00 + <p>Microsoft hat zum Patchday zahlreiche Sicherheitslücken geschlossen.</p> + heise Security + +'''; + final items = FeedParser.parse(atom, _source); + expect(items, hasLength(1)); + expect(items.single.link, 'https://example.com/atom-1'); + expect(items.single.excerpt, startsWith('Microsoft hat zum Patchday')); + expect(items.single.published, DateTime.utc(2026, 10, 11, 7, 30)); + expect(items.single.author, 'heise Security'); + }); + + test('ignores tracking pixels when picking the article image', () { + const atom = ''' + + + Softwareentwicklung: KI-Flut + + Teaser text that is long enough. <img src="https://cpx.golem.de/cpx.php?aid=1" width="1" height="1" /> + +'''; + expect(FeedParser.parse(atom, _source).single.imageUrl, isNull); + }); + + test('parseDate handles named zones, short years and garbage', () { + expect(FeedParser.parseDate('Mon, 05 Oct 2026 12:00:00 EST'), + DateTime.utc(2026, 10, 5, 17)); + expect(FeedParser.parseDate('5 Oct 26 12:00 +0000'), DateTime.utc(2026, 10, 5, 12)); + expect(FeedParser.parseDate('not a date'), isNull); + expect(FeedParser.parseDate(''), isNull); + }); +} diff --git a/test/live_feeds_test.dart b/test/live_feeds_test.dart new file mode 100644 index 0000000..d68d734 --- /dev/null +++ b/test/live_feeds_test.dart @@ -0,0 +1,56 @@ +// Hits the real feeds. Run with: LIVE_FEEDS=1 flutter test test/live_feeds_test.dart +import 'dart:io'; + +import 'package:daily_tech_news/data/default_sources.dart'; +import 'package:daily_tech_news/services/article_extractor.dart'; +import 'package:daily_tech_news/services/consent_service.dart'; +import 'package:daily_tech_news/services/feed_service.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final live = Platform.environment['LIVE_FEEDS'] == '1'; + + test('all default feeds load and parse', () async { + final service = FeedService(); + final failures = []; + for (final source in defaultSources) { + try { + final items = await service.fetchSource(source); + final dated = items.where((a) => a.published != null).length; + final withImage = items.where((a) => a.imageUrl != null).length; + // ignore: avoid_print + print('${source.name.padRight(28)} ${items.length.toString().padLeft(3)} items, ' + '$dated dated, $withImage with image'); + if (items.isEmpty) failures.add('${source.name}: no items'); + } catch (e) { + failures.add('${source.name}: $e'); + } + } + expect(failures, isEmpty); + }, skip: live ? false : 'set LIVE_FEEDS=1 to run', timeout: const Timeout(Duration(minutes: 3))); + + test('reader view extracts the article body', () async { + final service = FeedService(); + final extractor = ArticleExtractor(consent: ConsentService()); + final thin = []; + for (final source in defaultSources) { + final article = (await service.fetchSource(source)).first; + final content = await extractor.load(article, acceptConsentWalls: true); + final counts = {}; + for (final b in content.blocks) { + counts[b.type] = (counts[b.type] ?? 0) + 1; + } + // ignore: avoid_print + print('${source.name.padRight(28)} teaser ${article.excerpt.length.toString().padLeft(4)} ' + '-> ${content.plainText.length.toString().padLeft(5)} chars, ' + '${counts[BlockType.paragraph] ?? 0} paragraphs, ${counts[BlockType.image] ?? 0} images'); + if (content.consentWall) { + thin.add('${source.name} (consent wall)'); + } else if (content.plainText.length < 400) { + thin.add(source.name); + } + } + // ignore: avoid_print + print('Teaser only (paywall / blocked / very short): $thin'); + }, skip: live ? false : 'set LIVE_FEEDS=1 to run', timeout: const Timeout(Duration(minutes: 5))); +} diff --git a/test/paywall_service_test.dart b/test/paywall_service_test.dart new file mode 100644 index 0000000..64142c1 --- /dev/null +++ b/test/paywall_service_test.dart @@ -0,0 +1,85 @@ +import 'package:daily_tech_news/models/article.dart'; +import 'package:daily_tech_news/models/news_source.dart'; +import 'package:daily_tech_news/services/paywall_service.dart'; +import 'package:daily_tech_news/services/storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +NewsSource _source({bool checkPage = false}) => NewsSource( + id: 'src', + name: 'Source', + feedUrl: 'https://example.com/feed', + homepage: 'https://example.com', + language: SourceLanguage.de, + checkPaywallOnPage: checkPage, + ); + +Article _article(String title, {String? link, bool checkPage = false}) => Article( + title: title, link: link ?? 'https://example.com/$title', source: _source(checkPage: checkPage)); + +Future _storage() async { + SharedPreferences.setMockInitialValues({}); + return Storage.open(); +} + +void main() { + test('recognizes paid and sponsored titles', () async { + final paywall = PaywallService(await _storage(), client: MockClient((_) async => http.Response('', 500))); + expect(paywall.isPaid(_article('heise+ | Essbare Batterie')), isTrue); + expect(paywall.isPaid(_article('(g+) Siri-Ersatz im Eigenbau')), isTrue); + expect(paywall.isPaid(_article('SPIEGEL+ Test')), isTrue); + expect(paywall.isPaid(_article('Apple reduziert iPhone-18-Pro-Bestellungen')), isFalse); + expect(paywall.isPaid(_article('OnePlus 16 vorgestellt')), isFalse); + + expect(paywall.isSponsored(_article('Anzeige: Logitech-Set zum Sparpreis')), isTrue); + expect(paywall.isSponsored(_article('Werbung | Neues Angebot')), isTrue); + expect(paywall.isSponsored(_article('Anzeigenmarkt bricht ein')), isFalse); + }); + + test('checks pages only for flagged sources and remembers results', () async { + final storage = await _storage(); + final requested = []; + final client = MockClient((request) async { + requested.add(request.url.path); + final free = request.url.path.contains('free'); + return http.Response( + '', + 200); + }); + final paywall = PaywallService(storage, client: client); + final paid = _article('Paid story', link: 'https://example.com/paid', checkPage: true); + final free = _article('Free story', link: 'https://example.com/free', checkPage: true); + final unflagged = _article('Other', link: 'https://example.com/other'); + final titled = _article('heise+ | Known', link: 'https://example.com/titled', checkPage: true); + + expect(await paywall.checkPages([paid, free, unflagged, titled]), isTrue); + expect(requested..sort(), ['/free', '/paid'], reason: 'unflagged and title-marked skipped'); + expect(paywall.isPaid(paid), isTrue); + expect(paywall.isPaid(free), isFalse); + + // A fresh service reads the saved results instead of fetching again. + requested.clear(); + final again = PaywallService(storage, client: client); + expect(again.isPaid(paid), isTrue); + expect(await again.checkPages([paid, free]), isFalse); + expect(requested, isEmpty); + }); + + test('network errors are retried on the next refresh', () async { + final storage = await _storage(); + var calls = 0; + final paywall = PaywallService(storage, client: MockClient((_) async { + calls++; + return http.Response('', 503); + })); + final a = _article('Story', link: 'https://example.com/a', checkPage: true); + await paywall.checkPages([a]); + await paywall.checkPages([a]); + expect(calls, 2); + expect(paywall.isPaid(a), isFalse); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..210e293 Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..81dc4e4 Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..99967e0 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..81dc4e4 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..99967e0 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..cb9404c --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + Tagesbyte + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..d9875c6 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Tagesbyte", + "short_name": "Tagesbyte", + "start_url": ".", + "display": "standalone", + "background_color": "#2231A6", + "theme_color": "#3355DD", + "description": "Daily tech news with AI summaries", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} \ No newline at end of file diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..0a08c7e --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(daily_tech_news LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "daily_tech_news") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..6dfc5b4 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,20 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi")); + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..eb1d58b --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_inappwebview_windows + flutter_secure_storage_windows + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..152751b --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "de.dailytechnews" "\0" + VALUE "FileDescription", "Tagesbyte" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "daily_tech_news" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 de.dailytechnews. All rights reserved." "\0" + VALUE "OriginalFilename", "daily_tech_news.exe" "\0" + VALUE "ProductName", "Tagesbyte" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..7f26240 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"Tagesbyte", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..3647e72 Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_