Compare commits

...

38 commits

Author SHA1 Message Date
Matthias Rupp
778ee8175e Rename MapMarkerResponseDtoDecorator to MapMarkerResponse 2023-05-08 02:02:23 -11:00
Matthias Rupp
3e47ca3815 Review suggestions 2023-05-07 21:24:55 -11:00
Matthias Rupp
ab7102bf50 Remove unneccessary filter statement 2023-05-07 21:12:40 -11:00
Matthias Rupp
0f28a1893f Linter error 2023-05-07 09:00:12 -11:00
Matthias Rupp
de617093bf Remove assetId from preloaded responses 2023-05-07 08:52:16 -11:00
Matthias Rupp
7a8455c254 Rework MapMarkerResponseDto 2023-05-07 07:00:06 -11:00
Matthias Rupp
6127d3f8f6 Extend coordinate rounding unit test 2023-05-07 05:24:04 -11:00
Matthias Rupp
1917542091 Fix web type problems 2023-05-06 21:50:33 -11:00
Matthias Rupp
0e516d1685 Clean up 2023-05-06 21:18:24 -11:00
Matthias Rupp
e85eb4e179 add browser check 2023-05-06 09:32:00 -11:00
Matthias Rupp
b1fbefe6c6 Preload functionality 2023-05-06 08:52:02 -11:00
Matthias Rupp
855a68415c Merge remote-tracking branch 'origin/main' into feat/global-map-optim 2023-05-05 20:48:06 -11:00
Matthias Rupp
616c983428 Initial experiments 2023-05-04 22:47:15 -11:00
Matthias Rupp
d341fc0d1d Clean up leaflet imports 2023-05-04 21:45:07 -11:00
Matthias Rupp
0f302c76d7 Chage mapMarker endpoint to map-marker 2023-05-04 21:40:48 -11:00
Matthias Rupp
c6164aeade Linter error 2023-05-02 08:20:36 -11:00
Matthias Rupp
eaa2365416 Review suggestions 2023-05-02 08:18:00 -11:00
Matthias Rupp
655423571e Review suggestions 2023-05-02 08:13:57 -11:00
Matthias Rupp
6b1a863e2d Update API 2023-05-02 01:22:25 -11:00
Matthias Rupp
934fcf03f1 fix: Support video thumbnails 2023-05-02 00:50:22 -11:00
Matthias Rupp
ce4fbdecfa Map markers test 2023-05-02 00:23:18 -11:00
Matthias Rupp
44c750cfa4 Fix openapi mobile code generation issues 2023-05-02 00:02:03 -11:00
Matthias Rupp
8c79e8e719 Server code style 2023-05-01 23:24:12 -11:00
Matthias Rupp
fc21e37b2c Run prettier 2023-05-01 23:22:41 -11:00
Matthias Rupp
7f7ef949df Fix eslint error 2023-05-01 22:04:32 -11:00
Matthias Rupp
73f1ad6e73 Fix ts errors 2023-05-01 22:00:47 -11:00
Matthias Rupp
cb781c250b Add newlines 2023-05-01 21:32:35 -11:00
Matthias Rupp
71c7438a79 Fix linter errors 2023-05-01 21:26:03 -11:00
Matthias Rupp
f49e122361 Allow cluster viewing 2023-05-01 21:03:52 -11:00
Matthias Rupp
d48b0f7a1d Center map to most recent asset 2023-05-01 08:45:49 -11:00
Matthias Rupp
a87700c9a5 Add dark theme support 2023-05-01 08:37:56 -11:00
Matthias Rupp
e30fe5e208 Remove sidebar icon flip 2023-04-30 08:09:52 -11:00
Matthias Rupp
1b1d2f0ba4 Add API endpoint that returns only assets with location information (Thanks @EPP100) 2023-04-30 08:01:49 -11:00
Matthias Rupp
9a1e8e55f5 Add asset viewer 2023-04-29 03:45:23 -11:00
Matthias Rupp
337b42a838 Refactor 2023-04-29 03:25:44 -11:00
Matthias Rupp
30c6fa9cf7 Minor layout changes 2023-04-29 03:21:04 -11:00
Matthias Rupp
6e0859b67c Use single DOM element for all markers 2023-04-28 22:00:07 -11:00
Matthias Rupp
7b550023a8 First crude implementation of the global asset map in web 2023-04-28 21:34:52 -11:00
24 changed files with 243 additions and 444 deletions

View file

