Class: Muzik::Client

Inherits:
Object
  • Object
show all
Includes:
Appscript
Defined in:
lib/muzik/client.rb

Constant Summary collapse

INDEX_FIELDS_CLOUD =
%i[artist title id updated_at].freeze
INDEX_FIELDS_LOCAL =
%i[artist title location id updated_at].freeze
TRASH_LIFE_SECONDS =
7 * 24 * 60 * 60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Client

Returns a new instance of Client.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/muzik/client.rb', line 21

def initialize(**options)
  if options[:cloud_url]
    self.google_drive = GoogleDrive::Session.from_config(options[:google_drive_config_location])
    self.cloud_directory = google_drive.folder_by_url(options[:cloud_url])
    self.cloud_index_file =
      cloud_directory.files(q: ['name = ? and trashed = false', 'index.csv']).first
    self.cloud_index_file = nil if cloud_index_file&.trashed?
  end

  if options[:github_access_token] && options[:github_repo]
    self.github = Octokit::Client.new(access_token: options[:github_access_token])
    self.repo = options[:github_repo]
  end

  self.apple_music = app(options[:apple_music]) if options[:apple_music]

  self.local_path = options[:local_path]
  self.upload_path = options[:upload_path]
  self.trash_path = options[:trash_path]
  self.log_location = options[:log_location]
end

Instance Attribute Details

#apple_musicObject

Returns the value of attribute apple_music.



9
10
11
# File 'lib/muzik/client.rb', line 9

def apple_music
  @apple_music
end

#cloud_directoryObject

Returns the value of attribute cloud_directory.



10
11
12
# File 'lib/muzik/client.rb', line 10

def cloud_directory
  @cloud_directory
end

#cloud_index_csvObject

Returns the value of attribute cloud_index_csv.



11
12
13
# File 'lib/muzik/client.rb', line 11

def cloud_index_csv
  @cloud_index_csv
end

#cloud_index_fileObject

Returns the value of attribute cloud_index_file.



12
13
14
# File 'lib/muzik/client.rb', line 12

def cloud_index_file
  @cloud_index_file
end

#githubObject

Returns the value of attribute github.



13
14
15
# File 'lib/muzik/client.rb', line 13

def github
  @github
end

#google_driveObject

Returns the value of attribute google_drive.



14
15
16
# File 'lib/muzik/client.rb', line 14

def google_drive
  @google_drive
end

#local_pathObject

Returns the value of attribute local_path.



15
16
17
# File 'lib/muzik/client.rb', line 15

def local_path
  @local_path
end

#log_locationObject

Returns the value of attribute log_location.



16
17
18
# File 'lib/muzik/client.rb', line 16

def log_location
  @log_location
end

#repoObject

Returns the value of attribute repo.



17
18
19
# File 'lib/muzik/client.rb', line 17

def repo
  @repo
end

#trash_pathObject

Returns the value of attribute trash_path.



18
19
20
# File 'lib/muzik/client.rb', line 18

def trash_path
  @trash_path
end

#upload_pathObject

Returns the value of attribute upload_path.



19
20
21
# File 'lib/muzik/client.rb', line 19

def upload_path
  @upload_path
end

Instance Method Details

#refresh_cloudObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/muzik/client.rb', line 64

def refresh_cloud
  print('Refreshing cloud library ~ ')
  return puts('Cloud index file not found.'.red) unless cloud_index_file

  download_index_file

  # Remove duplicates and build set of ids
  valid = {}
  songs = {}
  cloud_index_csv.each do |row|
    next unless row[:artist] && row[:title] && row[:id]

    songs[row[:artist]] ||= Set.new
    unless songs[row[:artist]].include?(row[:title])
      songs[row[:artist]] << row[:title]
      valid[row[:id]] = row
      next
    end

    google_drive.file_by_id(row[:id])&.delete
  end

  # Remove rogue files and build new index
  rows = []
  cloud_directory.subfolders(q: ['trashed = false']) do |directory|
    directory_empty = true
    directory.files(q: ['trashed = false']) do |file|
      unless file.full_file_extension == 'mp3'
        directory_empty = false
        next
      end

      if valid[file.id]
        directory_empty = false
        valid[file.id][:updated_at] = file.modified_time.to_time.to_i
        rows << valid[file.id]
      else
        file.delete
      end
    end

    directory.delete if directory_empty
  end

  rows.sort_by! { |row| [row[:artist], row[:title]] }

  csv = CSV.new('', **csv_options)
  csv << INDEX_FIELDS_CLOUD
  rows.each { |row| csv << row }
  io = csv.to_io
  io.rewind

  cloud_index_file.update_from_io(io)

  if github?
    io.rewind
    update_github_library(io.read)
  end

  puts('done'.green)
