Module: Paperclip::Storage::Youtube

Defined in:
lib/paperclip/storage/youtube.rb

Overview

Youtube video hosting, easy place to share videos for You can find at www.youtube.com/ There are a few S3-specific options for has_attached_file:

  • youtube_credentials: Takes a path, a File, or a Hash. The path (or File) must point to a YAML file containing the login_name and login_password and youttube_username

and developer_key that you can got it from your account on Youtube.

You can 'environment-space' this just like you do to your
database.yml file, so different environments can use different accounts:
  development:
    login_name: dr-click...
    login_password: 123...
  production:
    login_name: dr-click...
    login_password: 123...

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



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
# File 'lib/paperclip/storage/youtube.rb', line 27

def self.extended base
  begin
    require 'net/http'
  rescue LoadError => e
    log("(Error) #{e.message}")
    e.message << " (Can't find required library 'net/http')"
    raise e
  end
  begin
    require 'net/https'
  rescue LoadError => e
    log("(Error) #{e.message}")
    e.message << " (Can't find required library 'net/https')"
    raise e
  end
  begin
    require 'mime/types'
  rescue LoadError => e
    log("(Error) #{e.message}")
    e.message << " (You may need to install the mime-types gem)"
    raise e
  end
  begin
    require 'builder'
  rescue LoadError => e
    log("(Error) #{e.message}")
    e.message << " (You may need to install the builder gem)"
    raise e
  end
  begin
    require 'rexml/document'
  rescue LoadError => e
    log("(Error) #{e.message}")
    e.message << " (Can't find required library 'rexml/document')"
    raise e
  end
  
  base.instance_eval do
    @youtube_options = @options[:youtube_options] || {}
    
    @developer_key = @options[:developer_key] || @youtube_options[:developer_key]
    @login_name = @options[:login_name] || @youtube_options[:login_name]
    @login_password = @options[:login_password] || @youtube_options[:login_password]
    @youttube_username = @options[:youttube_username] || @youtube_options[:youttube_username]
    
    @auth_host = @options[:auth_host] || @youtube_options[:auth_host] || 'www.google.com'
    @auth_path = @options[:auth_path] || @youtube_options[:auth_path] || '/youtube/accounts/ClientLogin'
    
    @upload_host = @options[:upload_host] || @youtube_options[:upload_host] || 'uploads.gdata.youtube.com'
    @upload_path = @options[:upload_path] || @youtube_options[:upload_path] || "/feeds/api/users/#{@youttube_username}/uploads"
    
    @data_host = @options[:data_host] || @youtube_options[:data_host] || 'gdata.youtube.com'
  end
  
  Paperclip.interpolates(:youtube_url) do |attachment, style|
      style = :thumbnail_1 if style == :thumbnail
      if style == :original
        'http://www.youtube.com/watch?v=:youtube_id'
      else
        "http://i.ytimg.com/vi/:youtube_id/#{style.to_s.split('_').last.to_i}.jpg" 
      end
  end
end

Instance Method Details

#auth_hostObject



103
104
105
# File 'lib/paperclip/storage/youtube.rb', line 103

def auth_host
  @auth_host
end

#auth_pathObject



106
107
108
# File 'lib/paperclip/storage/youtube.rb', line 106

def auth_path
  @auth_path
end

#authorization_headersObject



213
214
215
216
217
218
219
# File 'lib/paperclip/storage/youtube.rb', line 213

def authorization_headers
  {
    "Authorization"  => "GoogleLogin auth=#{token}",
    "X-GData-Client" => "#{youttube_username}",
    "X-GData-Key"    => "key=#{developer_key}"
  }
end

#boundaryObject



181
182
183
# File 'lib/paperclip/storage/youtube.rb', line 181

def boundary 
  "An43094fu"
end

#data_hostObject



115
116
117
# File 'lib/paperclip/storage/youtube.rb', line 115

def data_host
  @data_host
end

#developer_keyObject



97
98
99
# File 'lib/paperclip/storage/youtube.rb', line 97

def developer_key
  @developer_key
end

#exists?(style_name = default_style) ⇒ Boolean

Returns:

  • (Boolean)


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/paperclip/storage/youtube.rb', line 158

def exists?(style_name = default_style)
  http = Net::HTTP.new(data_host)
  headers = {
    'Content-Type' => 'application/atom+xml',
    'Authorization' => "GoogleLogin auth=#{token}",
    'GData-Version' => '2',
    'X-GData-Key' => "key=#{developer_key}"
  }
  
  resp= http.get(upload_path+"/#{self.instance.youtube_id}", headers)
  if resp.code == "200"
    return true
  elsif
    log("(Error) Couldn't find the video '#{self.instance.youtube_id}'")
    return false
  end
end

#flush_deletesObject

:nodoc:



265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/paperclip/storage/youtube.rb', line 265

def flush_deletes #:nodoc:
  @queued_for_delete.each do |path|
    begin
      log("deleting from youtube : #{self.instance.youtube_id}")
      youtube_delete
    rescue => e
      log("(Error) #{e.message}")
      raise e.message
    end
  end
  @queued_for_delete = []
end

#flush_writesObject

:nodoc:



252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/paperclip/storage/youtube.rb', line 252

def flush_writes #:nodoc:
  @queued_for_write.each do |style, file|
    begin
      log("Uploading to youtube : #{self.instance.media_file_name}")
      youtube_upload(File.open(file.path), self.instance.media_file_name)
    rescue => e
      log("(Error) #{e.message} - #{e.backtrace.inspect}")
      raise e.message
    end
  end
  @queued_for_write = {}
