mdarby-scribd_fu 1.2.3.2 → 2.0

Sign up to get free protection for your applications and to get access to all the features.
data/init.rb CHANGED
@@ -1 +1 @@
1
- require File.dirname(__FILE__) + "/rails/init"
1
+ require File.join(File.dirname(__FILE__), "lib", "scribd_fu")
data/lib/scribd_fu.rb CHANGED
@@ -1,108 +1,250 @@
1
- require 'attachment_fu/methods'
2
- require 'paperclip/methods'
3
-
4
1
  module ScribdFu
5
- # A list of content types supported by scribd.
6
- CONTENT_TYPES = ['application/pdf', 'image/jpeg', 'image/pjpeg',
7
- 'image/gif', 'image/png', 'image/x-png', 'image/jpg',
8
- 'application/msword', 'application/mspowerpoint',
9
- 'application/vnd.ms-powerpoint', 'application/excel',
10
- 'application/vnd.ms-excel', 'application/postscript',
11
- 'text/plain', 'application/rtf',
12
- 'application/vnd.oasis.opendocument.text',
13
- 'application/vnd.oasis.opendocument.presentation',
14
- 'application/vnd.oasis.opendocument.spreadsheet',
15
- 'application/vnd.sun.xml.writer',
16
- 'application/vnd.sun.xml.impress',
17
- 'application/vnd.sun.xml.calc',
18
- # OOXML, AKA `the MIME types from hell'. Seriously, these are long enough to
19
- # start their own dictionary...
2
+
3
+ ConfigPath = "#{RAILS_ROOT}/config/scribd_fu.yml".freeze
4
+
5
+ # A list of content types supported by iPaper.
6
+ ContentTypes = [
7
+ 'application/pdf',
8
+ 'application/msword',
9
+ 'application/mspowerpoint',
10
+ 'application/vnd.ms-powerpoint',
11
+ 'application/excel',
12
+ 'application/vnd.ms-excel',
13
+ 'application/postscript',
14
+ 'text/plain',
15
+ 'application/rtf',
16
+ 'application/vnd.oasis.opendocument.text',
17
+ 'application/vnd.oasis.opendocument.presentation',
18
+ 'application/vnd.oasis.opendocument.spreadsheet',
19
+ 'application/vnd.sun.xml.writer',
20
+ 'application/vnd.sun.xml.impress',
21
+ 'application/vnd.sun.xml.calc',
20
22
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
21
23
  'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
22
24
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
23
25
  'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
24
26
  'application/vnd.openxmlformats-officedocument.presentationml.template',
25
27
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
26
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.template']
28
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'
29
+ ]
30
+
31
+ # Available parameters for the JS API
32
+ # http://www.scribd.com/publisher/api/api?method_name=Javascript+API
33
+ Available_JS_Params = [ :height, :width, :page, :my_user_id, :search_query,
34
+ :jsapi_version, :disable_related_docs, :mode, :auto_size ]
27
35
 
28
- def self.included(base)
29
- base.extend ActsAsScribdDocument
36
+ class ScribdFuError < StandardError #:nodoc:
30
37
  end
31
38
 
32
- module ActsAsScribdDocument
33
- # Synonym for <tt>has_scribdable_attachment(nil)</tt>.
34
- def acts_as_scribd_document
35
- has_scribdable_attachment
39
+ class ScribdFuUploadError < ScribdFuError #:nodoc:
40
+ end
41
+
42
+
43
+ class << self
44
+
45
+ def included(base) #:nodoc:
46
+ base.extend ClassMethods
36
47
  end
37
48
 
38
- # Marks the given +attribute+ as a scribdable document file. If +attribute+
39
- # is nil, assumes this is an Attachment_fu model and deals with the setup
40
- # accordingly; otherwise, assumes a +paperclip+ model and sets up scribding
41
- # related to the particular given attribute.
42
- def has_scribdable_attachment(attribute = nil)
43
- class_eval do
44
- include ScribdFu::InstanceMethods
49
+ # Login, store, and return a handle to the Scribd user account
50
+ def scribd_user
51
+ begin
52
+ # Ensure we can login to Scribd, and get a handle on the account
53
+ Scribd::API.instance.key = config[:key]
54
+ Scribd::API.instance.secret = config[:secret]
55
+ @scribd_user = Scribd::User.login(config[:user], config[:password])
56
+ rescue
57
+ raise ScribdFuError, "Your Scribd credentials are incorrect"
58
+ end
59
+ end
45
60
 
46
- if attribute.nil?
47
- include ScribdFu::AttachmentFu::InstanceMethods
48
- else
49
- include ScribdFu::Paperclip::InstanceMethods # ignored if already done
61
+ # Upload a file to Scribd
62
+ def upload(obj, file_path)
63
+ begin
64
+ res = scribd_user.upload(:file => "#{file_path}", :access => access_level)
65
+ obj.update_attributes({:ipaper_id => res.doc_id, :ipaper_access_key => res.access_key})
66
+ rescue
67
+ raise ScribdFuUploadError, "Sorry, but #{obj.class} ##{obj.id} could not be uploaded to Scribd"
68
+ end
69
+ end
50
70
 
51
- add_scribd_attribute attribute # class method added by above include
52
- end
71
+ # Delete an iPaper document
72
+ def destroy(document)
73
+ document.destroy
74
+ end
75
+
76
+ # Read, store, and return the ScribdFu config file's contents
77
+ def config
78
+ raise ScribdFuError, "#{ConfigPath} does not exist" unless File.file?(ConfigPath)
79
+
80
+ # Load the config file and strip any whitespace from the values
81
+ @config ||= YAML.load_file(ConfigPath).each_pair{|k,v| {k=>v.to_s.strip}}.symbolize_keys!
82
+ end
83
+
84
+ # Get the preferred access level for iPaper documents
85
+ def access_level
86
+ config[:access] || 'private'
87
+ end
88
+
89
+ # Load, store, and return the associated iPaper document
90
+ def load_ipaper_document(id)
91
+ begin
92
+ @document ||= scribd_user.find_document(id)
93
+ rescue
94
+ raise ScribdFuError, "Scribd Document ##{id} not found!"
53
95
  end
54
96
  end
97
+
55
98
  end
56
99
 
57
- module InstanceMethods
58
- # Sets up Scribd configuration info when this module is included.
59
- def self.included(base)
60
- base.extend ClassMethods
100
+ module ClassMethods
61
101
 
62
- mattr_reader :scribd_config, :scribd_login
102
+ # Load and inject ScribdFu goodies
103
+ def has_ipaper_and_uses(str)
104
+ check_environment
105
+ load_base_plugin(str)
63
106
 
64
- begin
65
- require 'rscribd'
66
- rescue LoadError
67
- raise RequiredLibraryNotFoundError.new('rscribd could not be loaded')
107
+ include InstanceMethods
108
+
109
+ after_save :upload_to_scribd # This *MUST* be an after_save
110
+ before_destroy :destroy_ipaper_document
111
+ end
112
+
113
+ private
114
+
115
+ # Configure ScribdFu for this particular environment
116
+ def check_environment
117
+ load_rscribd
118
+ check_config
119
+ check_fields
68
120
  end
69
121
 
70
- begin
71
- unless @@scribd_login
72
- @@scribd_config = YAML.load_file("#{RAILS_ROOT}/config/scribd.yml").symbolize_keys
73
- @@scribd_config = @@scribd_config[:scribd]
122
+ def check_config
123
+ ScribdFu::config
124
+ end
74
125
 
75
- # Ensure we can connect to the Service
76
- Scribd::API.instance.key = @@scribd_config['key'].to_s.strip
77
- Scribd::API.instance.secret = @@scribd_config['secret'].to_s.strip
126
+ # Load the rscribd gem
127
+ def load_rscribd
128
+ begin
129
+ require 'rscribd'
130
+ rescue LoadError
131
+ raise ScribdFuError, 'Please install the rscribd gem'
132
+ end
133
+ end
78
134
 
79
- @@scribd_login = Scribd::User.login @@scribd_config['user'].to_s.strip, @@scribd_config['password'].to_s.strip
135
+ # Load Attachment_Fu specific methods and files
136
+ def load_attachment_fu
137
+ require 'scribd_fu/attachment_fu'
138
+ include ScribdFu::AttachmentFu::InstanceMethods
139
+ end
140
+
141
+ # Load Paperclip specific methods and files
142
+ def load_paperclip
143
+ require 'scribd_fu/paperclip'
144
+ include ScribdFu::Paperclip::InstanceMethods
145
+ end
146
+
147
+ # Ensure ScribdFu-centric attributes exist
148
+ def check_fields
149
+ fields = %w{ipaper_id ipaper_access_key}.inject([]){|stack, f| stack << "#{name}##{f}" unless column_names.include?(f); stack}
150
+ raise ScribdFuError, "These fields are missing: #{fields.to_sentence}" if fields.size > 0
151
+ end
152
+
153
+ # Load either AttachmentFu or Paperclip-specific methods
154
+ def load_base_plugin(str)
155
+ if str == 'AttachmentFu'
156
+ load_attachment_fu
157
+ elsif str == 'Paperclip'
158
+ load_paperclip
159
+ else
160
+ raise ScribdFuError, "Sorry, only Attachment_fu and Paperclip are supported."
80
161
  end
81
- rescue
82
- raise "config/scribd.yml file not found, or your credentials are incorrect."
83
162
  end
163
+
164
+ end
165
+
166
+ module InstanceMethods
167
+
168
+ def self.included(base)
169
+ base.extend ClassMethods
84
170
  end
85
171
 
86
- def access_level
87
- if self.respond_to?(:is_public) && self.is_public != nil
88
- scribd_access = self.is_public ? 'public' : 'private'
89
- else
90
- scribd_access = scribd_config['access']
91
- end
172
+ # Upload the associated file to Scribd for iPaper conversion
173
+ # This is called +after_save+ and cannot be called earlier,
174
+ # so don't get any ideas.
175
+ def upload_to_scribd
176
+ ScribdFu::upload(self, file_path) if scribdable?
177
+ end
92
178
 
93
- scribd_access
179
+ # Checks whether the associated file is convertable to iPaper
180
+ def scribdable?
181
+ ContentTypes.include?(get_content_type) && ipaper_id.blank?
94
182
  end
95
- end
96
183
 
97
- module ClassMethods
98
- # Sets up the scribd_options accessor, a before_destroy hook to ensure the
99
- # deletion of associated Scribd documents, and an after_save hook to upload
100
- # to scribd.
101
- def self.extended(base)
102
- base.class_inheritable_accessor :scribd_options
184
+ # Responds true if the conversion is converting
185
+ def conversion_processing?
186
+ !(conversion_complete? || conversion_successful? || conversion_error?)
187
+ end
103
188
 
104
- base.before_destroy :destroy_scribd_documents
105
- base.before_validation :upload_to_scribd
189
+ # Responds true if the conversion is complete -- note that this gives no
190
+ # indication as to whether the conversion had an error or was succesful,
191
+ # just that the conversion completed.
192
+ def conversion_complete?
193
+ ipaper_document && ipaper_document.conversion_status != 'PROCESSING'
106
194
  end
195
+
196
+ # Responds true if the document has been converted.
197
+ def conversion_successful?
198
+ ipaper_document && ipaper_document.conversion_status =~ /^DISPLAYABLE|DONE$/
199
+ end
200
+
201
+ # Responds true if there was a conversion error while converting to iPaper.
202
+ def conversion_error?
203
+ ipaper_document && ipaper_document.conversion_status == 'ERROR'
204
+ end
205
+
206
+ # Responds the Scribd::Document associated with this model, or nil if it does not exist.
207
+ def ipaper_document
208
+ @document ||= ScribdFu::load_ipaper_document(ipaper_id)
209
+ end
210
+
211
+ # Destroys the scribd document for this record. This is called +before_destroy+
212
+ def destroy_ipaper_document
213
+ ScribdFu::destroy(ipaper_document) if ipaper_document
214
+ end
215
+
216
+ # Display the iPaper document in a view
217
+ def display_ipaper(options = {})
218
+ alt = options.has_key?(:alt) ? options[:alt] : ""
219
+
220
+ <<-END
221
+ <script type="text/javascript" src="http://www.scribd.com/javascripts/view.js"></script>
222
+ <div id="embedded_flash">#{alt}</div>
223
+ <script type="text/javascript">
224
+ var scribd_doc = scribd.Document.getDoc(#{ipaper_id}, '#{ipaper_access_key}');
225
+ #{js_params(options)}
226
+ scribd_doc.write("embedded_flash");
227
+ </script>
228
+ END
229
+ end
230
+
231
+
232
+ private
233
+
234
+ # Check and collect any Javascript params that might have been passed in
235
+ def js_params(options)
236
+ opt = []
237
+
238
+ options.each_pair do |k, v|
239
+ opt << "scribd_doc.addParam('#{k}', '#{v}');" if Available_JS_Params.include?(k)
240
+ end
241
+
242
+ opt.compact.join("\n")
243
+ end
244
+
107
245
  end
246
+
108
247
  end
248
+
249
+ # Let's do this.
250
+ ActiveRecord::Base.send(:include, ScribdFu) if Object.const_defined?("ActiveRecord")
data/scribd_fu.gemspec CHANGED
@@ -1,7 +1,7 @@
1
1
  Gem::Specification.new do |s|
2
2
  s.name = "scribd_fu"
3
- s.version = "1.2.3.2"
4
- s.date = "2009-03-18"
3
+ s.version = "2.0"
4
+ s.date = "2009-03-29"
5
5
  s.summary = "Quick and easy interactions with Scribd's iPaper service"
6
6
  s.email = "matt@matt-darby.com"
7
7
  s.homepage = "http://github.com/mdarby/scribd_fu/tree/master"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mdarby-scribd_fu
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.3.2
4
+ version: "2.0"
5
5
  platform: ruby
6
6
  authors:
7
7
  - Matt Darby
@@ -9,7 +9,7 @@ autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
11
 
12
- date: 2009-03-18 00:00:00 -07:00
12
+ date: 2009-03-29 00:00:00 -07:00
13
13
  default_executable:
14
14
  dependencies:
15
15
  - !ruby/object:Gem::Dependency
data/README DELETED
@@ -1 +0,0 @@
1
- README.textile
data/Rakefile DELETED
@@ -1,22 +0,0 @@
1
- require 'rake'
2
- require 'rake/testtask'
3
- require 'rake/rdoctask'
4
-
5
- desc 'Default: run unit tests.'
6
- task :default => :test
7
-
8
- desc 'Test the Scribd_fu plugin.'
9
- Rake::TestTask.new(:test) do |t|
10
- t.libs << 'lib'
11
- t.pattern = 'test/**/*_test.rb'
12
- t.verbose = true
13
- end
14
-
15
- desc 'Generate documentation for the Scribd_fu plugin.'
16
- Rake::RDocTask.new(:rdoc) do |rdoc|
17
- rdoc.rdoc_dir = 'rdoc'
18
- rdoc.title = 'Scribd_fu'
19
- rdoc.options << '--line-numbers' << '--inline-source'
20
- rdoc.rdoc_files.include('README')
21
- rdoc.rdoc_files.include('lib/**/*.rb')
22
- end
@@ -1,7 +0,0 @@
1
- class ScribdConfigGenerator < Rails::Generator::Base
2
- def manifest
3
- record do |m|
4
- m.file 'scribd.yml', 'config/scribd.yml', :collision => :skip
5
- end
6
- end
7
- end
@@ -1,9 +0,0 @@
1
- #Scribd Account Info
2
-
3
- scribd:
4
- key:
5
- secret:
6
- user:
7
- password:
8
- access:
9
- #storage: s3 # Uncomment if Attachment_fu is using Amazon S3 for storage
data/install.rb DELETED
@@ -1 +0,0 @@
1
- # Install hook code here
@@ -1,163 +0,0 @@
1
- require 'ftools'
2
-
3
- module ScribdFu
4
- module AttachmentFu
5
- module ClassMethods
6
- # Adds validations to the current model to check that its attachment is
7
- # scribdable.
8
- def validates_as_scribd_document
9
- validates_presence_of :scribd_id, :scribd_access_key, :content_type
10
- validate :scribdable?
11
- end
12
- end
13
-
14
- module InstanceMethods
15
- def self.included(base)
16
- base.extend ClassMethods
17
- end
18
-
19
- # Checks whether the attachment is scribdable. This boils down to a check
20
- # to ensure that the contents of the attachment are of a content type that
21
- # scribd can understand.
22
- def scribdable?
23
- ScribdFu::CONTENT_TYPES.include?(content_type)
24
- end
25
-
26
- def scribd_id=(id)
27
- write_attribute :scribd_id, id.to_s.strip
28
- end
29
-
30
- def scribd_access_key=(key)
31
- write_attribute :scribd_access_key, key.to_s.strip
32
- end
33
-
34
- # Destroys the scribd document for this record. This is called
35
- # +before_destroy+, as set up by ScribdFu::ClassMethods#extended.
36
- #
37
- # Also available as destroy_scribd_document, which makes more sense in
38
- # terms of pluralization for external calls.
39
- def destroy_scribd_documents
40
- unless scribd_document.nil?
41
- if scribd_document.destroy
42
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Removing Object #{id} successful"
43
- else
44
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Removing Object #{id} failed!"
45
- end
46
- end
47
- end
48
- alias_method :destroy_scribd_document, :destroy_scribd_documents
49
-
50
- # Uploads the attachment to scribd for processing.. This is called
51
- # +before_validation+, as set up by ScribdFu::ClassMethods#extended.
52
- def upload_to_scribd
53
- if scribdable? and self.scribd_id.blank?
54
- with_file_path do |file_path|
55
- if resource = scribd_login.upload(:file => "#{file_path}",
56
- :access => access_level)
57
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Object #{id} successfully uploaded for conversion to iPaper."
58
-
59
- self.scribd_id = resource.doc_id
60
- self.scribd_access_key = resource.access_key
61
-
62
- save
63
- else
64
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Object #{id} upload failed!"
65
- end
66
- end
67
- end
68
- end
69
-
70
- # Returns a URL for a thumbnail for this model's attachment.
71
- #
72
- # If Scribd does not provide a thumbnail URL, then Attachment_fu's
73
- # thumbnail is fallen back on by returning the value of
74
- # <tt>public_filename(:thumb)</tt>.
75
- #
76
- # Sample use in a view:
77
- # <%= image_tag(@attachment .thumbnail_url, :alt => @attachment.name) %>
78
- def thumbnail_url
79
- (scribd_document && scribd_document.thumbnail_url) or
80
- public_filename(:thumb)
81
- end
82
-
83
- # Returns the actual image data of a thumbnail for this model's
84
- # attachment.
85
- #
86
- # If Scribd does not have a thumbnail for this file, then Attachment_fu's
87
- # thumbnanil is fallen back on by returning the file at
88
- # <tt>full_filename(:thumb)</tt>.
89
- #
90
- # Sample use in a controller:
91
- # render :inline => @attachment.thumbnail_file,
92
- # :content_type => 'image/jpeg'
93
- def thumbnail_file
94
- path = (scribd_document && scribd_document.thumbnail_url) ||
95
- full_filename(:thumb)
96
-
97
- open(path).read
98
- rescue Errno::ENOENT
99
- nil
100
- end
101
-
102
- # Yields the correct path to the file, either the local filename or the
103
- # S3 URL.
104
- #
105
- # This method creates a temporary file of the correct filename if
106
- # necessary, so as to be able to give scribd the right filename. The file
107
- # is destroyed when the passed block ends.
108
- def with_file_path(&block) # :yields: full_file_path
109
- # TODO We can probably do this using respond_to?
110
- if scribd_config['storage'].eql?('s3')
111
- yield s3_url
112
- elsif save_attachment? # file hasn't been saved, use the temp file
113
- temp_rename = File.join(Dir.tmpdir, filename)
114
- File.copy(temp_path, temp_rename)
115
-
116
- yield temp_rename
117
- else
118
- yield full_filename
119
- end
120
- ensure
121
- temp_rename && File.unlink(temp_rename) # always delete this
122
- end
123
-
124
- # Responds true if the conversion is complete -- note that this gives no
125
- # indication as to whether the conversion had an error or was succesful,
126
- # just that the conversion completed.
127
- #
128
- # Note that this method still returns false if the model does not refer to a
129
- # valid document. scribd_attributes_valid? should be used to determine the
130
- # validity of the document.
131
- def conversion_complete?
132
- scribd_document && scribd_document.conversion_status != 'PROCESSING'
133
- end
134
-
135
- # Responds true if the document has been converted.
136
- #
137
- # Note that this method still returns false if the model does not refer to a
138
- # valid document. scribd_attributes_valid? should be used to determine the
139
- # validity of the document.
140
- def conversion_successful?
141
- scribd_document && scribd_document.conversion_status =~ /^DISPLAYABLE|DONE$/
142
- end
143
-
144
- # Responds true if there was a conversion error while converting
145
- # to iPaper.
146
- #
147
- # Note that this method still returns false if the model does not refer to a
148
- # valid document. scribd_attributes_valid? should be used to determine the
149
- # validity of the document.
150
- def conversion_error?
151
- scribd_document && scribd_document.conversion_status == 'ERROR'
152
- end
153
-
154
- # Responds the Scribd::Document associated with this model, or nil if it
155
- # does not exist.
156
- def scribd_document
157
- @scribd_document ||= scribd_login.find_document(scribd_id)
158
- rescue Scribd::ResponseError # at minimum, the document was not found
159
- nil
160
- end
161
- end
162
- end
163
- end
@@ -1,231 +0,0 @@
1
- require 'ftools'
2
-
3
- module ScribdFu
4
- module Paperclip
5
- module ClassMethods
6
- # Adds validations to the current model to check that the attachment at
7
- # +attribute+ is scribdable. If +attribute+ is nil, then all attachments
8
- # that have been marked as scribdable are validated.
9
- #
10
- # Note that all calls to has_scribdable_attachment should be made before
11
- # calling validates_attachment_scribdability with a nil parameter;
12
- # otherwise, only those that have been created already will be validated.
13
- def validates_attachment_scribdability(attribute = nil)
14
- attributes = attribute.nil? ? scribd_attributes : [attribute]
15
-
16
- attributes.each do |attribute|
17
- validates_presence_of "#{attribute}_scribd_id",
18
- "#{attribute}_scribd_access_key",
19
- "#{attribute}_content_type"
20
- validates_attachment_content_type attribute,
21
- :content_type => ScribdFu::CONTENT_TYPES
22
- end
23
- end
24
-
25
- # Adds the given +attribute+ to the list of attributes that are uploaded
26
- # to scribd.
27
- #
28
- # Note that a scribd attribute should not be added if it is not a
29
- # Paperclip attachment attribute.
30
- def add_scribd_attribute(attribute)
31
- write_inheritable_attribute :scribd_attributes, [] if scribd_attributes.nil?
32
-
33
- scribd_attributes << attribute
34
-
35
- setup_scribd_attribute(attribute)
36
- end
37
-
38
- def scribd_attributes
39
- read_inheritable_attribute :scribd_attributes
40
- end
41
-
42
- private
43
- # Sets up methods needed for the given +attribute+ to be scribdable.
44
- def setup_scribd_attribute(attribute)
45
- define_method("#{attribute}_scribd_id=") do |id|
46
- write_attribute "#{attribute}_scribd_id", id.to_s.strip
47
- end
48
-
49
- define_method("#{attribute}_scribd_access_key=") do |key|
50
- write_attribute "#{attribute}_scribd_access_key", key.to_s.strip
51
- end
52
- end
53
- end
54
-
55
- module InstanceMethods
56
- def self.included(base)
57
- base.extend ClassMethods
58
- end
59
-
60
- # Checks whether the given attribute is scribdable. This boils down to a
61
- # check to ensure that the contents of the attribute are of a content type
62
- # that scribd can understand.
63
- def scribdable?(attribute)
64
- ScribdFu::CONTENT_TYPES.include?(self["#{attribute}_content_type"])
65
- end
66
-
67
- # Destroys all scribd documents for this record. This is called
68
- # +before_destroy+, as set up by ScribdFu::ClassMethods#extended.
69
- def destroy_scribd_documents
70
- self.class.scribd_attributes.each do |attribute|
71
- document = scribd_document_for(self["#{attribute}_scribd_id"])
72
-
73
- unless document.nil?
74
- if document.destroy
75
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Removing Object #{id}##{attribute} successful"
76
- else
77
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Removing Object #{id}##{attribute} failed!"
78
- end
79
- end
80
- end
81
- end
82
-
83
- # Uploads all scribdable attributes to scribd for processing. This is
84
- # called +before_validation+, as set up by
85
- # ScribdFu::ClassMethods#extended.
86
- def upload_to_scribd
87
- self.class.scribd_attributes.each do |attribute|
88
- scribd_id = self["#{attribute}_scribd_id"]
89
-
90
- if scribdable?(attribute) and scribd_id.blank?
91
- with_file_path_for(attribute) do |filename|
92
- if resource = scribd_login.upload(:file => filename,
93
- :access => access_level)
94
- self.send("#{attribute}_scribd_id=", resource.doc_id)
95
- self.send("#{attribute}_scribd_access_key=", resource.access_key)
96
-
97
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Object " +
98
- "#{id}##{attribute} successfully uploaded " +
99
- "for conversion to iPaper."
100
- else
101
- logger.info "[Scribd_fu] #{Time.now.rfc2822}: Object " +
102
- "#{id}##{attribute} upload failed!"
103
-
104
- false # cancel the save
105
- end
106
- end
107
- end
108
- end
109
- end
110
-
111
- # Returns a URL for a thumbnail for the specified +attribute+ attachment.
112
- #
113
- # If Scribd does not provide a thumbnail URL, then Paperclip's thumbnail
114
- # is fallen back on by returning the value of
115
- # <tt>attribute.url(:thumb)</tt>.
116
- #
117
- # Sample use in a view:
118
- # <%= image_tag(@attachment.thumbnail_url, :alt => @attachment.name) %>
119
- def thumbnail_url(attribute)
120
- doc = scribd_document_for(attribute)
121
-
122
- (doc && doc.thumbnail_url) or self.send(attribute).url(:thumb)
123
- end
124
-
125
- # Returns the actual image data of a thumbnail for the specified
126
- # +attribute+ attachment.
127
- #
128
- # If Scribd does not have a thumbnail for this file, then
129
- # Paperclip's thumbnanil is fallen back on by returning the file from
130
- # <tt>attribute.to_file(:thumb)</tt>.
131
- #
132
- # Sample use in a controller:
133
- # render :inline => @attachment.thumbnail_file,
134
- # :content_type => 'image/jpeg'
135
- def thumbnail_file(attribute)
136
- doc = scribd_document_for(attribute)
137
-
138
- if doc && doc.thumbnail_url
139
- open(doc.thumbnail_url).read
140
- else
141
- send(attribute).to_file(:thumb).open { |f| f.read }
142
- end
143
- rescue Errno::ENOENT, NoMethodError # file not found or nil thumb file
144
- nil
145
- end
146
-
147
- # Responds true if the conversion is complete for the given +attribute+ --
148
- # note that this gives no indication as to whether the conversion had an
149
- # error or was succesful, just that the conversion completed. See
150
- # <tt>conversion_successful?</tt> for that information.
151
- #
152
- # Note also that this method still returns false if the model does not
153
- # refer to a valid document. scribd_attributes_valid? should be used to
154
- # determine the validity of the document.
155
- def conversion_complete?(attribute)
156
- doc = scribd_document_for(attribute)
157
-
158
- doc && doc.conversion_status != 'PROCESSING'
159
- end
160
-
161
- # Responds true if the document for the given +attribute+ has been
162
- # converted successfully. This *will* respond false if the conversion has
163
- # failed.
164
- #
165
- # Note that this method still returns false if the model does not refer to a
166
- # valid document. <tt>scribd_attributes_valid?</tt> should be used to
167
- # determine the validity of the document.
168
- def conversion_successful?(attribute)
169
- doc = scribd_document_for(attribute)
170
-
171
- doc && doc.conversion_status =~ /^DISPLAYABLE|DONE$/
172
- end
173
-
174
- # Responds true if there was a conversion error while converting the given
175
- # +attribute+ to iPaper.
176
- #
177
- # Note that this method still returns false if the model does not refer to a
178
- # valid document. <tt>scribd_attributes_valid?</tt> should be used to
179
- # determine the validity of the document.
180
- def conversion_error?(attribute)
181
- doc = scribd_document_for(attribute)
182
-
183
- doc && doc.conversion_status == 'ERROR'
184
- end
185
-
186
- # Responds the Scribd::Document associated with the given +attribute+, or
187
- # nil if it does not exist.
188
- def scribd_document_for(attribute)
189
- scribd_documents[attribute] ||= scribd_login.find_document(self["#{attribute}_scribd_id"])
190
- rescue Scribd::ResponseError # at minimum, the document was not found
191
- nil
192
- end
193
-
194
- private
195
- def scribd_documents
196
- @scribd_documents ||= HashWithIndifferentAccess.new
197
- end
198
-
199
- # Returns the full filename for the given attribute. If the file is
200
- # stored on S3, this is a full S3 URI, while it is a full path to the
201
- # local file if the file is stored locally.
202
- def full_filename_for(attribute)
203
- filename = attachment_for(attribute).path
204
- end
205
-
206
- # Yields the correct path to the file for the attachment in
207
- # +attribute+, either the local filename or the S3 URL.
208
- #
209
- # This method creates a temporary file of the correct filename for the
210
- # attachment in +attribute+ if necessary, so as to be able to give
211
- # scribd the right filename. The file is destroyed when the passed block
212
- # ends.
213
- def with_file_path_for(attribute, &block) # :yields: full_file_path
214
- attachment = attachment_for(attribute)
215
-
216
- if attachment.respond_to?(:s3)
217
- yield attachment.url
218
- elsif File.exists?(attachment.path)
219
- yield attachment.path
220
- else # file hasn't been saved, use a tempfile
221
- temp_rename = File.join(Dir.tmpdir, attachment.original_filename)
222
- File.copy(attachment.to_file.path, temp_rename)
223
-
224
- yield temp_rename
225
- end
226
- ensure
227
- temp_rename && File.unlink(temp_rename) # always delete this
228
- end
229
- end
230
- end
231
- end
@@ -1,58 +0,0 @@
1
- module ScribdFuHelper
2
- # Available parameters for the JS API
3
- # http://www.scribd.com/publisher/api/api?method_name=Javascript+API
4
- AVAILABLE_JS_PARAMS = [ :height, :width, :page, :my_user_id, :search_query,
5
- :jsapi_version, :disable_related_docs, :mode, :auto_size ]
6
-
7
-
8
- # Displays the scribd object for the attachment on the given +object+. If
9
- # +alt_text_or_attribute+ is given, then it will be used as the alternate text
10
- # for an Attachment_fu model, or as the attribute name for a Paperclip
11
- # model. If you want to specify alternate text for a Paperclip model, use the
12
- # last parameter, +alt_text_if_paperclip+.
13
- #
14
- # If you are using Paperclip, you _must_ specify +alt_text_or_attribute+ as
15
- # the attribute on which the scribd object exists.
16
- #
17
- # For example, using Attachment_fu:
18
- # <%= display_scribd document %>
19
- # <%= display_scribd document, 'You need Flash to view this document' %>
20
- #
21
- # Using Paperclip:
22
- # <%= display_scribd user, :biography %>
23
- # <%= display_scribd user, :biography, 'You need Flash for biographies." %>
24
- def display_scribd(object, alt_text_or_attribute = '', alt_text_if_paperclip = nil)
25
- # Resolve the right scribd ID, access key, and alt text.
26
- if object.respond_to?("scribd_id")
27
- scribd_id = object.scribd_id
28
- scribd_ak = object.scribd_access_key
29
-
30
- alt_text = alt_text_or_attribute
31
- else
32
- scribd_id = object.send "#{alt_text_or_attribute}_scribd_id"
33
- scribd_ak = object.send "#{alt_text_or_attribute}_scribd_access_key"
34
-
35
- alt_text = alt_text_if_paperclip
36
- end
37
-
38
- begin
39
- # Collect a set of addParam statements to set up JS parameters for the scribd document
40
- # (only if they are valid).
41
- param_includes = options[:params].collect do |param, value|
42
- "scribd_doc.addParam('#{param}', '#{value}');" if AVAILABLE_JS_PARAMS.include?(param)
43
- end.compact.join("\n")
44
- rescue
45
- # Where is 'options' coming from???
46
- end
47
-
48
- <<-END
49
- <script type="text/javascript" src="http://www.scribd.com/javascripts/view.js"></script>
50
- <div id="embedded_flash">#{alt_text}</div>
51
- <script type="text/javascript">
52
- var scribd_doc = scribd.Document.getDoc(#{scribd_id}, '#{scribd_ak}');
53
- #{param_includes}
54
- scribd_doc.write("embedded_flash");
55
- </script>
56
- END
57
- end
58
- end
data/rails/init.rb DELETED
@@ -1,7 +0,0 @@
1
- require 'scribd_fu'
2
- require 'scribd_fu_helper'
3
-
4
- ActiveRecord::Base.send(:include, ScribdFu)
5
- ActionView::Base.send(:include, ScribdFuHelper)
6
-
7
- RAILS_DEFAULT_LOGGER.debug "** [Scribd_fu] loaded"
data/uninstall.rb DELETED
@@ -1 +0,0 @@
1
- # Uninstall hook code here