rescue StandardError => error
  log_error(error)
end

#refresh_localObject



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/muzik/client.rb', line 128

def refresh_local
  print('Refreshing local library ~ ')
  return puts('No local index file found.'.red) unless File.exists?(local_index_file_location)

  songs = {}
  local_index_csv = CSV.read(local_index_file_location, **csv_options)
  raise('Invalid headers on local index file.') unless
    local_index_csv.headers.sort == INDEX_FIELDS_LOCAL.sort

  # Remove duplicates and build set of file locations
  locations = Set.new
  songs = {}
  local_index_csv.each do |row|
    next unless row[:artist] && row[:title] && row[:location]

    songs[row[:artist]] ||= Set.new
    unless songs[row[:artist]].include?(row[:title])
      songs[row[:artist]] << row[:title]
      locations << row[:location]
      next
    end

    move_file_to_trash(row[:location])
  end

  download_index_file unless cloud_index_csv

  cloud_index = {}
  cloud_index_csv.each do |row|
    cloud_index[row[:artist]] ||= {}
    cloud_index[row[:artist]][row[:title]] = row[:id]
  end

  # Remove rogue files and build new index
  rows = []
  Dir["#{local_path}/**/*.mp3"].each do |file_name|
    if locations.include?(file_name)
      File.open(file_name, 'rb') do |file|
        ID3Tag.read(file) do |tag|
          id = cloud_index.dig(tag.artist, tag.title)
          if id
            apple_music.add(file_name) if apple_music?
            rows << local_csv_row_for(
              artist: tag.artist,
              id: id,
              location: file_name,
              title: tag.title,
              updated_at: file.mtime.to_i
            )
          else
            move_file_to_trash(file_name)
          end
        end
      end
    else
      move_file_to_trash(file_name)
    end
  end

  artist_index = INDEX_FIELDS_LOCAL.index(:artist)
  title_index = INDEX_FIELDS_LOCAL.index(:title)
  rows.sort_by! { |row| [row[artist_index], row[title_index]] }

  CSV.open(local_index_file_location, 'w', **csv_options) do |csv|
    csv << INDEX_FIELDS_LOCAL
    rows.each { |row| csv << row }
  end

  cleanup
  puts('done'.green)
end

#setup_cloudObject



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/muzik/client.rb', line 43

def setup_cloud
  print('Setting up cloud ~ ')
  return puts('Cloud index file already exists.'.red) if cloud_index_file

  csv = CSV.new('', **csv_options)
  csv << INDEX_FIELDS_CLOUD
  csv.rewind

  cloud_directory.upload_from_io(csv.to_io, 'index.csv')
  puts('done'.green)
end

#setup_localObject



55
56
57
58
59
60
61
62
# File 'lib/muzik/client.rb', line 55

def setup_local
  print('Setting up local ~ ')
  return puts('Local index file already exists.'.red) if
    File.exists?(local_index_file_location)

  CSV.open(local_index_file_location, 'w', **csv_options) { |csv| csv << INDEX_FIELDS_LOCAL }
  puts('done'.green)
end

#syncObject



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/muzik/client.rb', line 200