@ -55,7 +55,6 @@ doc/JobStatusDto.md
doc/LoginCredentialDto.md
doc/LoginResponseDto.md
doc/LogoutResponseDto.md
doc/MapMarkerResponseDto.md
doc/OAuthApi.md
doc/OAuthCallbackDto.md
doc/OAuthConfigDto.md
@ -172,7 +171,6 @@ lib/model/job_status_dto.dart
lib/model/login_credential_dto.dart
lib/model/login_response_dto.dart
lib/model/logout_response_dto.dart
lib/model/map_marker_response_dto.dart
lib/model/o_auth_callback_dto.dart
lib/model/o_auth_config_dto.dart
lib/model/o_auth_config_response_dto.dart
@ -266,7 +264,6 @@ test/job_status_dto_test.dart
test/login_credential_dto_test.dart
test/login_response_dto_test.dart
test/logout_response_dto_test.dart
test/map_marker_response_dto_test.dart
test/o_auth_api_test.dart
test/o_auth_callback_dto_test.dart
test/o_auth_config_dto_test.dart

View file

@ -210,7 +210,6 @@ Class | Method | HTTP request | Description
- [LoginCredentialDto](doc//LoginCredentialDto.md)
- [LoginResponseDto](doc//LoginResponseDto.md)
- [LogoutResponseDto](doc//LogoutResponseDto.md)
- [MapMarkerResponseDto](doc//MapMarkerResponseDto.md)
- [OAuthCallbackDto](doc//OAuthCallbackDto.md)
- [OAuthConfigDto](doc//OAuthConfigDto.md)
- [OAuthConfigResponseDto](doc//OAuthConfigResponseDto.md)

View file

@ -1041,7 +1041,7 @@ This endpoint does not need any parameter.
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **getMapMarkers**
> List<MapMarkerResponseDto> getMapMarkers(isFavorite, isArchived, skip)
> List<Object> getMapMarkers(preload)
@ -1054,6 +1054,10 @@ import 'package:openapi/api.dart';
//defaultApiClient.getAuthentication<ApiKeyAuth>('cookie').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('cookie').apiKeyPrefix = 'Bearer';
// TODO Configure API key authorization: api_key
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key').apiKeyPrefix = 'Bearer';
// TODO Configure HTTP Bearer authorization: bearer
// Case 1. Use String Token
//defaultApiClient.getAuthentication<HttpBearerAuth>('bearer').setAccessToken('YOUR_ACCESS_TOKEN');
@ -1062,12 +1066,10 @@ import 'package:openapi/api.dart';
//defaultApiClient.getAuthentication<HttpBearerAuth>('bearer').setAccessToken(yourTokenGeneratorFunction);
final api_instance = AssetApi();
final isFavorite = true; // bool |
final isArchived = true; // bool |
final skip = 8.14; // num |
final preload = true; // bool |
try {
final result = api_instance.getMapMarkers(isFavorite, isArchived, skip);
final result = api_instance.getMapMarkers(preload);
print(result);
} catch (e) {
print('Exception when calling AssetApi->getMapMarkers: $e\n');
@ -1078,17 +1080,15 @@ try {
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**isFavorite** | **bool**| | [optional]
**isArchived** | **bool**| | [optional]
**skip** | **num**| | [optional]
**preload** | **bool**| | [optional]
### Return type
[**List<MapMarkerResponseDto>**](MapMarkerResponseDto.md)
[**List<Object>**](Object.md)
### Authorization
[cookie](../README.md#cookie), [bearer](../README.md#bearer)
[cookie](../README.md#cookie), [api_key](../README.md#api_key), [bearer](../README.md#bearer)
### HTTP request headers

View file

@ -1,18 +0,0 @@
# openapi.model.MapMarkerResponseDto
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**type** | [**AssetTypeEnum**](AssetTypeEnum.md) | |
**lat** | **double** | |
**lon** | **double** | |
**id** | **String** | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View file

@ -88,7 +88,6 @@ part 'model/job_status_dto.dart';
part 'model/login_credential_dto.dart';
part 'model/login_response_dto.dart';
part 'model/logout_response_dto.dart';
part 'model/map_marker_response_dto.dart';
part 'model/o_auth_callback_dto.dart';
part 'model/o_auth_config_dto.dart';
part 'model/o_auth_config_response_dto.dart';

View file

@ -985,12 +985,8 @@ class AssetApi {
///
/// Parameters:
///
/// * [bool] isFavorite:
///
/// * [bool] isArchived:
///
/// * [num] skip:
Future<Response> getMapMarkersWithHttpInfo({ bool? isFavorite, bool? isArchived, num? skip, }) async {
/// * [bool] preload:
Future<Response> getMapMarkersWithHttpInfo({ bool? preload, }) async {
// ignore: prefer_const_declarations
final path = r'/asset/map-marker';
@ -1001,14 +997,8 @@ class AssetApi {
final headerParams = <String, String>{};
final formParams = <String, String>{};
if (isFavorite != null) {
queryParams.addAll(_queryParams('', 'isFavorite', isFavorite));
}
if (isArchived != null) {
queryParams.addAll(_queryParams('', 'isArchived', isArchived));
}
if (skip != null) {
queryParams.addAll(_queryParams('', 'skip', skip));
if (preload != null) {
queryParams.addAll(_queryParams('', 'preload', preload));
}
const contentTypes = <String>[];
@ -1029,13 +1019,9 @@ class AssetApi {
///
/// Parameters:
///
/// * [bool] isFavorite:
///
/// * [bool] isArchived:
///
/// * [num] skip:
Future<List<MapMarkerResponseDto>?> getMapMarkers({ bool? isFavorite, bool? isArchived, num? skip, }) async {
final response = await getMapMarkersWithHttpInfo( isFavorite: isFavorite, isArchived: isArchived, skip: skip, );
/// * [bool] preload:
Future<List<Object>?> getMapMarkers({ bool? preload, }) async {
final response = await getMapMarkersWithHttpInfo( preload: preload, );
if (response.statusCode >= HttpStatus.badRequest) {
throw ApiException(response.statusCode, await _decodeBodyBytes(response));
}
@ -1044,8 +1030,8 @@ class AssetApi {
// FormatException when trying to decode an empty string.
if (response.body.isNotEmpty && response.statusCode != HttpStatus.noContent) {
final responseBody = await _decodeBodyBytes(response);
return (await apiClient.deserializeAsync(responseBody, 'List<MapMarkerResponseDto>') as List)
.cast<MapMarkerResponseDto>()
return (await apiClient.deserializeAsync(responseBody, 'List<Object>') as List)
.cast<Object>()
.toList();
}

View file

@ -275,8 +275,6 @@ class ApiClient {
return LoginResponseDto.fromJson(value);
case 'LogoutResponseDto':
return LogoutResponseDto.fromJson(value);
case 'MapMarkerResponseDto':
return MapMarkerResponseDto.fromJson(value);
case 'OAuthCallbackDto':
return OAuthCallbackDto.fromJson(value);
case 'OAuthConfigDto':

View file

@ -1,133 +0,0 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.12
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of openapi.api;
class MapMarkerResponseDto {
/// Returns a new [MapMarkerResponseDto] instance.
MapMarkerResponseDto({
required this.type,
required this.lat,
required this.lon,
required this.id,
});
AssetTypeEnum type;
double lat;
double lon;
String id;
@override
bool operator ==(Object other) => identical(this, other) || other is MapMarkerResponseDto &&
other.type == type &&
other.lat == lat &&
other.lon == lon &&
other.id == id;
@override
int get hashCode =>
// ignore: unnecessary_parenthesis
(type.hashCode) +
(lat.hashCode) +
(lon.hashCode) +
(id.hashCode);
@override
String toString() => 'MapMarkerResponseDto[type=$type, lat=$lat, lon=$lon, id=$id]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
json[r'type'] = this.type;
json[r'lat'] = this.lat;
json[r'lon'] = this.lon;
json[r'id'] = this.id;
return json;
}
/// Returns a new [MapMarkerResponseDto] instance and imports its values from
/// [value] if it's a [Map], null otherwise.
// ignore: prefer_constructors_over_static_methods
static MapMarkerResponseDto? fromJson(dynamic value) {
if (value is Map) {
final json = value.cast<String, dynamic>();
// Ensure that the map contains the required keys.
// Note 1: the values aren't checked for validity beyond being non-null.
// Note 2: this code is stripped in release mode!
assert(() {
requiredKeys.forEach((key) {
assert(json.containsKey(key), 'Required key "MapMarkerResponseDto[$key]" is missing from JSON.');
assert(json[key] != null, 'Required key "MapMarkerResponseDto[$key]" has a null value in JSON.');
});
return true;
}());
return MapMarkerResponseDto(
type: AssetTypeEnum.fromJson(json[r'type'])!,
lat: mapValueOfType<double>(json, r'lat')!,
lon: mapValueOfType<double>(json, r'lon')!,
id: mapValueOfType<String>(json, r'id')!,
);
}
return null;
}
static List<MapMarkerResponseDto> listFromJson(dynamic json, {bool growable = false,}) {
final result = <MapMarkerResponseDto>[];
if (json is List && json.isNotEmpty) {
for (final row in json) {
final value = MapMarkerResponseDto.fromJson(row);
if (value != null) {
result.add(value);
}
}
}
return result.toList(growable: growable);
}
static Map<String, MapMarkerResponseDto> mapFromJson(dynamic json) {
final map = <String, MapMarkerResponseDto>{};
if (json is Map && json.isNotEmpty) {
json = json.cast<String, dynamic>(); // ignore: parameter_assignments
for (final entry in json.entries) {
final value = MapMarkerResponseDto.fromJson(entry.value);
if (value != null) {
map[entry.key] = value;
}
}
}
return map;
}
// maps a json object with a list of MapMarkerResponseDto-objects as value to a dart map
static Map<String, List<MapMarkerResponseDto>> mapListFromJson(dynamic json, {bool growable = false,}) {
final map = <String, List<MapMarkerResponseDto>>{};
if (json is Map && json.isNotEmpty) {
// ignore: parameter_assignments
json = json.cast<String, dynamic>();
for (final entry in json.entries) {
map[entry.key] = MapMarkerResponseDto.listFromJson(entry.value, growable: growable,);
}
}
return map;
}
/// The list of required keys that must be present in a JSON.
static const requiredKeys = <String>{
'type',
'lat',
'lon',
'id',
};
}

View file

@ -119,7 +119,7 @@ void main() {
// Get all assets that have GPS information embedded
//
//Future<List<MapMarkerResponseDto>> getMapMarkers({ bool isFavorite, bool isArchived, num skip }) async
//Future<List<Object>> getMapMarkers({ bool preload }) async
test('test getMapMarkers', () async {
// TODO
});

View file

@ -1,42 +0,0 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.12
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
import 'package:openapi/api.dart';
import 'package:test/test.dart';
// tests for MapMarkerResponseDto
void main() {
// final instance = MapMarkerResponseDto();
group('test MapMarkerResponseDto', () {
// AssetTypeEnum type
test('to test the property `type`', () async {
// TODO
});
// double lat
test('to test the property `lat`', () async {
// TODO
});
// double lon
test('to test the property `lon`', () async {
// TODO
});
// String id
test('to test the property `id`', () async {
// TODO
});
});
}

View file

@ -36,6 +36,7 @@ export interface IAssetRepository {
getSearchPropertiesByUserId(userId: string): Promise<SearchPropertiesDto[]>;
getAssetCountByTimeBucket(userId: string, timeBucket: TimeGroupEnum): Promise<AssetCountByTimeBucket[]>;
getAssetCountByUserId(userId: string): Promise<AssetCountByUserIdResponseDto>;
getMapMarkerByUserId(ownerId: string): Promise<AssetEntity[]>;
getArchivedAssetCountByUserId(userId: string): Promise<AssetCountByUserIdResponseDto>;
getAssetByTimeBucket(userId: string, getAssetByTimeBucketDto: GetAssetByTimeBucketDto): Promise<AssetEntity[]>;
getAssetByChecksum(userId: string, checksum: Buffer): Promise<AssetEntity>;
@ -238,6 +239,30 @@ export class AssetRepository implements IAssetRepository {
});
}
/**
* Get all assets belong to the user on the database and that contain exif location information
* @param ownerId
*/
async getMapMarkerByUserId(ownerId: string): Promise<AssetEntity[]> {
return this.assetRepository.find({
where: {
ownerId,
resizePath: Not(IsNull()),
isVisible: true,
exifInfo: {
latitude: Not(IsNull()),
longitude: Not(IsNull()),
},
},
relations: {
exifInfo: true,
},
order: {
fileCreatedAt: 'DESC',
},
});
}
get(id: string): Promise<AssetEntity | null> {
return this.assetRepository.findOne({ where: { id } });
}

View file

@ -31,7 +31,9 @@ import { CheckDuplicateAssetDto } from './dto/check-duplicate-asset.dto';
import { ApiBody, ApiConsumes, ApiHeader, ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { CuratedObjectsResponseDto } from './response-dto/curated-objects-response.dto';
import { CuratedLocationsResponseDto } from './response-dto/curated-locations-response.dto';
import { AssetResponseDto, ImmichReadStream, MapMarkerResponseDto } from '@app/domain';
import { AssetResponseDto, ImmichReadStream } from '@app/domain';
import { GetMapMarkerDto } from './dto/get-map-marker.dto';
import { MapMarkerResponseDto } from './response-dto/map-marker-response.dto';
import { CheckDuplicateAssetResponseDto } from './response-dto/check-duplicate-asset-response.dto';
import { CreateAssetDto, mapToUploadFile } from './dto/create-asset.dto';
import { AssetFileUploadResponseDto } from './response-dto/asset-file-upload-response.dto';
@ -267,9 +269,9 @@ export class AssetController {
@Get('/map-marker')
getMapMarkers(
@GetAuthUser() authUser: AuthUserDto,
@Query(new ValidationPipe({ transform: true })) dto: AssetSearchDto,
@Query(new ValidationPipe({ transform: true })) query: GetMapMarkerDto,
): Promise<MapMarkerResponseDto[]> {
return this.assetService.getMapMarkers(authUser, dto);
return this.assetService.getMapMarkers(authUser, query.preload === true);
}
/**

View file

@ -142,6 +142,7 @@ describe('AssetService', () => {
getAll: jest.fn(),
getAllVideos: jest.fn(),
getAllByUserId: jest.fn(),
getMapMarkerByUserId: jest.fn(),
getAllByDeviceId: jest.fn(),
getAssetCountByTimeBucket: jest.fn(),
getById: jest.fn(),
@ -498,14 +499,30 @@ describe('AssetService', () => {
describe('get map markers', () => {
it('should get geo information of assets', async () => {
assetRepositoryMock.getAllByUserId.mockResolvedValue(_getAssets());
assetRepositoryMock.getMapMarkerByUserId.mockResolvedValue(
_getAssets().filter((asset) => asset.exifInfo?.latitude != null),
);
const markers = await sut.getMapMarkers(authStub.admin, {});
const markers = await sut.getMapMarkers(authStub.admin, false);
expect(markers).toHaveLength(1);
expect(markers[0].lat).toBe(_getAsset_1().exifInfo?.latitude);
expect(markers[0].lon).toBe(_getAsset_1().exifInfo?.longitude);
expect(markers[0].id).toBe(_getAsset_1().id);
expect(markers[0]).toHaveLength(3);
expect(markers[0][0]).toBeCloseTo(_getAsset_1().exifInfo?.latitude || 0, 4);
expect(markers[0][1]).toBeCloseTo(_getAsset_1().exifInfo?.longitude || 0, 4);
expect(markers[0][2]).toBe(_getAsset_1().id);
});
it('should preload assets', async () => {
assetRepositoryMock.getMapMarkerByUserId.mockResolvedValue(
_getAssets().filter((asset) => asset.exifInfo?.latitude != null),
);
const markers = await sut.getMapMarkers(authStub.admin, true);
expect(markers).toHaveLength(1);
expect(markers[0]).toHaveLength(2);
expect(markers[0][0]).toBeCloseTo(_getAsset_1().exifInfo?.latitude || 0, 4);
expect(markers[0][1]).toBeCloseTo(_getAsset_1().exifInfo?.longitude || 0, 4);
});
});
});

View file

@ -30,10 +30,9 @@ import {
JobName,
mapAsset,
mapAssetWithoutExif,
MapMarkerResponseDto,
mapAssetMapMarker,
} from '@app/domain';
import { CreateAssetDto, UploadFile } from './dto/create-asset.dto';
import { MapMarkerResponseDto, mapAssetMapMarker } from './response-dto/map-marker-response.dto';
import { DeleteAssetResponseDto, DeleteAssetStatusEnum } from './response-dto/delete-asset-response.dto';
import { GetAssetThumbnailDto, GetAssetThumbnailFormatEnum } from './dto/get-asset-thumbnail.dto';
import { CheckDuplicateAssetResponseDto } from './response-dto/check-duplicate-asset-response.dto';
@ -144,10 +143,10 @@ export class AssetService {
return assets.map((asset) => mapAsset(asset));
}
public async getMapMarkers(authUser: AuthUserDto, dto: AssetSearchDto): Promise<MapMarkerResponseDto[]> {
const assets = await this._assetRepository.getAllByUserId(authUser.id, dto);
public async getMapMarkers(authUser: AuthUserDto, preload: boolean): Promise<MapMarkerResponseDto[]> {
const assets = await this._assetRepository.getMapMarkerByUserId(authUser.id);
return assets.map((asset) => mapAssetMapMarker(asset)).filter((marker) => marker != null) as MapMarkerResponseDto[];
return assets.map((asset) => mapAssetMapMarker(asset, preload));
}
public async getAssetByTimeBucket(

View file

@ -0,0 +1,16 @@
import { Transform } from 'class-transformer';
import { IsBoolean, IsOptional } from 'class-validator';
import { toBoolean } from 'apps/immich/src/utils/transform.util';
import { ApiProperty } from '@nestjs/swagger';
export class GetMapMarkerDto {
@IsOptional()
@IsBoolean()
@Transform(toBoolean)
@ApiProperty()
/**
* true: returns only a list of locations
* false: also include asset id
*/
preload?: boolean;
}

View file

@ -0,0 +1,24 @@
import { AssetEntity } from '@app/infra/entities';
import { round } from 'lodash';
export type MapMarkerResponseDto = [
// latitude
number,
// longitude
number,
// assetId
string?,
];
export function mapAssetMapMarker(asset: AssetEntity, preload: boolean): MapMarkerResponseDto {
const lat = asset.exifInfo?.latitude || 0;
const lon = asset.exifInfo?.longitude || 0;
const response: MapMarkerResponseDto = [round(lat, 5), round(lon, 5)];
if (!preload) {
response.push(asset.id);
}
return response;
}

View file

@ -2607,28 +2607,12 @@
"description": "Get all assets that have GPS information embedded",
"parameters": [
{
"name": "isFavorite",
"name": "preload",
"required": false,
"in": "query",
"schema": {
"type": "boolean"
}
},
{
"name": "isArchived",
"required": false,
"in": "query",
"schema": {
"type": "boolean"
}
},
{
"name": "skip",
"required": false,
"in": "query",
"schema": {
"type": "number"
}
}
],
"responses": {
@ -2639,7 +2623,7 @@
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/MapMarkerResponseDto"
"type": "object"
}
}
}
@ -2655,6 +2639,9 @@
},
{
"cookie": []
},
{
"api_key": []
}
]
}
@ -5484,31 +5471,6 @@
"timeBucket"
]
},
"MapMarkerResponseDto": {
"type": "object",
"properties": {
"type": {
"$ref": "#/components/schemas/AssetTypeEnum"
},
"lat": {
"type": "number",
"format": "double"
},
"lon": {
"type": "number",
"format": "double"
},
"id": {
"type": "string"
}
},
"required": [
"type",
"lat",
"lon",
"id"
]
},
"UpdateAssetDto": {
"type": "object",
"properties": {

View file

@ -1,4 +1,3 @@
export * from './asset-response.dto';
export * from './exif-response.dto';
export * from './smart-info-response.dto';
export * from './map-marker-response.dto';

View file

@ -1,35 +0,0 @@
import { AssetEntity, AssetType } from '@app/infra/entities';
import { ApiProperty } from '@nestjs/swagger';
export class MapMarkerResponseDto {
id!: string;
@ApiProperty({ enumName: 'AssetTypeEnum', enum: AssetType })
type!: AssetType;
@ApiProperty({ type: 'number', format: 'double' })
lat!: number;
@ApiProperty({ type: 'number', format: 'double' })
lon!: number;
}
export function mapAssetMapMarker(entity: AssetEntity): MapMarkerResponseDto | null {
if (!entity.exifInfo) {
return null;
}
const lat = entity.exifInfo.latitude;
const lon = entity.exifInfo.longitude;
if (!lat || !lon) {
return null;
}
return {
id: entity.id,
type: entity.type,
lon,
lat,
};
}

View file

@ -86,4 +86,37 @@ export class ImmichApi {
}
}
export type MapMarkerResponseDto = [
// latitude
number,
// longitude
number,
// assetId
string
];
export class MapMarkerResponse {
constructor(private lat: number, private lon: number, private assetId: string | null) {}
static from(response: object): MapMarkerResponse {
const responseArray = response as MapMarkerResponseDto;
const assetId = responseArray.length === 3 ? responseArray[2] : null;
return new MapMarkerResponse(responseArray[0] as number, responseArray[1] as number, assetId);
}
static fromMany(responses: object[]): MapMarkerResponse[] {
return responses.map(MapMarkerResponse.from);
}
public getAssetId(): string | null {
return this.assetId;
}
public getLatLon(): [number, number] {
return [this.lat, this.lon];
}
}
export const api = new ImmichApi({ basePath: '/api' });

View file

@ -1438,39 +1438,6 @@ export interface LogoutResponseDto {
*/
'redirectUri': string;
}
/**
*
* @export
* @interface MapMarkerResponseDto
*/
export interface MapMarkerResponseDto {
/**
*
* @type {AssetTypeEnum}
* @memberof MapMarkerResponseDto
*/
'type': AssetTypeEnum;
/**
*
* @type {number}
* @memberof MapMarkerResponseDto
*/
'lat': number;
/**
*
* @type {number}
* @memberof MapMarkerResponseDto
*/
'lon': number;
/**
*
* @type {string}
* @memberof MapMarkerResponseDto
*/
'id': string;
}
/**
*
* @export
@ -4796,13 +4763,11 @@ export const AssetApiAxiosParamCreator = function (configuration?: Configuration
},
/**
* Get all assets that have GPS information embedded
* @param {boolean} [isFavorite]
* @param {boolean} [isArchived]
* @param {number} [skip]
* @param {boolean} [preload]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMapMarkers: async (isFavorite?: boolean, isArchived?: boolean, skip?: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
getMapMarkers: async (preload?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/asset/map-marker`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
@ -4817,20 +4782,15 @@ export const AssetApiAxiosParamCreator = function (configuration?: Configuration
// authentication cookie required
// authentication api_key required
await setApiKeyToObject(localVarHeaderParameter, "x-api-key", configuration)
// authentication bearer required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (isFavorite !== undefined) {
localVarQueryParameter['isFavorite'] = isFavorite;
}
if (isArchived !== undefined) {
localVarQueryParameter['isArchived'] = isArchived;
}
if (skip !== undefined) {
localVarQueryParameter['skip'] = skip;
if (preload !== undefined) {
localVarQueryParameter['preload'] = preload;
}
@ -5406,14 +5366,12 @@ export const AssetApiFp = function(configuration?: Configuration) {
},
/**
* Get all assets that have GPS information embedded
* @param {boolean} [isFavorite]
* @param {boolean} [isArchived]
* @param {number} [skip]
* @param {boolean} [preload]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getMapMarkers(isFavorite?: boolean, isArchived?: boolean, skip?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<MapMarkerResponseDto>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getMapMarkers(isFavorite, isArchived, skip, options);
async getMapMarkers(preload?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<object>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getMapMarkers(preload, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
@ -5674,14 +5632,12 @@ export const AssetApiFactory = function (configuration?: Configuration, basePath
},
/**
* Get all assets that have GPS information embedded
* @param {boolean} [isFavorite]
* @param {boolean} [isArchived]
* @param {number} [skip]
* @param {boolean} [preload]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getMapMarkers(isFavorite?: boolean, isArchived?: boolean, skip?: number, options?: any): AxiosPromise<Array<MapMarkerResponseDto>> {
return localVarFp.getMapMarkers(isFavorite, isArchived, skip, options).then((request) => request(axios, basePath));
getMapMarkers(preload?: boolean, options?: any): AxiosPromise<Array<object>> {
return localVarFp.getMapMarkers(preload, options).then((request) => request(axios, basePath));
},
/**
* Get all asset of a device that are in the database, ID only.
@ -5971,15 +5927,13 @@ export class AssetApi extends BaseAPI {
/**
* Get all assets that have GPS information embedded
* @param {boolean} [isFavorite]
* @param {boolean} [isArchived]
* @param {number} [skip]
* @param {boolean} [preload]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AssetApi
*/
public getMapMarkers(isFavorite?: boolean, isArchived?: boolean, skip?: number, options?: AxiosRequestConfig) {
return AssetApiFp(this.configuration).getMapMarkers(isFavorite, isArchived, skip, options).then((request) => request(this.axios, this.basePath));
public getMapMarkers(preload?: boolean, options?: AxiosRequestConfig) {
return AssetApiFp(this.configuration).getMapMarkers(preload, options).then((request) => request(this.axios, this.basePath));
}
/**

View file

@ -1,29 +1,23 @@
<script lang="ts" context="module">
import { createContext } from '$lib/utils/context';
import { MarkerClusterGroup, Marker, Icon, LeafletEvent } from 'leaflet';
const { get: getContext, set: setClusterContext } = createContext<() => MarkerClusterGroup>();
export const getClusterContext = () => {
return getContext()();
};
</script>
<script lang="ts">
import 'leaflet.markercluster';
import { MarkerClusterGroup, Marker, Icon, LeafletEvent } from 'leaflet';
import { onDestroy, onMount } from 'svelte';
import { getMapContext } from './map.svelte';
import { MapMarkerResponseDto, api } from '@api';
import { MapMarkerResponse, api } from '@api';
import { createEventDispatcher } from 'svelte';
class AssetMarker extends Marker {
marker: MapMarkerResponseDto;
marker: MapMarkerResponse;
constructor(marker: MapMarkerResponseDto) {
super([marker.lat, marker.lon], {
constructor(marker: MapMarkerResponse) {
const markerAssetId = marker.getAssetId();
super(marker.getLatLon(), {
alt: 'Loading...',
icon: new Icon({
iconUrl: api.getAssetThumbnailUrl(marker.id),
iconRetinaUrl: api.getAssetThumbnailUrl(marker.id),
className: 'marker-cluster-asset-marker',
iconUrl: markerAssetId ? api.getAssetThumbnailUrl(markerAssetId) : '',
iconRetinaUrl: markerAssetId ? api.getAssetThumbnailUrl(markerAssetId) : '',
iconSize: [60, 60],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
@ -35,22 +29,18 @@
this.marker = marker;
}
getAssetId(): string {
return this.marker.id;
getAssetId(): string | null {
return this.marker.getAssetId();
}
}
const dispatch = createEventDispatcher<{ view: { assets: string[] } }>();
export let markers: MapMarkerResponseDto[];
let cluster: MarkerClusterGroup;
const map = getMapContext();
let cluster: MarkerClusterGroup;
setClusterContext(() => cluster);
onMount(() => {
function setUpCluster(markers: MapMarkerResponse[]) {
cluster = new MarkerClusterGroup({
showCoverageOnHover: false,
zoomToBoundsOnClick: false,
@ -63,35 +53,52 @@
cluster.on('clusterclick', (event: LeafletEvent) => {
const ids = event.sourceTarget
.getAllChildMarkers()
.map((marker: AssetMarker) => marker.getAssetId());
dispatch('view', { assets: ids });
.map((marker: AssetMarker) => marker.getAssetId())
.filter((id: string | null) => id);
if (ids.length > 0) {
dispatch('view', { assets: ids });
}
});
for (let marker of markers) {
const leafletMarker = new AssetMarker(marker);
leafletMarker.on('click', () => {
dispatch('view', { assets: [marker.id] });
const id = leafletMarker.getAssetId();
if (id) {
dispatch('view', { assets: [id] });
}
});
cluster.addLayer(leafletMarker);
}
map.addLayer(cluster);
});
}
onMount(() => setUpCluster(markers));
export let markers: MapMarkerResponse[];
$: {
if (cluster) {
cluster.remove();
setUpCluster(markers);
}
}
onDestroy(() => {
if (cluster) cluster.remove();
});
</script>
{#if cluster}
<slot />
{/if}
<style>
:global(.leaflet-marker-icon) {
:global(.marker-cluster-asset-marker) {
border-radius: 25%;
background-color: rgba(236, 237, 246, 0.8);
line-height: 60px;
text-align: center;
}
:global(.marker-cluster) {

View file

@ -8,7 +8,7 @@ export const load = (async ({ locals: { api, user } }) => {
}
try {
const { data: mapMarkers } = await api.assetApi.getMapMarkers();
const { data: mapMarkers } = await api.assetApi.getMapMarkers(true);
return {
user,

View file

@ -8,17 +8,25 @@
isViewingAssetStoreState,
viewingAssetStoreState
} from '$lib/stores/asset-interaction.store';
import { api, MapMarkerResponse } from '@api';
import { onMount } from 'svelte';
import { browser } from '$app/environment';
export let data: PageData;
let mapMarkers: MapMarkerResponse[] = [];
let initialMapCenter: [number, number] = [48, 11];
$: {
if (data.mapMarkers.length) {
let firstMarker = data.mapMarkers[0];
initialMapCenter = [firstMarker.lat, firstMarker.lon];
onMount(async () => {
mapMarkers = MapMarkerResponse.fromMany(data.mapMarkers);
if (mapMarkers.length) {
initialMapCenter = mapMarkers[0].getLatLon();
}
}
const markersResponse = (await api.assetApi.getMapMarkers()).data;
mapMarkers = MapMarkerResponse.fromMany(markersResponse);
});
let viewingAssets: string[] = [];
let viewingAssetCursor = 0;
@ -46,22 +54,24 @@
<div slot="buttons" />
<div class="h-[90%] w-full">
{#await import('$lib/components/shared-components/leaflet') then { Map, TileLayer, AssetMarkerCluster }}
<Map latlng={initialMapCenter} zoom={7}>
<TileLayer
allowDarkMode={true}
urlTemplate={'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'}
options={{
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}}
/>
<AssetMarkerCluster
markers={data.mapMarkers}
on:view={(event) => onViewAssets(event.detail.assets)}
/>
</Map>
{/await}
{#if browser}
{#await import('$lib/components/shared-components/leaflet') then { Map, TileLayer, AssetMarkerCluster }}
<Map latlng={initialMapCenter} zoom={7}>
<TileLayer
allowDarkMode={true}
urlTemplate={'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'}
options={{
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}}
/>
<AssetMarkerCluster
markers={mapMarkers}
on:view={(event) => onViewAssets(event.detail.assets)}
/>
</Map>
{/await}
{/if}
</div>
</UserPageLayout>