1
+ # Will export the zip file to /tmp/superset_dashboards with zip filename adjusted to include the dashboard_id
2
+ # Example zipfile: dashboard_#{dashboard_id}_export_#{datestamp}.zip
3
+ # Will then unzip and copy the files into the destination_path with the dashboard_id as a subfolder
4
+ #
5
+ # Usage
6
+ # Superset::Dashboard::Export.new(dashboard_id: 15, destination_path: '/tmp/superset_dashboard_backups/').perform
7
+ #
8
+
9
+ require 'superset/file_utilities'
10
+
11
+ module Superset
12
+ module Dashboard
13
+ class Export < Request
14
+ include FileUtilities
15
+
16
+ TMP_SUPERSET_DASHBOARD_PATH = '/tmp/superset_dashboards'
17
+
18
+ attr_reader :dashboard_id , :destination_path
19
+
20
+ def initialize ( dashboard_id : , destination_path : )
21
+ @dashboard_id = dashboard_id
22
+ @destination_path = destination_path . chomp ( '/' )
23
+ end
24
+
25
+ def perform
26
+ create_tmp_dir
27
+ save_exported_zip_file
28
+ unzip_files
29
+ copy_export_files_to_destination_path if destination_path
30
+ end
31
+
32
+ def response
33
+ @response ||= client . call (
34
+ :get ,
35
+ client . url ( route ) ,
36
+ client . param_check ( params )
37
+ )
38
+ end
39
+
40
+ private
41
+
42
+ def params
43
+ { "q" : "!(#{ dashboard_id } )" } # pulled off chrome dev tools doing a GUI export. Swagger interface not helpfull with this endpoint.
44
+ end
45
+
46
+ def save_exported_zip_file
47
+ File . open ( zip_file_name , 'wb' ) { |fp | fp . write ( response . body ) }
48
+ end
49
+
50
+ def unzip_files
51
+ @extracted_files = unzip_file ( zip_file_name , tmp_uniq_dashboard_path )
52
+ end
53
+
54
+ def download_folder
55
+ File . dirname ( extracted_files [ 0 ] )
56
+ end
57
+
58
+ def copy_export_files_to_destination_path
59
+ path_with_dash_id = File . join ( destination_path , dashboard_id . to_s )
60
+ FileUtils . mkdir_p ( path_with_dash_id ) unless File . directory? ( path_with_dash_id )
61
+
62
+ Dir . glob ( "#{ download_folder } /*" ) . each do |item |
63
+ FileUtils . cp_r ( item , path_with_dash_id )
64
+ end
65
+ end
66
+
67
+ def zip_file_name
68
+ @zip_file_name ||= "#{ tmp_uniq_dashboard_path } /dashboard_#{ dashboard_id } _export_#{ datestamp } .zip"
69
+ end
70
+
71
+ def create_tmp_dir
72
+ FileUtils . mkdir_p ( tmp_uniq_dashboard_path ) unless File . directory? ( tmp_uniq_dashboard_path )
73
+ end
74
+
75
+ # uniq random tmp folder name for each export
76
+ # this will allow us to do a wildcard glop on the folder to get the files
77
+ def tmp_uniq_dashboard_path
78
+ @tmp_uniq_dashboard_path ||= File . join ( TMP_SUPERSET_DASHBOARD_PATH , uuid )
79
+ end
80
+
81
+ def uuid
82
+ SecureRandom . uuid
83
+ end
84
+
85
+ def extracted_files
86
+ @extracted_files ||= [ ]
87
+ end
88
+
89
+ def route
90
+ "dashboard/export/"
91
+ end
92
+
93
+ def datestamp
94
+ @datestamp ||= Time . now . strftime ( '%Y%m%d' )
95
+ end
96
+ end
97
+ end
98
+ end
0 commit comments