Class: Squarepusher::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/squarepusher/core.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, secret, token, token_secret, args = {}) ⇒ Client

optional items for args: :overwrite - overwrite local files :verbose - verbose logging :privacy - privacy level for requests :event_listener - listener object that must provide “event” method



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
# File 'lib/squarepusher/core.rb', line 123

def initialize(key, secret, token, token_secret, args={})
  @overwrite = args[:overwrite] || false
  @verbose = args[:verbose] || false
  @privacy = args[:privacy] || 5

  @event_listener = args[:event_listener] || nil

  if not @event_listener.nil?
    if not @event_listener.respond_to?(:event)
      puts "ignoring event listener #{@event_listener}; does not provide :event method"
      @event_listener = nil
    else
      puts "using event listener #{@event_listener}"
    end
  end
  
  FlickRawOptions['timeout'] = args[:timeout] || 5
  
  require 'flickraw'
  
  FlickRaw.api_key = key
  FlickRaw.shared_secret = secret
  
  # flickr.auth.checkToken(:auth_token => token)
  flickr.access_token = token
  flickr.access_secret = token_secret
  
  @size = args[:size] || :small_square
end

Class Method Details

.from_config_path(path, args = {}) ⇒ Object



82
83
84
85
86
# File 'lib/squarepusher/core.rb', line 82

def from_config_path(path, args={})
  open(path) do |stream|
    from_config_stream(stream, args)
  end
end

.from_config_stream(stream, args = {}) ⇒ Object



88
89
90
91
# File 'lib/squarepusher/core.rb', line 88

def from_config_stream(stream, args={})
  key, secret, token, token_secret = parse_config_stream(stream)
  Squarepusher::Client.new(key, secret, token, token_secret, args)
end

.parse_config_stream(stream) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/squarepusher/core.rb', line 93

def parse_config_stream(stream)
  parsed = YAML.load(stream)
  if not parsed.respond_to?(:has_key?)
    raise Exception.new("invalid YAML in #{path}; parsed #{parsed.inspect}")
  end
  puts "parsed config: #{parsed.inspect}"
  required_keys = ['key', 'secret', 'token', 'token_secret']
  missing_keys = []
  vals = []
  required_keys.each do |k|
    v = parsed.fetch(k, nil)
    if not v.nil?
      vals << v
    else
      missing_keys << k 
    end
  end
  if not missing_keys.empty?
    raise Exception.new("missing keys in #{path}: #{missing_keys.inspect}")
  end
  vals
end

Instance Method Details

#download_favorites(output_dir, page = 1, &photo_call) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/squarepusher/core.rb', line 219

def download_favorites(output_dir, page=1, &photo_call)
  puts "page: #{page}"
  count = 0
  flickr.favorites.getList(:page => page, :extras => 'owner_name, original_format').each do |p|
    ext = if p.respond_to?(:original_format) then p.originalformat else "jpg" end
    path = "#{output_dir}/#{p.owner}-#{p.id}.#{ext}"
    count += 1
    next if not @overwrite and File.exists?(path)
    u = Squarepusher.url_for(p, :medium_640)
    download_image(u, path)
    if block_given? then photo_call.call(p, u, path) end
  end
  puts "count: #{count}"
  if count == 100 then download_favorites(output_dir, page+1, &photo_call) end
end

#download_photoset(photoset, output_dir, args = {}) ⇒ Object



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
# File 'lib/squarepusher/core.rb', line 235

def download_photoset(photoset, output_dir, args={})
  size = args[:size] || @size

  pset_normalized_title = Squarepusher.normalize(photoset.title)
  dirname = pset_normalized_title
  set_dir = File.join(output_dir, dirname)
  $fileutils.mkdir_p set_dir
  
  # contains the following keys
  # error
  # exists      
  results = {}
  local_paths = []
  results[:local_photoset_dir] = set_dir
  results[:local_paths] = local_paths

  # handles socket timeout when loading photoset info
  status, photoset_result = handle_error { flickr.photosets.getPhotos(:photoset_id => photoset.id,
    :privacy_filter => @privacy,
    :extras => "original_format,url_o,date_taken")["photo"] }
  if status == :error
    error photoset_result
    results[status] = 1
    return results
  else
    photos = photoset_result
  end
  
  photos.each do |p|
    # removes all non digits from date
    date_taken = p["datetaken"].gsub(/[^\d]+/, '')

    name = "#{date_taken}-#{p.id}-#{pset_normalized_title}"
    if not p.title.empty?
      normalized_title = Squarepusher.normalize(p.title)
      name << "-#{normalized_title}"
    end
    
    url = Squarepusher.url_for(p, size)
    
    # TODO: only add .jpg suffix if it's not in the image name already
    path = File.join(set_dir, name)
    path << ".jpg" if not path =~ /.jpg$/
    
    if not @overwrite and File.exists?(path)
      debug "#{path} exists; skipping"
      result = :exists
    else
      result = download_image(url, path)
    end
    
    if results.has_key?(result)
      results[result] = results[result] + 1
    else
      results[result] = 1
    end

    if result == :success || result == :exists
      local_paths << path
    end
  end
  results
