utilities.rb 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. require 'java'
  2. java_import com.jbidwatcher.util.config.JConfig
  3. java_import com.cyberfox.util.platform.Path
  4. java_import com.jbidwatcher.util.Currency
  5. java_import com.jbidwatcher.util.Constants
  6. java_import com.jbidwatcher.util.queue.MQFactory
  7. java_import com.jbidwatcher.auction.AuctionEntry
  8. java_import com.jbidwatcher.auction.server.AuctionServerManager
  9. java_import com.jbidwatcher.ui.AuctionsManager
  10. java_import com.jbidwatcher.ui.FilterManager
  11. java_import com.jbidwatcher.ui.table.TableColumnController
  12. java_import com.jbidwatcher.ui.commands.UserActions
  13. java_import com.jbidwatcher.ui.commands.MenuCommand
  14. puts "Loading JBidwatcher Ruby Utilities"
  15. require 'rubygems'
  16. dirname = File.dirname(__FILE__)
  17. gems = if File.exists?(File.join(dirname, 'gems.jar')) || File.exists?('lib/jbidwatcher/gems.jar')
  18. File.expand_path(File.join(dirname, 'gems.jar'))
  19. else
  20. JConfig.java_class.class_loader.resource_as_url('lib/jbidwatcher/gems.jar').to_s
  21. end
  22. # This is an awful hack, but if I don't do this, Windows doesn't load active_support. :(
  23. class File
  24. def self.realpath(x)
  25. x
  26. end
  27. end
  28. require gems
  29. ENV['GEM_PATH']="#{gems}!/"
  30. Gem.paths = ENV
  31. require 'digest/md5'
  32. require 'net/http.rb'
  33. require 'cgi'
  34. require 'nokogiri'
  35. require 'json'
  36. require 'open-uri'
  37. require 'ebay_parser'
  38. require 'time'
  39. require 'column_lookup'
  40. class JBidwatcherUtilities
  41. MY_JBIDWATCHER_URL = "http://my.jbidwatcher.com:9876/advanced"
  42. def test_basics
  43. # Check that the basic libraries work.
  44. puts "This is a test..."
  45. puts Digest::MD5.hexdigest('foo')
  46. # Check that accessing objects defined by JBidwatcher works
  47. c = Currency.getCurrency("$54.98")
  48. puts c.getValue
  49. puts c.fullCurrencyName
  50. puts "Done."
  51. end
  52. def about
  53. MQFactory.getConcrete("user").enqueue("FAQ")
  54. end
  55. def fire(user_event)
  56. MQFactory.getConcrete("user").enqueue(user_event)
  57. end
  58. def build_url(meth, hash)
  59. uri = "#{MY_JBIDWATCHER_URL}/#{meth}"
  60. url = URI.parse(uri)
  61. [uri, url, hash.to_param]
  62. end
  63. def post(command, hash)
  64. uri, url, params = build_url(command, hash)
  65. p = Net::HTTP::Post.new(uri)
  66. p.body = params
  67. p.content_type = 'application/x-www-form-urlencoded'
  68. Net::HTTP.new(url.host, url.port).start do |http|
  69. http.request p
  70. end
  71. end
  72. def report_exception(exception)
  73. result = post "exception", {:body => exception}
  74. puts result.body
  75. result.body
  76. end
  77. def recognize_bidpage(entry, page)
  78. puts entry.title
  79. result = post "recognize", {:body => page, :user => JConfig.queryConfiguration("my.jbidwatcher.id")}
  80. puts result.body
  81. result.body
  82. end
  83. def browse_to(id)
  84. entry = $auctions_manager.getEntry(id)
  85. entry.server.showBrowser(entry)
  86. end
  87. def notify(message)
  88. MQFactory.getConcrete("Swing").enqueue("NOTIFY #{message}")
  89. end
  90. def snipe(auction, amount)
  91. entry = auction if(auction.respond_to? :getIdentifier)
  92. entry ||= $auctions_manager.getEntry(auction)
  93. amount = Currency.getCurrency(amount) unless amount.respond_to? :fullCurrencyName
  94. entry.prepareSnipe(amount)
  95. $filter_manager.redrawEntry(entry)
  96. end
  97. def cancel_snipe(id)
  98. entry = $auctions_manager.getEntry(id)
  99. entry.cancelSnipe(false)
  100. $filter_manager.redrawEntry(entry)
  101. end
  102. def custom_column(column, auction)
  103. @columns[column].call(auction).to_s
  104. end
  105. def add_column(name, &block)
  106. $table_controller.add_column(name) unless @columns[name]
  107. @columns[name] = block
  108. end
  109. def initialize
  110. @columns = {}
  111. end
  112. COMMANDS = {}
  113. UserActions.java_class.declared_instance_methods.each do |m|
  114. if m.annotation_present?(MenuCommand.java_class)
  115. annotation = m.annotation(MenuCommand.java_class)
  116. COMMANDS[annotation.action] = { :name => m.name.to_sym, :arity => annotation.params } if annotation.action && annotation.action != ""
  117. COMMANDS[m.name.to_sym] = { :name => m.name.to_sym, :arity => annotation.params }
  118. end
  119. end
  120. TRANSLATIONS = {
  121. 'Add New' => 'Add',
  122. 'Check For Updates' => 'Check Updates',
  123. 'Explain Colors And Icons' => 'Help Colors'
  124. }
  125. def handle_action(action, action_manager, *params)
  126. do_action = "Do#{action.gsub(' ', '')}".to_sym
  127. pair = COMMANDS[action] || COMMANDS[do_action]
  128. method = pair.nil? ? do_action : pair[:name]
  129. arity = pair.nil? ? 0 : pair[:arity]
  130. # Special case params: -1 means pass in null as the sole parameter, -2 means just the auction entry.
  131. params, arity = {-1 => [[nil], 1], -2 => [[params[1]], 1]}[arity] if arity < 0
  132. if action_manager.respond_to?(method, true)
  133. params = [method] + params[0...arity]
  134. action_manager.send(*params)
  135. else
  136. JConfig.log.logMessage "Did not know how to handle #{action}"
  137. end
  138. end
  139. def load_scripts
  140. script_dir = Path.getCanonicalFile "scripts","jbidwatcher",false
  141. if File.exist?(script_dir) && File.directory?(script_dir)
  142. sd = Dir.new script_dir
  143. scripts = sd.reject do |filename|
  144. script_file = File.join(script_dir, filename)
  145. File.directory?(script_file) || File.extname(script_file) != '.rb'
  146. end
  147. scripts.each do |script_file|
  148. require File.join(script_dir, script_file)
  149. end
  150. else
  151. unless File.exist? script_dir
  152. Dir.mkdir script_dir
  153. end
  154. end
  155. end
  156. def after_startup
  157. require "models"
  158. gixen
  159. require 'active_support'
  160. require 'active_support/core_ext'
  161. require 'pp'
  162. end
  163. def parse(body)
  164. Ebay::Parser.new(body).parse
  165. end
  166. def log(msg)
  167. JConfig.log.logMessage msg
  168. end
  169. def get_update(auction_id, last_updated_at)
  170. current = (Time.now.to_f*1000).to_i
  171. last_int = last_updated_at.nil? ? 0 : last_updated_at.time
  172. lite_url = "http://www.ebay.com/itm/ws/eBayISAPI.dll?ViewItemLite&pbv=0&item=#{auction_id}"
  173. lite_url += "&lastaccessed=#{last_int}&lvr=0&dl=5&_=#{current}"
  174. body = open(lite_url).read
  175. result = JSON.parse(body)
  176. response = result['ViewItemLiteResponse']
  177. if response['Error'].blank?
  178. item = response['Item'].first
  179. end_date = item['EndDate']
  180. ends_at = Time.parse(end_date['Time'] + ' ' + end_date['Date'])
  181. cur_price = item['CurrentPrice']['MoneyStandard']
  182. ended = item['IsEnded']
  183. bid_count = item['BidCount']
  184. {
  185. 'current_price' => cur_price,
  186. 'end_date' => (ends_at.to_f*1000).to_i,
  187. 'ended' => ended,
  188. 'bid_count' => bid_count
  189. }
  190. end
  191. rescue => e
  192. log e.inspect
  193. return nil
  194. end
  195. def dump_hash(h)
  196. pp h
  197. end
  198. def gixen
  199. @gixen ||= begin
  200. dirname = File.dirname(__FILE__)
  201. if File.exists?(File.join(dirname, "gixen")) || File.exists?('lib/jbidwatcher/gixen')
  202. $:<< File.join(dirname, "gixen")
  203. else
  204. $:<< JConfig.java_class.class_loader.resource_as_url('lib/jbidwatcher/gixen').to_s
  205. end
  206. require 'gixen'
  207. server_prefix = Constants::EBAY_SERVER_NAME
  208. username = JConfig.query_configuration("#{server_prefix}.user")
  209. password = JConfig.query_configuration("#{server_prefix}.password")
  210. Gixen.new(username, password) if username != 'default'
  211. end
  212. end
  213. # This is just a dumping ground right now; I should change that soon.
  214. def get_value(entry, column)
  215. end
  216. end
  217. # $auction_server_manager = AuctionServerManager.getInstance
  218. # $auctions_manager = AuctionsManager.getInstance
  219. # $filter_manager = $auctions_manager.filters
  220. $table_controller = TableColumnController.getInstance
  221. JBidwatcher = JBidwatcherUtilities.new
  222. JBidwatcher.load_scripts
  223. # case TableColumnController.CUR_BID :
  224. # return currentBid(aEntry);
  225. # case TableColumnController.SNIPE_OR_MAX : return formatSnipeAndBid(aEntry);
  226. # case TableColumnController.MAX : return aEntry.isBidOn() ? formatBid(aEntry, errorNote) :neverBid;
  227. # case TableColumnController.SNIPE :
  228. # return snipeColumn(aEntry, errorNote);
  229. # case TableColumnController.TIME_LEFT :
  230. # return timeLeftColumn(aEntry);
  231. # case TableColumnController.END_DATE :
  232. # return endDateColumn(aEntry);
  233. # case TableColumnController.TITLE : return XMLElement.decodeString(aEntry.getTitle());
  234. # case TableColumnController.STATUS : return getEntryIcon(aEntry);
  235. # case TableColumnController.THUMBNAIL :
  236. # return thumbnailColumn(aEntry);
  237. # case TableColumnController.SELLER :
  238. # return aEntry.getSellerName();
  239. # case TableColumnController.COMMENT :
  240. # String comment = aEntry.getComment();
  241. # return(comment==null? "" :comment);
  242. # case TableColumnController.BIDDER :
  243. # String bidder = aEntry.getHighBidder();
  244. # if (bidder != null && bidder.length() != 0)
  245. # return bidder;
  246. # return "--";
  247. # case TableColumnController.FIXED_PRICE :
  248. # Currency bin = aEntry.getBuyNow();
  249. # if (bin.isNull())
  250. # return "--";
  251. # return bin;
  252. # case TableColumnController.SHIPPING_INSURANCE :
  253. # Currency ship = aEntry.getShippingWithInsurance();
  254. # if (ship.isNull())
  255. # return "--";
  256. # return ship;
  257. # case TableColumnController.ITEM_LOCATION :
  258. # return aEntry.getItemLocation();
  259. # case TableColumnController.BIDCOUNT :
  260. # if (aEntry.getNumBidders() < 0)
  261. # return "(FP)";
  262. # return Integer.toString(aEntry.getNumBidders());
  263. # case TableColumnController.JUSTPRICE :
  264. # return aEntry.getCurrentPrice();
  265. # case TableColumnController.SELLER_FEEDBACK :
  266. # return seller.getFeedback();
  267. # case TableColumnController.SELLER_POSITIVE_FEEDBACK :
  268. # String fbp = seller.getPositivePercentage();
  269. # return (fbp == null || fbp.length() == 0) ? "--" :fbp;
  270. # case TableColumnController.CUR_TOTAL :
  271. # return priceWithShippingColumn(aEntry);
  272. # case TableColumnController.SNIPE_TOTAL :
  273. # return formatTotalSnipe(aEntry, errorNote);
  274. #
  275. #