dawarich/app/services/exports/create.rb

92 lines
2.1 KiB
Ruby
Raw Normal View History

2024-06-12 14:29:38 -04:00
# frozen_string_literal: true
class Exports::Create
def initialize(export:)
@export = export
@user = export.user
@start_at = export.start_at
@end_at = export.end_at
@file_format = export.file_format
2024-06-12 14:29:38 -04:00
end
def call
ActiveRecord::Base.transaction do
export.update!(status: :processing)
2024-06-12 14:29:38 -04:00
points = time_framed_points
2024-09-02 15:56:48 -04:00
data = points_data(points)
attach_export_file(data)
2024-06-12 14:29:38 -04:00
export.update!(status: :completed)
2024-07-04 16:20:12 -04:00
2025-03-24 15:58:43 -04:00
notify_export_finished
end
2024-06-12 14:29:38 -04:00
rescue StandardError => e
2025-03-24 15:58:43 -04:00
notify_export_failed(e)
2024-07-04 16:20:12 -04:00
2024-06-12 14:29:38 -04:00
export.update!(status: :failed)
end
private
attr_reader :user, :export, :start_at, :end_at, :file_format
2024-06-12 14:29:38 -04:00
def time_framed_points
user
.points
.where(timestamp: start_at.to_i..end_at.to_i)
.order(timestamp: :asc)
2024-06-12 14:29:38 -04:00
end
2024-08-22 16:40:27 -04:00
2025-03-24 15:58:43 -04:00
def notify_export_finished
2024-08-22 16:40:27 -04:00
Notifications::Create.new(
user:,
kind: :info,
title: 'Export finished',
content: "Export \"#{export.name}\" successfully finished."
).call
end
2025-03-24 15:58:43 -04:00
def notify_export_failed(error)
2024-08-22 16:40:27 -04:00
Notifications::Create.new(
user:,
kind: :error,
title: 'Export failed',
content: "Export \"#{export.name}\" failed: #{error.message}, stacktrace: #{error.backtrace.join("\n")}"
).call
end
2024-09-02 12:32:21 -04:00
2024-09-02 15:35:08 -04:00
def points_data(points)
case file_format.to_sym
2024-09-02 15:35:08 -04:00
when :json then process_geojson_export(points)
2024-09-28 06:45:22 -04:00
when :gpx then process_gpx_export(points)
else raise ArgumentError, "Unsupported file format: #{file_format}"
2024-09-02 15:35:08 -04:00
end
end
2024-09-02 14:51:34 -04:00
def process_geojson_export(points)
Points::GeojsonSerializer.new(points).call
2024-09-02 12:32:21 -04:00
end
def process_gpx_export(points)
Points::GpxSerializer.new(points, export.name).call
2024-09-02 15:35:08 -04:00
end
def attach_export_file(data)
export.file.attach(io: StringIO.new(data.to_s), filename: export.name, content_type:)
rescue StandardError => e
Rails.logger.error("Failed to create export file: #{e.message}")
raise
2024-09-02 12:32:21 -04:00
end
def content_type
case file_format.to_sym
when :json then 'application/json'
when :gpx then 'application/gpx+xml'
else raise ArgumentError, "Unsupported file format: #{file_format}"
end
end
2024-06-12 14:29:38 -04:00
end