lib/saber/tracker/base.rb in saber-0.0.7 vs lib/saber/tracker/base.rb in saber-1.0.0
- old
+ new
@@ -1,8 +1,121 @@
-require "httparty"
+require "active_support/core_ext/string/inflections"
module Saber
- class Tracker
+ module Tracker
class Base
+ def self.inherited(child)
+ Tracker.trackers[child.name.demodulize.underscore] = child
+ end
+
+ # implement
+ @@POPULATE_TYPES = []
+
+ def self.can_populate?(type)
+ @@POPULATE_TYPES.include?(type.to_s)
+ end
+
+ # implement
+ @@BASE_URL = ""
+ @@LOGIN_CHECK_PATH = ""
+
+ attr_reader :agent
+ attr_reader :site_name
+
+ def initialize
+ @site_name = self.class.name.demodulize.underscore
+ @agent = Mechanize.new
+
+ @agent.get(@@BASE_URL)
+ end
+
+ def login
+ if login_with_cookie
+ return
+ end
+
+ login_with_username
+ end
+
+ def upload(*torrent_files)
+ files = torrent_files.map{|v| Pa.delete_ext(v, ".torrent")}
+
+ files.each {|file|
+ info = Optimism.require!("./#{file}.yml")
+
+ if do_upload(file, info)
+ Saber.ui.say "Upload Complete: #{file}"
+ else
+ Saber.ui.error "Upload Failed: #{file}"
+ end
+ }
+ end
+
+ # Return data by auto-fill functions provied by site.
+ #
+ # @example
+ #
+ # populate("ebook", isbn)
+ #
+ # @return [Hash]
+ def populate(type, *args)
+ meth = "populate_#{type}"
+
+ if respond_to?(meth) then
+ send meth, *args
+ else
+ raise ArgumentError, "Not support this type -- #{type}"
+ end
+ end
+
+ protected
+
+ # Implement
+ #
+ # @return [Boolean] success?
+ def do_upload(file, info)
+ raise NotImplementedError
+ end
+
+ # Implement
+ #
+ # @return [Boolean] success?
+ def do_login_with_username(username)
+ raise NotImplementedError
+ end
+
+ def login_with_cookie
+ if Pa.exists?("#{Rc.p.home}/#{site_name}.cookies") then
+ open("#{Rc.p.home}/#{site_name}.cookies") { |io|
+ agent.cookie_jar.load_cookiestxt(io)
+ }
+
+ ret = agent.get(@@LOGIN_CHECK_PATH)
+
+ if ret.uri.path == @@LOGIN_CHECK_PATH
+ true
+ else
+ Saber.ui.say "Login with cookie failed."
+ false
+ end
+ end
+ end
+
+ def login_with_username
+ username = Rc._fetch(["#{site_name}.username", "username"], nil)
+
+ Saber.ui.say "Begin to login manually."
+ Saber.ui.say "Username: #{username}" if username
+ loop do
+ if do_login_with_username(username)
+ open("#{Rc.p.home}/#{site_name}.cookies", "w") { |f|
+ agent.cookie_jar.dump_cookiestxt(f)
+ }
+ return true
+ end
+ end
+ end
end
end
end
+
+# vim: fdn=4