1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
127
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
199
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
280
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
require 'rubygems'
require 'flacinfo'
require 'fileutils'
require 'image_science'

class ImportsController < ApplicationController
=begin  

this routine will check a folder for flac files, and then apply the vorbis comments
it finds to the relevant database tables.
        
todo:
        
* ability to select directory and then import from that.
* integrate MB (MusicBrainz) ids, cat#s, other details?
* speed up. Find memory leaks.
* is currently unaware of changes to existing data (i.e. genres added/removed, artist
name changes) Need to be able to import data, and also modify data.
* do not add data that already exists (check against MBIDs). Still failing in this regard

=end

  def determine_folder(identifier, path, filetype)
    rounded_down = ((((identifier-1) / 1000) * 1000)+1).to_s
    rounded_up = ((((identifier-1) / 1000) + 1) * 1000).to_s
    folder = path + rounded_down + "_" + rounded_up
    Dir.mkdir(folder) unless File.directory?(folder)
    return folder + "/" + identifier.to_s + "." + filetype
  end

  def index

    if session[:user_id].nil?
    @genreslist = genre_list    
      else
    @personal_genreslist = personal_genre_list  
    @genreslist = genre_list - personal_genre_list
    end unless Genre.count == 0

    #Dir.chdir("/media/hda5/flacs/batch_9") 
    #Dir.chdir("/media/LACIE/Music/flac/")
    Dir.chdir("/media/big_content/flacs/batch_todo")
    flacfiles = ("**/*.flac")
    Dir.glob(flacfiles) do |filename|

    new_job = FlacInfo.new(filename)

    path_to_file = Dir.getwd + "/" + File.new(filename).path
    tagged_file = new_job.tags

    artist_type = ArtistType.find(:first,
      :conditions => {:name => 'primary artist'})

    artist_type = ArtistType.create(:name => 'primary artist') unless artist_type      

    artist = Artist.find(:first, 
      :conditions => {:mbid => tagged_file["musicbrainz_artistid"]}
    )

    artist = Artist.update(artist, :name => tagged_file["artist"],
      :sortname => tagged_file["artistsort"]) if artist

    artist = Artist.create(:name => tagged_file["artist"], 
      :sortname => tagged_file["artistsort"],
        :mbid => tagged_file["musicbrainz_artistid"]) unless artist

    albumartist = Artist.find(:first, 
      :conditions => {:mbid => tagged_file["musicbrainz_albumartistid"]}
    )

    albumartist = Artist.update(albumartist, :name => tagged_file["albumartist"], 
      :sortname => tagged_file["albumartistsort"]) if albumartist

    albumartist = Artist.create(:name => tagged_file["albumartist"], 
      :sortname => tagged_file["albumartistsort"],
        :mbid => tagged_file["musicbrainz_albumartistid"]) unless albumartist

    track_type = TrackType.find(:first,
      :conditions => {:name => 'audio'})

    track_type = TrackType.create(:name => 'audio') unless track_type  

    sample_rate = new_job.streaminfo['samplerate']
    total_sample = new_job.streaminfo['total_samples']
    duration_in_seconds = total_sample / sample_rate

    track = Track.find(:first, 
      :conditions => {:mbid => tagged_file["musicbrainz_trackid"]}
      )

    track = Track.update(track, :name => tagged_file["title"],
      :timing => Time.at(duration_in_seconds).gmtime.strftime('%H:%M:%S'), 
        :track_type_id => track_type.id,
          :artist_id => artist.id) if track   

    track = Track.create(:name => tagged_file["title"], 
      :mbid => tagged_file["musicbrainz_trackid"], 
        :timing => Time.at(duration_in_seconds).gmtime.strftime('%H:%M:%S'), 
          :track_type_id => track_type.id,
            :artist_id => artist.id) unless track

    track_artist = TrackArtist.find(:first,
      :conditions => {:track_id => track.id,
        :artist_id => artist.id,
          :artist_type_id => artist_type.id
      }
    )      

    track_artist = TrackArtist.create(:track_id => track.id,
      :artist_id => artist.id,
        :artist_type_id => artist_type.id) unless track_artist      

    release_type = ReleaseType.find(:first,
      :conditions => {:name => tagged_file["releasetype"]}
    )

    release_type = ReleaseType.create(:name => tagged_file["releasetype"]) unless release_type 

    release = tagged_file["album"]
    unless release.nil? 
    release = Release.find(:first, 
      :conditions => {:mbid => tagged_file["musicbrainz_albumid"]}
    )

    release = Release.update(release, :name => tagged_file["album"], 
      :release_type_id => release_type.id,
        :artist_id => albumartist.id) if release

    release = Release.create(:name => tagged_file["album"], 
      :mbid => tagged_file["musicbrainz_albumid"],
        :release_type_id => release_type.id,
          :artist_id => albumartist.id) unless release

    thirty_thumb_packshot = '/media/hdb1/railsapps/marlow/public/images/packshots/30_thumb/' 
    thirty_thumb_sym = '/home/jp/RailsStuff/marlow/public/images/packshots/30_thumb/'
    sixty_thumb_packshot = '/media/hdb1/railsapps/marlow/public/images/packshots/60_thumb/'
    sixty_thumb_sym = '/home/jp/RailsStuff/marlow/public/images/packshots/60_thumb/'
    twohundred_thumb_packshot = '/media/hdb1/railsapps/marlow/public/images/packshots/200_thumb/'
    twohundred_thumb_sym = '/home/jp/RailsStuff/marlow/public/images/packshots/200_thumb/'
    source_packshot = '/media/hdb1/railsapps/marlow/public/images/packshots/source/'

    ogg_audio = '/media/hdb1/railsapps/marlow/public/media/audio/ogg/'
    m4a_audio = '/media/hdb1/railsapps/marlow/public/media/audio/m4a/'
    ogg_sym = '/home/jp/RailsStuff/marlow/public/media/audio/ogg/'
    m4a_sym = '/home/jp/RailsStuff/marlow/public/media/audio/m4a/'

    packshot = Dir.glob("**/#{tagged_file['musicbrainz_albumid']}.jpg").to_s
    if packshot.length > 0
      ImageScience.with_image(packshot) do |img|

  img.thumbnail(30) do |thumb|
          thumb.save(determine_folder(release.id, thirty_thumb_packshot, 'jpg'))
    symlink = File.symlink?(determine_folder(release.id, thirty_thumb_sym, 'jpg'))
    if symlink == true
      File.delete(determine_folder(release.id, thirty_thumb_sym, 'jpg'))
      File.symlink("#{determine_folder(release.id, thirty_thumb_packshot, 'jpg')}", "#{determine_folder(release.id, thirty_thumb_sym, 'jpg')}")
      else
      File.symlink("#{determine_folder(release.id, thirty_thumb_packshot, 'jpg')}", "#{determine_folder(release.id, thirty_thumb_sym, 'jpg')}")
    end
    #print "#{determine_folder(release.id, thirty_thumb_packshot, 'jpg')}"
        end

        img.thumbnail(60) do |thumb|
          thumb.save(determine_folder(release.id, sixty_thumb_packshot, 'jpg'))
    symlink = File.symlink?(determine_folder(release.id, sixty_thumb_sym, 'jpg'))
    if symlink == true
      File.delete(determine_folder(release.id, sixty_thumb_sym, 'jpg'))
      File.symlink("#{determine_folder(release.id, sixty_thumb_packshot, 'jpg')}", "#{determine_folder(release.id, sixty_thumb_sym, 'jpg')}")
      else
      File.symlink("#{determine_folder(release.id, sixty_thumb_packshot, 'jpg')}", "#{determine_folder(release.id, sixty_thumb_sym, 'jpg')}")
    end
    #print "#{determine_folder(release.id, sixty_thumb_packshot, 'jpg')}"
        end

        img.thumbnail(200) do |thumb|
          thumb.save(determine_folder(release.id, twohundred_thumb_packshot, 'jpg'))
    symlink = File.symlink?(determine_folder(release.id, twohundred_thumb_sym, 'jpg'))
    if symlink == true
      File.delete(determine_folder(release.id, twohundred_thumb_sym, 'jpg'))
      File.symlink("#{determine_folder(release.id, twohundred_thumb_packshot, 'jpg')}", "#{determine_folder(release.id, twohundred_thumb_sym, 'jpg')}")
      else
      File.symlink("#{determine_folder(release.id, twohundred_thumb_packshot, 'jpg')}", "#{determine_folder(release.id, twohundred_thumb_sym, 'jpg')}")
    end
    #print "#{determine_folder(release.id, twohundred_thumb_packshot, 'jpg')}"
        end

      end
      FileUtils.cp("#{packshot}", "#{determine_folder(release.id, source_packshot, 'jpg')}")
      else
    end          

    release_artist = ReleaseArtist.find(:first,
      :conditions => {:release_id => release.id,
        :artist_id => albumartist.id,
          :artist_type_id => artist_type.id
      }
    )      

    release_artist = ReleaseArtist.create(:release_id => release.id,
      :artist_id => albumartist.id,
        :artist_type_id => artist_type.id) unless release_artist

    release_track = ReleaseTrack.find(:first, 
      :conditions => {:release_id => release.id,
        :track_id => track.id,
          :sequence => tagged_file["tracknumber"]
        }
    )

    release_track = ReleaseTrack.create(:track_id => track.id, 
      :release_id => release.id, 
        :sequence => tagged_file["tracknumber"]) unless release_track

    label = tagged_file["label"]
    unless label.nil?
    label = Label.find(:first,
      :conditions => {:name => tagged_file["label"]
      }
    )
    label = Label.create(:name => tagged_file["label"]) unless label

    release_date = tagged_file["date"]
    release_date += '-01-01' if release_date && (release_date.length == 4)
    release_date += '-01' if release_date && (release_date.length == 7)
    release_event = ReleaseEvent.find(:first,
      :conditions => {:release_id => release.id, 
        :label_id => label.id, 
          :release_date => release_date#,
            #:cat_num => tagged_file["catalognumber"],
              #:barcode => tagged_file["barcode"] ## commented out until I can devise a smarter way of creating/updating release events
      }
    )
    release_event = ReleaseEvent.create(:release_id => release.id, 
      :label_id => label.id, 
        :release_date => release_date#,
          #:cat_num => tagged_file["catalognumber"],
            #:barcode => tagged_file["barcode"] ## commented out until I can devise a smarter way of creating/updating release events
            ) unless release_event

    end # labels

    genre = tagged_file["genre"]
    unless genre.nil?
    genre.split(/\s*,\s*/).each do |genrename| 

    genre = Genre.find(:first,
      :conditions => {:name => genrename}
    )
    genre = Genre.create(:name => genrename) unless genre  

        release_genre = ReleaseGenre.find(:first, 
          :conditions => {:release_id => release.id,
            :genre_id => genre.id
          }
        )
        release_genre = ReleaseGenre.create(:genre_id => genre.id, 
          :release_id => release.id) unless release_genre

        track_genre = TrackGenre.find(:first,
          :conditions => {:track_id => track.id,
            :genre_id => genre.id
          }
        )      
        track_genre = TrackGenre.create(:genre_id => genre.id,
          :track_id => track.id) unless track_genre   

          end # releases
        end # genre if
      end # genre do
