neonredd 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (53) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +4 -0
  3. data/LICENSE.md +22 -0
  4. data/README.md +1 -0
  5. data/Rakefile +5 -0
  6. data/Redd.LICENSE.md +22 -0
  7. data/RedditKit.LICENSE.md +9 -0
  8. data/lib/redd/access.rb +76 -0
  9. data/lib/redd/clients/base/account.rb +20 -0
  10. data/lib/redd/clients/base/identity.rb +22 -0
  11. data/lib/redd/clients/base/none.rb +27 -0
  12. data/lib/redd/clients/base/privatemessages.rb +33 -0
  13. data/lib/redd/clients/base/read.rb +114 -0
  14. data/lib/redd/clients/base/stream.rb +82 -0
  15. data/lib/redd/clients/base/submit.rb +19 -0
  16. data/lib/redd/clients/base/utilities.rb +143 -0
  17. data/lib/redd/clients/base/wikiread.rb +33 -0
  18. data/lib/redd/clients/base.rb +181 -0
  19. data/lib/redd/clients/installed.rb +56 -0
  20. data/lib/redd/clients/script.rb +40 -0
  21. data/lib/redd/clients/userless.rb +32 -0
  22. data/lib/redd/clients/web.rb +59 -0
  23. data/lib/redd/error.rb +151 -0
  24. data/lib/redd/objects/base.rb +39 -0
  25. data/lib/redd/objects/comment.rb +22 -0
  26. data/lib/redd/objects/labeled_multi.rb +13 -0
  27. data/lib/redd/objects/listing.rb +29 -0
  28. data/lib/redd/objects/more_comments.rb +10 -0
  29. data/lib/redd/objects/private_message.rb +28 -0
  30. data/lib/redd/objects/submission.rb +140 -0
  31. data/lib/redd/objects/subreddit.rb +329 -0
  32. data/lib/redd/objects/thing/editable.rb +22 -0
  33. data/lib/redd/objects/thing/hideable.rb +18 -0
  34. data/lib/redd/objects/thing/inboxable.rb +25 -0
  35. data/lib/redd/objects/thing/messageable.rb +38 -0
  36. data/lib/redd/objects/thing/moderatable.rb +43 -0
  37. data/lib/redd/objects/thing/refreshable.rb +14 -0
  38. data/lib/redd/objects/thing/saveable.rb +21 -0
  39. data/lib/redd/objects/thing/votable.rb +33 -0
  40. data/lib/redd/objects/thing.rb +26 -0
  41. data/lib/redd/objects/user.rb +52 -0
  42. data/lib/redd/objects/wiki_page.rb +15 -0
  43. data/lib/redd/rate_limit.rb +88 -0
  44. data/lib/redd/response/parse_json.rb +18 -0
  45. data/lib/redd/response/raise_error.rb +16 -0
  46. data/lib/redd/version.rb +4 -0
  47. data/lib/redd.rb +50 -0
  48. data/neonredd.gemspec +33 -0
  49. data/spec/redd/objects/base_spec.rb +1 -0
  50. data/spec/redd/response/raise_error_spec.rb +11 -0
  51. data/spec/redd_spec.rb +5 -0
  52. data/spec/spec_helper.rb +71 -0
  53. metadata +225 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a84912f5d82a8f8b944023f8712dea6e8e43eea9