end

#each_photosetObject



166
167
168
169
170
# File 'lib/squarepusher/core.rb', line 166

def each_photoset
  flickr.photosets.getList.each do |pset|
    yield pset
  end
end

#get_photo(photo_id) ⇒ Object



153
154
155
# File 'lib/squarepusher/core.rb', line 153

def get_photo(photo_id)
  flickr.photos.getInfo(:photo_id => photo_id)
end

#get_photos_for_set(pset_id, params = {}) ⇒ Object



161
162
163
164
# File 'lib/squarepusher/core.rb', line 161

def get_photos_for_set(pset_id, params = {})
  params[:photoset_id] = pset_id
  flickr.photosets.getPhotos(params)
end

#get_photoset(pset_id) ⇒ Object



157
158
159
# File 'lib/squarepusher/core.rb', line 157

def get_photoset(pset_id)
  flickr.photosets.getInfo(:photoset_id => pset_id)
end

#random_contactObject



178
179
180
181
182
183
184
# File 'lib/squarepusher/core.rb', line 178

def random_contact
  contact_hash = flickr.contacts.getList().to_hash()
  pages = contact_hash["pages"].to_i
  puts "WARNING - #{pages} pages of contacts found - only using first one" if pages > 1
  contacts = contact_hash["contact"]
  contacts[rand(contacts.size)]
end

#random_favorite_of_contact(contact_id, args = {}) ⇒ Object

Raises:

  • (Exception)


202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/squarepusher/core.rb', line 202

def random_favorite_of_contact(contact_id, args={})
  args[:user_id] = contact_id
  faves = flickr.favorites.getPublicList(args)
  raise Exception.new("no favorites found") if faves.size == 0

  faves_hash = faves.to_hash
  # puts "hash: #{faves_hash.inspect}"
  photos = faves_hash["photo"]
  pages = faves_hash["pages"]

  fire_event(:domain => :flickr, :user => contact_id, :favorite_page_count => pages)

  choice = photos[rand(photos.size)]

  choice
end

#random_favorite_of_mine(args = {}) ⇒ Object

Raises:

  • (Exception)


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/squarepusher/core.rb', line 186

def random_favorite_of_mine(args={})
  faves = flickr.favorites.getList(args)
  raise Exception.new("no favorites found") if faves.size == 0

  faves_hash = faves.to_hash
  # puts "hash: #{faves_hash.inspect}"
  photos = faves_hash["photo"]
  pages = faves_hash["pages"]

  fire_event(:domain => :flickr, :user => :self, :favorite_page_count => pages)

  choice = photos[rand(photos.size)]

  choice
end

#search_by_tags(user_id, tags, args = {}) ⇒ Object



172
173
174
175
176
# File 'lib/squarepusher/core.rb', line 172

def search_by_tags(user_id, tags, args={})
  args[:user_id] = user_id
  args[:tags] = tags
  return flickr.photos.search(args)
end

#sync_photoset(photoset, output_dir, args = {}) ⇒ Object

syncs local directory with flickr photoset meaning, if a file exists locally that is no longer in the set, it will be deleted



301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/squarepusher/core.rb', line 301

def sync_photoset(photoset, output_dir, args={})
  results = download_photoset(photoset, output_dir, args)
  local_pset_dir = results[:local_photoset_dir]

  # converts list to set for faster lookups
  local_paths = Set.new(results[:local_paths])

  Dir.entries(local_pset_dir).collect { |e| "#{local_pset_dir}/#{e}"}.select { |e| File.file?(e) }.each do |e|
    if not local_paths.include?(e)
      # puts "deleting #{e}"
      $fileutils.rm e
    end
  end
end