#=begin // uncomment to only import data and packshots
    oggenc = '/usr/bin/oggenc'
    oggargs = [
      '-q3' # we could go to -q(uality)4
    ]

    system("#{oggenc} #{oggargs.join} \"#{path_to_file}\" -o \"#{determine_folder(track.id, ogg_audio, 'ogg')}\"")

    symlink = File.symlink?(determine_folder(track.id, ogg_sym, 'ogg'))
      if symlink == true
        File.delete("#{determine_folder(track.id, ogg_sym, 'ogg')}")
        File.symlink("#{determine_folder(track.id, ogg_audio, 'ogg')}", "#{determine_folder(track.id, ogg_sym, 'ogg')}")
        else
        File.symlink("#{determine_folder(track.id, ogg_audio, 'ogg')}", "#{determine_folder(track.id, ogg_sym, 'ogg')}")
      end

    faac = '/usr/bin/faac'
    flac = '/usr/bin/flac'
    faacargs = [
      '-q 100' 
    ]

    flacargs = [
      '--decode', # required to decode
      '--stdout'
    ]
    track_id_to_string = track.id.to_s
    system("#{flac} #{flacargs.join(" ")} \"#{path_to_file}\" | #{faac} #{faacargs.join} -o \"#{determine_folder(track.id, m4a_audio, 'm4a')}\" -")

    symlink = File.symlink?("#{determine_folder(track.id, m4a_sym, 'm4a')}")
      if symlink == true
      File.delete("#{determine_folder(track.id, m4a_sym, 'm4a')}")
      File.symlink("#{determine_folder(track.id, m4a_audio, 'm4a')}", "#{determine_folder(track.id, m4a_sym, 'm4a')}")
      else
      File.symlink("#{determine_folder(track.id, m4a_audio, 'm4a')}", "#{determine_folder(track.id, m4a_sym, 'm4a')}")
    end

#=end // uncomment to only import data and packshots
    end # dir.glob
    Artist.rebuild_index #currently crashing things. Annoying.
    Track.rebuild_index
    Label.rebuild_index
    Genre.rebuild_index
    Release.rebuild_index
    User.rebuild_index
    redirect_to(user_path(session[:user_id])) 
  end # index

end # class