4
+ data.tar.gz: d68880ed1124a58477c1a820dcacc63589ebca0d
5
+ SHA512:
6
+ metadata.gz: 1b0438751bfdd66ef3d1b1efc1f7e486f0cf4de3dc13091216e2848030553f137e24baa231eb6ad71d5d196782c7fdfc87213437eded7d3a31d6ef6d6ae016b8
7
+ data.tar.gz: d7d7ffe5b266a9e216c7e69d09c3cc23c9b3ebc6ae79b73376297ad75edff0d91b31ca0a20edb9bee927fad8060cd2d4d42ed59e0499b70a7843328566e9bd5d
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in redd.gemspec
4
+ gemspec
data/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2016 SirNeon
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1 @@
1
+ # Neonredd
data/Rakefile ADDED
@@ -0,0 +1,5 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+ task default: :spec
data/Redd.LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2015 Avinash Dwarapu
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,9 @@
1
+ Copyright (c) 2013 Sam Symons
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,76 @@
1
+ require 'multi_json'
2
+
3
+ module Redd
4
+ # A container for the client's access to their account via OAuth2
5
+ class Access
6
+ # @!attribute [r] access_token
7
+ # @return [String] The access token used to access the users account.
8
+ attr_reader :access_token
9
+
10
+ # @!attribute [r] refresh_token
11
+ # @return [String, nil] The refresh token, if the access was permanent.
12
+ attr_reader :refresh_token
13
+
14
+ # @!attribute [r] scope
15
+ # @return [Array] The scope that the client is allowed to access.
16
+ attr_reader :scope
17
+
18
+ # @!attribute [r] expires_at
19
+ # @return [Time] The time when the access token expires.
20
+ attr_reader :expires_at
21
+
22
+ # @param [String] body The response body containing the required info.
23
+ def initialize(body)
24
+ @access_token = body[:access_token]
25
+ @refresh_token = body[:refresh_token]
26
+ @scope = (body[:scope] ? body[:scope].split(',') : [])
27
+ @expires_at =
28
+ if body[:expires_at]
29
+ Time.at(body[:expires_at])
30
+ else
31
+ Time.now + (body[:expires_in] || 0)
32
+ end
33
+ end
34
+
35
+ # @return [Boolean] Whether the access is temporary.
36
+ def temporary?
37
+ !refresh_token
38
+ end
39
+
40
+ # @return [Boolean] Whether the access is permanent.
41
+ def permanent?
42
+ !temporary?
43
+ end
44
+
45
+ # @return [Boolean] Whether the access has expired.
46
+ def expired?
47
+ Time.now > (@expires_at + 60)
48
+ end
49
+
50
+ # Refresh the object with the new response body.
51
+ # This happens when a new access token is requested using a request token.
52
+ # @param [Hash] body The new response body.
53
+ def refreshed!(body)
54
+ @access_token = body[:access_token]
55
+ @expires_at = Time.now + body[:expires_in]
56
+ end
57
+
58
+ # @return [String] A JSON version of the data that can be loaded later.
59
+ def to_json
60
+ MultiJson.dump(
61
+ access_token: @access_token,
62
+ refresh_token: @refresh_token,
63
+ scope: @scope.join(','),
64
+ expires_at: @expires_at.to_i
65
+ )
66
+ end
67
+
68
+ # Create a new instance of the class from the JSON returned from #to_json
69
+ # @param [String] json
70
+ # @return [Access]
71
+ def self.from_json(json)
72
+ hash = MultiJson.load(json, symbolize_keys: true)
73
+ new(hash)
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,20 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that require the "account" scope
5
+ module Account
6
+ # Edit some user preferences
7
+ # @param [Hash] changed_prefs The preferences to override.
8
+ # @return [Objects::Base] A Hashie-style container of the new prefs.
9
+ # @see https://www.reddit.com/dev/api/oauth#PATCH_api_v1_me_prefs
10
+ def edit_my_prefs(changed_prefs)
11
+ response = connection.patch do |req|
12
+ req.url '/api/v1/me/prefs'
13
+ req.body = MultiJson.dump(changed_prefs)
14
+ end
15
+ Objects::Base.new(self, response.body)
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,22 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that require the "identity" scope
5
+ module Identity
6
+ # @return [Objects::User] The logged-in user.
7
+ def me
8
+ response = get('/api/v1/me')
9
+ object_from_body(kind: 't2', data: response.body)
10
+ end
11
+
12
+ # @return [Objects::Base] Your current preferences.
13
+ # @see https://www.reddit.com/dev/api/oauth#GET_api_v1_me_prefs
14
+ def my_prefs
15
+ response = get('/api/v1/me/prefs')
16
+ # Basically an uneditable mashie.
17
+ Objects::Base.new(self, response.body)
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,27 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that don't require any scope.
5
+ module None
6
+ # @return [Boolean] Whether a captcha is required for some API methods.
7
+ def needs_captcha?
8
+ get('/api/needs_captcha.json').body
9
+ end
10
+
11
+ # Create a new captcha identifier.
12
+ # @return [String] The identifier.
13
+ # @todo Maybe create some kind of set_captcha!(...) method for the
14
+ # client to send automatically with the next response.
15
+ def new_captcha
16
+ post('/api/new_captcha').body[:json][:data][:iden]
17
+ end
18
+
19
+ # @param iden [String] The captcha identifier.
20
+ # @return The url for the captcha image.
21
+ def captcha_url(iden)
22
+ "http://www.reddit.com/captcha/#{iden}.png"
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,33 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that require the "privatemessages" scope
5
+ module Privatemessages
6
+ # Return a listing of a user's private messages.
7
+ #
8
+ # @param category ["inbox", "unread", "sent"] The category of messages
9
+ # to view.
10
+ # @param mark [Boolean] Whether to remove the orangered from the
11
+ # user's inbox.
12
+ # @param params [Hash] A list of params to send with the request.
13
+ # @option params [String] :after Return results after the given
14
+ # fullname.
15
+ # @option params [String] :before Return results before the given
16
+ # fullname.
17
+ # @option params [Integer] :count (0) The number of items already seen
18
+ # in the listing.
19
+ # @option params [1..100] :limit (25) The maximum number of things to
20
+ # return.
21
+ def my_messages(category = 'inbox', mark = false, params = {})
22
+ params[:mark] = mark
23
+ request_object(:get, "/message/#{category}.json", params)
24
+ end
25
+
26
+ # Mark all messages as read.
27
+ def read_all_messages
28
+ post('/api/read_all_messages')
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,114 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that require the "read" scope
5
+ module Read
6
+ # @param [Array<String>] fnames A list of fullnames.
7
+ # @return [Objects::Listing<Objects::Thing>] A listing of things with
8
+ # the fullname.
9
+ def from_fullname(*fnames)
10
+ names = fnames.join(',')
11
+ request_object(:get, '/api/info', id: names)
12
+ end
13
+
14
+ # @param [String] url The url of the thing.
15
+ # @return [Objects::Thing] The thing.
16
+ def from_url(url)
17
+ request_object(:get, '/api/info', url: url).first
18
+ end
19
+
20
+ # @param [String] name The username.
21
+ # @return [Objects::User] The user.
22
+ def user_from_name(name)
23
+ request_object(:get, "/user/#{name}/about.json")
24
+ end
25
+
26
+ # @param [String] name The subreddit's display name.
27
+ # @return [Objects::Subreddit] The subreddit if found.
28
+ def subreddit_from_name(name)
29
+ request_object(:get, "/r/#{name}/about.json")
30
+ end
31
+
32
+ # Fetch a list of multis belonging to the user.
33
+ def my_multis
34
+ multis = get('/api/multi/mine').body
35
+ multis.map { |thing| object_from_body(thing) }
36
+ end
37
+
38
+ # Fetch an individual multi from its path.
39
+ # @param [String] path The multi's path.
40
+ # @return [Objects::LabeledMulti]
41
+ def multi_from_path(path)
42
+ # rubocop:disable Style/RegexpLiteral
43
+ without_slash = path.gsub(/^\//, '')
44
+ request_object(:get, '/api/multi/' + without_slash)
45
+ end
46
+
47
+ # @!method get_hot(subreddit = nil, **params)
48
+ # @!method get_new(subreddit = nil, **params)
49
+ # @!method get_top(subreddit = nil, **params)
50
+ # @!method get_controversial(subreddit = nil, **params)
51
+ # @!method get_comments(subreddit = nil, **params)
52
+ #
53
+ # Get the appropriate listing.
54
+ # @param subreddit [Objects::Subreddit, String] The subreddit to query.
55
+ # @param params [Hash] A list of params to send with the request.
56
+ # @option params [String] :after Return results after the given
57
+ # fullname.
58
+ # @option params [String :before Return results before the given
59
+ # fullname.
60
+ # @option params [Integer] :count The number of items already seen in
61
+ # the listing.
62
+ # @option params [1..1000] :limit The maximum number of things to
63
+ # return.
64
+ # @option params [:hour, :day, :week, :month, :year, :all] :t The
65
+ # time period to consider when sorting.
66
+ #
67
+ # @note The option :t only applies to the top and controversial sorts.
68
+ # @return [Objects::Listing<Objects::Thing>]
69
+ # @todo Move all listing methods into a helper?
70
+ %w(hot new top controversial comments).each do |sort|
71
+ define_method :"get_#{sort}" do |subreddit = nil, **params|
72
+ srname = property(subreddit, :display_name) if subreddit
73
+ path = "/#{sort}.json"
74
+ path = path.prepend("/r/#{srname}") if subreddit
75
+ request_object(:get, path, params)
76
+ end
77
+ end
78
+
79
+ # Search.
80
+ # @param query [String] The query string.
81
+ # @param subreddit [Objects::Subreddit, String] The subreddit to query.
82
+ # @param params [Hash] A list of params to send with the request.
83
+ # @option params [String] :after Return results after the given
84
+ # fullname.
85
+ # @option params [String] :before Return results before the given
86
+ # fullname.
87
+ # @option params [Integer] :count The number of items already seen in
88
+ # the listing.
89
+ # @option params [1..100] :limit The maximum number of things to
90
+ # return.
91
+ # @option params [:cloudsearch, :lucene, :plain] :syntax The type of
92
+ # syntax to use.
93
+ # @option params [:relevance, :new, :hot, :top, :comments] :sort The
94
+ # way to sort the results.
95
+ # @option params [:hour, :day, :week, :month, :year, :all] :t The
96
+ # time period to consider when sorting.
97
+ #
98
+ # @note The option :t only applies to the top and controversial sorts.
99
+ # @return [Objects::Listing<Objects::Thing>]
100
+ def search(query, subreddit = nil, **params)
101
+ path = '/search.json'
102
+ params[:q] = query
103
+ if subreddit
104
+ params[:restrict_sr] = true
105
+ srname = property(subreddit, :display_name)
106
+ path = path.prepend("/r/#{srname}")
107
+ end
108
+
109
+ request_object(:get, path, params)
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,82 @@
1
+ require 'set'
2
+
3
+ module Redd
4
+ module Clients
5
+ class Base
6
+ # Methods that stream delicious content into your bot's lazy mouth.
7
+ module Stream
8
+ # A class similar to PRAW's implementation of a BoundedSet.
9
+ class PRAWBoundedQueueSet < Set
10
+ def initialize(max, *args, &block)
11
+ @max = max
12
+ @queue = []
13
+ super(*args, &block)
14
+ end
15
+
16
+ # Add an element to the front if it isn't already in the queue.
17
+ # @param element
18
+ # @return [PRAWBoundedQueueSet] self
19
+ def enqueue(element)
20
+ @queue.push(element) if add?(element)
21
+ dequeue! if size > @max
22
+ self
23
+ end
24
+ alias enq enqueue
25
+
26
+ # Add an element to the front if it isn't already in the queue.
27
+ # @param element
28
+ # @return [Boolean] Whether the element was added to the queue.
29
+ def enqueue?(element)
30
+ added = add?(element)
31
+ if added
32
+ @queue.push(element)
33
+ dequeue if size > @max
34
+ end
35
+ added
36
+ end
37
+ alias enq? enqueue?
38
+
39
+ # Remove the last element of the queue.
40
+ # @return The removed element.
41
+ def dequeue
42
+ element = @queue.shift
43
+ delete(element)
44
+ element
45
+ end
46
+ alias deq dequeue
47
+ end
48
+
49
+ # Stream the results of a method call to the given block.
50
+ # @param [Symbol] meth A method that returns a listing and has a
51
+ # keyword parameter named `:before`.
52
+ # @param [Array] args The arguments supplied to the method.
53
+ # @param [Hash] kwargs The keyword arguments supplied to the method.
54
+ # @yield An element of the returned listing.
55
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
56
+ def stream(meth = :get_new, *args, **kwargs)
57
+ bset = PRAWBoundedQueueSet.new(10)
58
+ before = ''
59
+ loop do
60
+ begin
61
+ # Get the latest comments from the subreddit.
62
+ params = kwargs.merge(before: before)
63
+ listing = send(meth, *args, **params)
64
+ # Run the loop for each of the item in the listing
65
+ listing.reverse_each do |thing|
66
+ yield thing if bset.enqueue?(thing.fullname)
67
+ end
68
+ # Set the latest comment.
69
+ before = listing.first.fullname unless listing.empty?
70
+ rescue Redd::Error::RateLimited => error
71
+ # If this error pops up, you probably have an issue with your bot.
72
+ sleep(error.time)
73
+ rescue Redd::Error => error
74
+ # 5-something errors are usually errors on reddit's end.
75
+ raise error unless (500...600).cover?(error.code)
76
+ end
77
+ end
78
+ end
79
+ end # <- See, this is why I sometimes prefer Python.
80
+ end # <- Thank god for code folding.
81
+ end
82
+ end
@@ -0,0 +1,19 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that require the "submit" scope
5
+ module Submit
6
+ # Add a comment to a link, reply to a comment or reply to a message.
7
+ # Bit of an all-purpose method, this one.
8
+ # @param thing [Objects::Submission, Objects::Comment,
9
+ # Objects::PrivateMessage] A thing to add a comment to.
10
+ # @param text [String] The text to comment.
11
+ # @return [Objects::Comment, Objects::PrivateMessage] The reply.
12
+ def add_comment(thing, text)
13
+ response = post('/api/comment', text: text, thing_id: thing.fullname)
14
+ object_from_body(response.body[:json][:data][:things][0])
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,143 @@
1
+ require_relative '../../objects/base'
2
+ require_relative '../../objects/thing'
3
+ require_relative '../../objects/listing'
4
+ require_relative '../../objects/wiki_page'
5
+ require_relative '../../objects/labeled_multi'
6
+ require_relative '../../objects/more_comments'
7
+ require_relative '../../objects/comment'
8
+ require_relative '../../objects/user'
9
+ require_relative '../../objects/submission'
10
+ require_relative '../../objects/private_message'
11
+ require_relative '../../objects/subreddit'
12
+
13
+ module Redd
14
+ module Clients
15
+ class Base
16
+ # Internal methods that make life easier.
17
+ # @todo Move this out to Redd::Utils?
18
+ module Utilities
19
+ # The kind strings and the objects that should be used for them.
20
+ OBJECT_KINDS = {
21
+ 'Listing' => Objects::Listing,
22
+ 'wikipage' => Objects::WikiPage,
23
+ 'LabeledMulti' => Objects::LabeledMulti,
24
+ 'more' => Objects::MoreComments,
25
+ 't1' => Objects::Comment,
26
+ 't2' => Objects::User,
27
+ 't3' => Objects::Submission,
28
+ 't4' => Objects::PrivateMessage,
29
+ 't5' => Objects::Subreddit
30
+ }.freeze
31
+
32
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
33
+ # Request and create an object from the response.
34
+ # @param [Symbol] meth The method to use.
35
+ # @param [String] path The path to visit.
36
+ # @param [Hash] params The data to send with the request.
37
+ # @return [Objects::Base] The object returned from the request.
38
+ def request_object(meth, path, params = {})
39
+ unless params[:limit].nil?
40
+ if params[:limit] > 100
41
+ multiplier = params[:limit] / 100
42
+ last_block_limit = params[:limit] - (multiplier * 100)
43
+ multiplier -= 1
44
+ params[:limit] = 100
45
+ body = send(meth, path, params).body
46
+ listing = object_from_body(body)
47
+
48
+ params[:after] = listing.after
49
+ after = append_to_listing(meth, path, params, multiplier, listing)
50
+
51
+ params[:limit] = last_block_limit
52
+ params[:after] = after
53
+
54
+ unless after.nil?
55
+ append_to_listing(meth, path, params, 1, listing)
56
+ end
57
+ return listing
58
+ end
59
+ end
60
+ body = send(meth, path, params).body
61
+ object_from_body(body)
62
+ end
63
+
64
+ # appends items to a listing when the limit is > 100
65
+ # @param [Symbol] meth The method to use.
66
+ # @param [String] path The path to visit.
67
+ # @param [Hash] params The data to send with the request.
68
+ # @param [Integer] multiplier The number of times to get listings
69
+ # @param [Redd::Objects::Listing] listing The listing to append to
70
+ # @return [String] returns the last Redd::Objects::Listing#after.
71
+ def append_to_listing(meth, path, params, multiplier, listing)
72
+ multiplier.times do
73
+ body = send(meth, path, params).body
74
+ new_listing = object_from_body(body)
75
+ params[:after] = new_listing.after
76
+ new_listing.each { |item| listing << item }
77
+ end
78
+ params[:after]
79
+ end
80
+
81
+ # Create an object instance with the correct attributes when given a
82
+ # body.
83
+ #
84
+ # @param [Hash] body A JSON hash.
85
+ # @return [Objects::Thing, Objects::Listing]
86
+ def object_from_body(body)
87
+ return nil unless body.is_a?(Hash)
88
+ object = object_from_kind(body[:kind])
89
+ flat = flatten_body(body)
90
+ object.new(self, flat)
91
+ end
92
+
93
+ # @param [Objects::Submission, Objects::Comment] base The start of the
94
+ # comment tree.
95
+ # @author Bryce Boe (@bboe) in Python
96
+ # @return [Array<Objects::Comment, Objects::MoreComments>] A linear
97
+ # array of the submission's comments or the comments' replies.
98
+ def flat_comments(base)
99
+ meth = (base.is_a?(Objects::Submission) ? :comments : :replies)
100
+ stack = base.send(meth).dup
101
+ flattened = []
102
+
103
+ until stack.empty?
104
+ comment = stack.shift
105
+ if comment.is_a?(Objects::Comment)
106
+ replies = comment.replies
107
+ stack = replies + stack if replies
108
+ end
109
+ flattened << comment
110
+ end
111
+
112
+ flattened
113
+ end
114
+
115
+ # Get a given property of a given object.
116
+ # @param [Objects::Base, String] object The object with the property.
117
+ # @param [Symbol] property The property to get.
118
+ def property(object, property)
119
+ object.respond_to?(property) ? object.send(property) : object.to_s
120
+ end
121
+
122
+ private
123
+
124
+ # Take a multilevel body ({kind: "tx", data: {...}}) and flatten it
125
+ # into something like {kind: "tx", ...}
126
+ # @param [Hash] body The response body.
127
+ # @return [Hash] The flattened hash.
128
+ def flatten_body(body)
129
+ data = body[:data] || body
130
+ data[:kind] = body[:kind]
131
+ data
132
+ end
133
+
134
+ # @param [String] kind A kind in the format /t[1-5]/.
135
+ # @return [Objects::Base, Objects::Listing] The appropriate object for
136
+ # a given kind.
137
+ def object_from_kind(kind)
138
+ OBJECT_KINDS.fetch(kind, Objects::Base)
139
+ end
140
+ end
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,33 @@
1
+ module Redd
2
+ module Clients
3
+ class Base
4
+ # Methods that require the "wikiread" scope.
5
+ # @note This method is not limited to {Objects::Subreddit} because there
6
+ # are also top-level wiki pages.
7
+ module Wikiread
8
+ # Get a list of pages in the subreddit wiki.
9
+ # @param subreddit [Objects::Subreddit, String] The subreddit to
10
+ # look in.
11
+ # @return [Array<String>] An array of wikipage titles.
12
+ def get_wikipages(subreddit = nil)
13
+ path = '/wiki/pages.json'
14
+ name = property(subreddit, :display_name)
15
+ path.prepend("/r/#{name}") if subreddit
16
+ get(path).body[:data]
17
+ end
18
+
19
+ # Get a wiki page.
20
+ # @param page [String] The title of the wiki page.
21
+ # @param subreddit [Objects::Subreddit, String] The subreddit to
22
+ # look in.
23
+ # @return [Objects::WikiPage] A wiki page.
24
+ def wikipage(page, subreddit = nil)
25
+ path = "/wiki/#{page}.json"
26
+ name = property(subreddit, :display_name)
27
+ path.prepend("/r/#{name}") if subreddit
28
+ request_object(:get, path)
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end