end

#login_nameObject



91
92
93
# File 'lib/paperclip/storage/youtube.rb', line 91

def 
  @login_name
end

#login_passwordObject



94
95
96
# File 'lib/paperclip/storage/youtube.rb', line 94

def 
  @login_password
end

#request_io(data, opts) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/paperclip/storage/youtube.rb', line 199

def request_io(data, opts)
  post_body = [
    "--#{boundary}\r\n",
    "Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n",
    request_xml(opts),
    "\r\n--#{boundary}\r\n",
    "Content-Type: #{opts[:mime_type]}\r\nContent-Transfer-Encoding: binary\r\n\r\n",
    data,
    "\r\n--#{boundary}--\r\n",
  ]
  
  YoutubeChain.new(post_body)
end

#request_xml(opts) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/paperclip/storage/youtube.rb', line 185

def request_xml(opts)
  b = Builder::XmlMarkup.new
  b.instruct!
  b.entry(:xmlns => "http://www.w3.org/2005/Atom", 'xmlns:media' => "http://search.yahoo.com/mrss/", 'xmlns:yt' => "http://gdata.youtube.com/schemas/2007") do | m |
    m.tag!("media:group") do | mg |
      mg.tag!("media:title", opts[:title], :type => "plain")
      mg.tag!("media:description", opts[:description], :type => "plain")
      mg.tag!("media:keywords", opts[:keywords].join(","))
      mg.tag!('media:category', opts[:category], :scheme => "http://gdata.youtube.com/schemas/2007/categories.cat")
      mg.tag!('yt:private') if opts[:private]
    end
  end.to_s
end

#to_file(style_name = default_style) ⇒ Object

Returns representation of the data of the file assigned to the given style, in the format most representative of the current storage.



178
179
# File 'lib/paperclip/storage/youtube.rb', line 178

def to_file style_name = default_style
end

#tokenObject



118
119
120
121
122
123
124
125
126
127
# File 'lib/paperclip/storage/youtube.rb', line 118

def token
  @token ||= begin
    http = Net::HTTP.new("www.google.com", 443)
    http.use_ssl = true
    body = "Email=#{YoutubeChain.esc }&Passwd=#{YoutubeChain.esc }&service=youtube&source=#{YoutubeChain.esc youttube_username}"
    response = http.post("/youtube/accounts/ClientLogin", body, "Content-Type" => "application/x-www-form-urlencoded")
    raise response.body[/Error=(.+)/,1] if response.code.to_i != 200
    @token = response.body[/Auth=(.+)/, 1]
  end
end

#update_youtube_id(data) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/paperclip/storage/youtube.rb', line 129

def update_youtube_id(data)
  doc = REXML::Document.new data
  id = doc.root.elements["id"].text.split("/").last if doc && doc.root
  
  if id
    video = Video.find self.instance.id
    video.update_attribute(:youtube_id, id)
  else
    log("(Error) Video has no id, please reupload to Youtube.")
    raise "Video has no id, please reupload to Youtube."
  end
end

#upload_hostObject



109
110
111
# File 'lib/paperclip/storage/youtube.rb', line 109

def upload_host
  @upload_host
end

#upload_pathObject



112
113
114
# File 'lib/paperclip/storage/youtube.rb', line 112

def upload_path
  @upload_path
end

#youttube_usernameObject



100
101
102
# File 'lib/paperclip/storage/youtube.rb', line 100

def youttube_username
  @youttube_username
end

#youtube_deleteObject



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/paperclip/storage/youtube.rb', line 142

def youtube_delete
  http = Net::HTTP.new(data_host)
  headers = {
    'Content-Type' => 'application/atom+xml',
    'Authorization' => "GoogleLogin auth=#{token}",
    'GData-Version' => '2',
    'X-GData-Key' => "key=#{developer_key}"
  }
  
  resp = http.delete(upload_path+"/#{self.instance.youtube_id}", headers)
  if resp.code != "200"
    log("(Error) Couldn't delete the video from Youtube")
    raise "Couldn't delete the video from Youtube"
  end
end

#youtube_upload(data, video_file) ⇒ Object



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
# File 'lib/paperclip/storage/youtube.rb', line 221

def youtube_upload(data, video_file)
  opts = { :mime_type => MIME::Types.type_for(video_file).join(),
            :title => self.instance.respond_to?(:title) && !self.instance.title.blank? ? self.instance.title :  video_file,
            :description => self.instance.respond_to?(:description) && !self.instance.description.blank? ? self.instance.description :  video_file,
            :category => 'People',
            :keywords => [],
            :filename => video_file}
  
  post_body_io = request_io(data, opts)
  upload_headers = authorization_headers.merge({
      "Slug"           => "#{opts[:filename]}",
      "Content-Type"   => "multipart/related; boundary=#{boundary}",
      "Content-Length" => "#{post_body_io.expected_length}"
  })
  
  path = upload_path
  
  Net::HTTP.start(upload_host) do | session |
    post = Net::HTTP::Post.new(path, upload_headers)
    post.body_stream = post_body_io
    response = session.request(post)
    
    if response.code == "201"
      update_youtube_id response.body
    else
      log("(Error) Couldn't upload the video to Youtube >> #{response.body}")
      raise "Couldn't upload the video to Youtube >> #{response.body}"
    end
  end
end