Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/core/databases/adapters/objectbox/entities.dart
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ class TagObjectBox extends BaseObjectBox {
String? emoji;

int? categoryId;
int? colorSeedValue;

@override
@Property(type: PropertyType.date)
Expand All @@ -235,6 +236,7 @@ class TagObjectBox extends BaseObjectBox {
required this.version,
required this.emoji,
required this.categoryId,
required this.colorSeedValue,
required this.createdAt,
required this.updatedAt,
required this.permanentlyDeletedAt,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ TagObjectBox _modelToObject(Map<String, dynamic> options) {
version: model.version,
emoji: model.emoji,
categoryId: model.categoryId,
colorSeedValue: model.colorSeedValue,
createdAt: model.createdAt,
updatedAt: model.updatedAt,
lastSavedDeviceId: model.lastSavedDeviceId,
Expand All @@ -37,6 +38,7 @@ TagDbModel _objectToModel(Map<String, dynamic> options) {
title: object.title,
emoji: object.emoji,
categoryId: object.categoryId,
colorSeedValue: object.colorSeedValue,
createdAt: object.createdAt,
updatedAt: object.updatedAt,
lastSavedDeviceId: object.lastSavedDeviceId,
Expand Down
77 changes: 77 additions & 0 deletions lib/core/databases/adapters/objectbox/stories_box.dart
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,19 @@ class StoriesBox extends BaseBox<StoryObjectBox, StoryDbModel> {
AppLogger.info('🔍 Reindexed Stories: $count (Failed: $failed)');
}

/// With [namedOnly], only stories whose place has a name: filtered before [limit], so unnamed stories can't
/// crowd out a named one.
Future<List<MapStoryObject>> getStoriesWithLocation({
SpLatLngBounds? bounds,
int? limit,
bool namedOnly = false,
}) async {
Condition<StoryObjectBox> conditions = _storiesWithLocationConditions();

if (namedOnly) {
conditions = conditions.and(StoryObjectBox_.placeName.notNull()).and(StoryObjectBox_.placeName.notEquals(''));
}

if (bounds != null) {
conditions = conditions
.and(StoryObjectBox_.latitude.between(bounds.south, bounds.north))
Expand Down Expand Up @@ -308,6 +315,76 @@ class StoriesBox extends BaseBox<StoryObjectBox, StoryDbModel> {
return result.map(_objectToMapStoryObject).toList();
}

/// Every named place from stories (only those in [bounds], when given), each identical place once — for
/// picking a place by name, or the nearest one. Never limited: many stories at one place still come back as
/// that one place, so none nearby is left out. Reads only the place column (no story content), decoded off
/// the main isolate.
Future<List<PlaceDbModel>> getNamedPlaces({SpLatLngBounds? bounds}) async {
var conditions = _storiesWithLocationConditions()
.and(StoryObjectBox_.placeName.notNull())
.and(StoryObjectBox_.placeName.notEquals(''));
if (bounds != null) {
conditions = conditions
.and(StoryObjectBox_.latitude.between(bounds.south, bounds.north))
.and(StoryObjectBox_.longitude.between(bounds.west, bounds.east));
}
final query = box.query(conditions).build();

try {
final placeJsons = (query.property(StoryObjectBox_.place)..distinct = true).find();
return await Isolate.run(() {
final places = <PlaceDbModel>[];
for (final json in placeJsons) {
try {
if (jsonDecode(json) case final Map<String, dynamic> map) places.add(PlaceDbModel.fromJson(map));
} catch (_) {
// One malformed place mustn't empty the whole list.
}
}
return places;
});
} finally {
query.close();
}
}

/// Sets story [id]'s place to [place] in one write transaction, only while its saved place still passes
/// [isExpected]: a place that arrives late (a GPS fix, a name lookup) can neither write back an older copy of
/// the story nor replace a place changed meanwhile. Only the place (and [StoryObjectBox.updatedAt]) changes.
/// [exists] is false when there's no such story (not saved yet, or permanently deleted); [updated] is the
/// story as saved, null when nothing was written.
Future<({bool exists, StoryDbModel? updated})> setPlaceIf(
int id,
PlaceDbModel place, {
required bool Function(PlaceDbModel? saved) isExpected,
}) async {
final written = store.runInTransaction(TxMode.write, () {
final object = box.get(id);
if (object == null || object.permanentlyDeletedAt != null) return null;

final saved = object.place != null ? PlaceDbModel.fromJson(jsonDecode(object.place!)) : null;
if (!isExpected(saved)) return false;

object
..latitude = place.latitude
..longitude = place.longitude
..placeName = place.placeName
..place = jsonEncode(place.toJson())
..updatedAt = DateTime.now()
// The place name is searched: reindexed when the search view opens.
..searchMetadata = null
..setDeviceId();
box.put(object, mode: PutMode.update);
return true;
});

if (written != true) return (exists: written != null, updated: null);

final updated = await find(id);
await afterCommit(id, updated);
return (exists: true, updated: updated);
}

Condition<StoryObjectBox> _storiesWithLocationConditions() {
return StoryObjectBox_.id
.notNull()
Expand Down
9 changes: 9 additions & 0 deletions lib/core/databases/models/place_db_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ class PlaceDbModel extends BaseDbModel {
return '${latitude.toStringAsFixed(4)}, ${longitude.toStringAsFixed(4)}';
}

/// "Locality, Country", or null when neither is known.
String? get areaLabel {
final parts = [locality?.trim(), country?.trim()].whereType<String>().where((e) => e.isNotEmpty);
return parts.isEmpty ? null : parts.join(', ');
}

/// A place's second line: its area, or its coordinates when the area isn't known.
String get areaOrCoordinatesLabel => areaLabel ?? '${latitude.toStringAsFixed(5)}, ${longitude.toStringAsFixed(5)}';

@override
int get id => 0;

Expand Down
9 changes: 9 additions & 0 deletions lib/core/databases/models/tag_db_model.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:ui';

import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:storypad/core/databases/adapters/objectbox/tags_box.dart';
Expand All @@ -21,6 +23,10 @@ class TagDbModel extends BaseDbModel {
final DateTime createdAt;
final int? categoryId;

/// The picked color, as ARGB. Its chip and dot colors are derived per brightness by
/// `TagColorService`, so only the seed is stored.
final int? colorSeedValue;

@override
final DateTime updatedAt;
final String? lastSavedDeviceId;
Expand All @@ -40,16 +46,19 @@ class TagDbModel extends BaseDbModel {
required this.updatedAt,
required this.lastSavedDeviceId,
required this.permanentlyDeletedAt,
this.colorSeedValue,
int? index,
}) : index = index ?? 0;

bool get feeling => categoryId == TagCategoryDbModel.feeling().id;
bool get isPerson => categoryId == TagCategoryDbModel.peopleId;
Color? get colorSeed => colorSeedValue != null ? Color(colorSeedValue!) : null;

TagDbModel.fromIDTitle(this.id, this.title)
: version = 0,
emoji = null,
categoryId = null,
colorSeedValue = null,
index = 0,
createdAt = DateTime.now(),
updatedAt = DateTime.now(),
Expand Down
16 changes: 15 additions & 1 deletion lib/core/databases/models/tag_db_model.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions lib/core/mixins/debounched_callback.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ mixin DebounchedCallback {
final Map<String, Timer?> _timers = {};
Timer? _singleTimer;

Timer? _timer(String? key) {
if (_timers.containsKey(key)) return _timers[key];
return _singleTimer;
}
// With a key: only that key's timer (a key not used yet has none). Without: the last one started.
Timer? _timer(String? key) => key == null ? _singleTimer : _timers[key];

void debouncedCallback(
VoidCallback callback, {
Expand Down
17 changes: 17 additions & 0 deletions lib/core/objects/sp_latlng.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:math' as math;

/// Platform-agnostic latitude/longitude coordinate.
///
/// Keeps the [MapAdapter] interface free from package-specific types like
Expand All @@ -8,6 +10,21 @@ class SpLatLng {
final double latitude;
final double longitude;

/// Great-circle distance in meters (haversine).
double distanceTo(SpLatLng other) {
const double earthRadius = 6371000.0;
double rad(double degrees) => degrees * math.pi / 180.0;

final dLat = rad(other.latitude - latitude);
final dLng = rad(other.longitude - longitude);
// Clamped: rounding can push it just past 1 for antipodal points, and sqrt(1 - a) would be NaN.
final a =
(math.pow(math.sin(dLat / 2), 2) +
math.cos(rad(latitude)) * math.cos(rad(other.latitude)) * math.pow(math.sin(dLng / 2), 2))
.clamp(0.0, 1.0);
return earthRadius * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));
Comment thread
theachoem marked this conversation as resolved.
Resolved
}

@override
String toString() => 'SpLatLng($latitude, $longitude)';

Expand Down
Loading
Loading