def sync
  puts('Synching local library with cloud ~ ')

  local_index = {}
  if File.exists?(local_index_file_location)
    local_index_csv = CSV.read(local_index_file_location, **csv_options)
    raise('Invalid headers on local index file.') unless
      local_index_csv.headers.sort == INDEX_FIELDS_LOCAL.sort

    local_index_csv.each { |row| local_index[row[:id]] = row.to_h.except(:id) }
  end


  download_index_file
  locations = Set.new
  rows = []
  process_valid_row = proc do |file_name, row|
    locations << file_name

    rows << local_csv_row_for(
      location: file_name,
      **row.to_h.slice(:artist, :id, :title, :updated_at)
    )

    apple_music.add(file_name) if apple_music?
  end

  count = 0
  partial_failure = false
  cloud_index_csv.each do |row|
    local_data = local_index.delete(row[:id])
    if local_data&.dig(:location) && local_data.except(:location) == row.to_h.except(:id)
      process_valid_row.call(local_data[:location], row)
      next
    end

    print("#{row[:artist]} - #{row[:title]}")

    file = google_drive.file_by_id(row[:id])
    new_directory = "#{local_path}/#{google_drive.folder_by_id(file.parents.first).name}"
    FileUtils.mkdir_p(new_directory) unless File.directory?(new_directory)
    new_file_name = "#{new_directory}/#{file.name}"

    file.download_to_file(new_file_name)
    FileUtils.touch(new_file_name, mtime: row[:updated_at].to_i)
    process_valid_row.call(new_file_name, row)
    count += 1

    puts(''.green)
  rescue StandardError => error
    puts(''.red) if row[:artist] && row[:title]
    log_error(error)
    partial_failure = true
  end

  artist_index = INDEX_FIELDS_LOCAL.index(:artist)
  title_index = INDEX_FIELDS_LOCAL.index(:title)
  rows.sort_by! { |row| [row[artist_index], row[title_index]] }

  CSV.open(local_index_file_location, 'w', **csv_options) do |csv|
    csv << INDEX_FIELDS_LOCAL
    rows.each { |row| csv << row }
  end

  if partial_failure
    refresh_local
  else
    Dir["#{local_path}/**/*.mp3"].each do |file_name|
      move_file_to_trash(file_name) unless locations.include?(file_name)
    end

    cleanup
  end

  puts("#{count} file#{count == 1 ? '' : 's'} downloaded.".green)
rescue StandardError => error
  puts('Failed.'.red)
  log_error(error)
  refresh_local if cloud_index_csv
end

#uploadObject



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/muzik/client.rb', line 281

def upload
  puts('Uploading new music ~ ')

  count = 0
  rows = []
  uploaded_files = []
  partial_failure = false
  begin
    directories = {}
    file_names = Dir["#{upload_path}/*.mp3"]
    new_songs = {}
    duplicates = []
    artist = title = nil
    file_names.each do |file_name|
      artist = title = nil
      File.open(file_name, 'rb') do |file|
        ID3Tag.read(file) do |tag|
          artist = tag.artist
          title = tag.title
        end
      end

      new_songs[artist] ||= Set.new
      next duplicates << file_name if new_songs[artist].include?(title)

      print("#{artist} - #{title}")
      new_songs[artist] << title

      unless directories[artist]
        directories[artist] =
          cloud_directory.subfolders(q: ['name = ? and trashed = false', artist]).first ||
          cloud_directory.create_subfolder(artist)
      end

      new_file_name = "#{title}.mp3".tr('/?#', '_')
      file = directories[artist].files(q: ['name = ? and trashed = false', new_file_name]).first
      if file && !file.trashed?
        file.update_from_file(file_name)
        file = google_drive.file_by_id(file.id)
      else
        file = directories[artist].upload_from_file(file_name, new_file_name)
      end

      rows << cloud_csv_row_for(
        artist: artist,
        id: file.id,
        title: title,
        updated_at: file.modified_time.to_time.to_i
      )
      uploaded_files << file_name
      count += 1
      puts(''.green)
    end
  rescue StandardError => error
    puts(''.red) if artist && title
    log_error(error)
    partial_failure = true
  end

  begin
    artist_index = INDEX_FIELDS_CLOUD.index(:artist)
    title_index = INDEX_FIELDS_CLOUD.index(:title)

    if cloud_index_file
      download_index_file
      cloud_index_csv.to_a[1..].each do |row|
        rows << row unless new_songs[row[artist_index]]&.include?(row[title_index])
      end
    end

    rows.sort_by! { |row| [row[artist_index], row[title_index]] }

    csv = CSV.new('', **csv_options)
    csv << INDEX_FIELDS_CLOUD
    rows.each { |row| csv << row }
    io = csv.to_io
    io.rewind

    if cloud_index_file
      cloud_index_file.update_from_io(io)
    else
      cloud_directory.upload_from_io(io, 'index.csv')
    end
  rescue StandardError => error
    puts('Failed.'.red)
    puts
    log_error(error)
    refresh_cloud
    return
  end

  if count.positive? && github?
    io.rewind
    update_github_library(io.read)
  end

  begin
    uploaded_files.each { |file_name| move_file_to_trash(file_name) }
  rescue StandardError => error
    log_error(error)
    remove_failure = true
  end

  puts("#{count} file#{count == 1 ? '' : 's'} uploaded.".green)
  puts

  if partial_failure
    puts('Some files failed to upload.'.yellow)
    refresh_cloud
  end

  puts('Some files could not be removed.'.yellow) if remove_failure
  return if duplicates.empty?

  puts('Duplicate files ignored:'.yellow)
  duplicates.each { |duplicate| puts(duplicate) }
end