jekyll-tweetsert 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 620896be0df8f5c877e4e8c52ecf5e879d29e4e3
4
+ data.tar.gz: c1c12cd48eef6759c32aa46c744323a6396fa7c2
5
+ SHA512:
6
+ metadata.gz: 5df648c341876335f5e80622faa8a262bbe6b1fca1f7684f570217c547c68e09c15c729121e3982a8ad22f398a25438eb93da990a72e5eb11a6fb032ec0062d5
7
+ data.tar.gz: e72c0eae8d162b2c0e67c50fa7ec09635a267a7079fbc05f4430559578e7c13aa543533bf6bc91ea5b61bd23ef52409f84bc3e5e9208d03b7c3615da122d58f1
@@ -0,0 +1,20 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # Swap
11
+ [._]*.s[a-v][a-z]
12
+ [._]*.sw[a-p]
13
+ [._]s[a-v][a-z]
14
+ [._]sw[a-p]
15
+ Session.vim
16
+
17
+ # rspec failure tracking
18
+ .rspec_status
19
+
20
+ jekyll-tweetsert*.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.16.0
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at TODO: Write your email address. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in jekyll-tweetsert.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 TODO: Write your name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,321 @@
1
+ # Jekyll::Tweetsert
2
+
3
+ *Version 1.0.0*
4
+
5
+ *Tweetsert* is a plugin for Jekyll that pulls recent tweets from one or more Twitter handles, then inserts them (dated appropriately) as regular posts on your site. You can specify which tweets to include or exclude based on patterns or words, import retweets and replies, and tweak the theme and link colors of the embedded tweet.
6
+
7
+ To organize your tweet-posts, Tweetsert can automatically assign a category and/or tag. You may also choose to automatically import Twitter hashtags.
8
+
9
+ ### Why do this?
10
+
11
+ 1. You want your blog readers to also see your recent tweets when they visit;
12
+ 1. You may want to pull in tweets from friends, family, co-workers, etc. into your blog;
13
+ 1. You want to create a blog composed only of tweets from a group of people;
14
+ 1. Just for fun!
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'jekyll-tweetsert'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ $ bundle
27
+
28
+ Or install it yourself as:
29
+
30
+ $ gem install jekyll-tweetsert
31
+
32
+ In compliance with the spirit of Twitter's API usage guidelines, you will need an access token. Get it here:
33
+
34
+ > **[tweetsert.hook.io](http://tweetsert.hook.io)**
35
+
36
+ You will be directed to Twitter's OAuth system. Once you grant permission (read-only), you will be presented with a token that you then place into your `_config.yml`. If you don't want to do that, you may use the environment variable **`JTP_ACCESS_TOKEN`** instead.
37
+
38
+ $ export JTP_ACCESS_TOKEN="..."
39
+ $ jekyll serve
40
+
41
+ ## Usage
42
+
43
+ The minimum configuration to run *Tweetsert* is the following:
44
+
45
+ ```yaml
46
+ tweetsert:
47
+ enabled: true
48
+ timeline:
49
+ handle: 'ibrado'
50
+ access_token: "12345678-aBcDeFgHiJkLmNoPqRsTuVwXyZajni01234567890"
51
+ ```
52
+
53
+ Here is a sample `_config.yml` section, with comments:
54
+
55
+ ```yaml
56
+ tweetsert:
57
+ enabled: true
58
+ layout: "tweet" # Template in _layouts to use; default "page"
59
+
60
+ # Show additional messages for debugging
61
+ #debug: true
62
+
63
+ # Prefix, number of words, and suffix of the generated titles
64
+ title:
65
+ #prefix: "[Tweet] "
66
+ words: 9
67
+ suffix: " ..."
68
+
69
+ # Some post/page properties you may want to set automatically
70
+ #properties:
71
+ # is_tweet: true
72
+ # tweet_html: $ # the embedded tweet
73
+ # share: false
74
+ # comments: true
75
+
76
+ # The timeline(s) you import, and which tweets you want/don't want
77
+ timeline:
78
+ # Your handle; you may also just use 'handles' below
79
+ handle: 'ibrado'
80
+
81
+ # Other handles you want to include
82
+ # If you get an 404 Not Found, you may have misspelled a handle
83
+ #handles:
84
+ # - 'somehandle'
85
+ # - 'anotherhandle'
86
+
87
+ # The token you got via tweetsert.hook.io
88
+ # You may also use the JTP_ACCESS_TOKEN environment variable instead
89
+ access_token: "12345678-aBcDeFgHiJkLmNoPqRsTuVwXyZajni01234567890"
90
+
91
+ # Timeline entries to retrieve. Limited by Twitter to 200; default 100
92
+ # Note that this includes deleted tweets, so it's not exact
93
+ limit: 100
94
+
95
+ # Include tweets starting with @handle; default: false
96
+ #replies: true
97
+
98
+ # Include retweets (RT); default false
99
+ #retweets: true
100
+
101
+ # If both include and exclude are configured below,
102
+ # only tweets pulled in by "include" will be further filtered by "exclude"
103
+
104
+ # Only include tweets that have these words/handles/hashtags/URLs
105
+ # (case insensitive regex)
106
+ #include:
107
+ #- '#blog'
108
+ #- '(^|[^@\w])@(\w{1,15})\b' # Must mention @someone
109
+ #- 'important'
110
+ #- '@handle'
111
+
112
+ # Exclude tweets that have these words/handles/hashtags/URLs
113
+ # (case insensitive regex)
114
+ exclude:
115
+ - 'https://example.org/\d+/' # Your own blog posts
116
+ - '^.@' # Tweets that start with .@someone
117
+ #- 'ignore'
118
+ #- '#somehash'
119
+ #- '@handle'
120
+
121
+ # Do not include tweets newer than your latest post; default true
122
+ #no_newer: false
123
+
124
+ # Do not include tweets older than your first post; default true
125
+ #no_older: false
126
+
127
+ embed:
128
+ # Set to false if you don't want the excerpt to be set; default true
129
+ #excerpts: false
130
+
131
+ # Set to dark if you want a dark background/light text; default: light
132
+ #theme: "dark"
133
+
134
+ # Base color of the links, default: set by Twitter
135
+ #link_color: "#80FF80"
136
+
137
+ # Include Twitter's oEmbed API script every time; default: false
138
+ # Set to true if you manually include it in e.g. the header
139
+ #omit_script: true
140
+
141
+ category:
142
+ default: "tweets" # Automatically set to this category
143
+ dir: "" # Folder that contains your categories
144
+ #dir: "categories" # Default
145
+
146
+ layout: "cat_index" # What layout to use, inside _layouts
147
+ #layout: "category_index" # Default
148
+
149
+ #title:
150
+ # prefix: "Posts in the «" # Prefix of the generated title
151
+ # suffix: "» category" # Suffix of the generated title
152
+
153
+ tags:
154
+ #default: "tweet" # Tag all tweets automatically with this
155
+ dir: "tag" # Location of the generated tag indices
156
+ layout: "tag_index" # As above, for tags
157
+ #title:
158
+ # prefix: "Posts tagged “"
159
+ # suffix: "”"
160
+
161
+ hashtags: true # Import #hashtags as site tags
162
+
163
+ # Hashtags you don't want to import
164
+ ignore:
165
+ - blahblah
166
+
167
+ # Automatic tagging based on content, tag: <string or array>
168
+ #auto:
169
+ # keepkey: "@bitcoinkeepkey"
170
+ # ethereum: "ethereum"
171
+ # pets:
172
+ # - buzzfeedanimals
173
+ # - Duchess
174
+ # - Princess
175
+ # - Athos
176
+
177
+ ```
178
+
179
+ Here's another one, cleaned-up:
180
+
181
+ ```yaml
182
+ tweetsert:
183
+ enabled: true
184
+ layout: "post"
185
+ debug: false
186
+
187
+ title:
188
+ prefix: "[Tweet] "
189
+ words: 9
190
+ suffix: " ..."
191
+
192
+ properties:
193
+ is_tweet: true
194
+ tweet_html: $
195
+ share: false
196
+ comments: true
197
+
198
+ timeline:
199
+ handle: 'ibrado'
200
+
201
+ handles:
202
+ - 'somehandle'
203
+ - 'anotherhandle'
204
+
205
+ access_token: "12345678-aBcDeFgHiJkLmNoPqRsTuVwXyZajni01234567890"
206
+ limit: 100
207
+
208
+ replies: false
209
+ retweets: true
210
+
211
+ #include:
212
+ # - '#blogimport'
213
+
214
+ exclude:
215
+ - 'https://example.org/\d+/'
216
+ - '^.@'
217
+
218
+ no_newer: true
219
+ no_older: false
220
+
221
+ embed:
222
+ excerpts: true
223
+ theme: "dark"
224
+ link_color: "#80FF80"
225
+ omit_script: false
226
+
227
+ category:
228
+ default: "tweets"
229
+ dir: ""
230
+
231
+ layout: "category_index"
232
+ title:
233
+ prefix: "Posts in the &laquo;"
234
+ suffix: "&raquo; category"
235
+
236
+ tags:
237
+ default: "tweet"
238
+ dir: "tag"
239
+
240
+ layout: "tag_index"
241
+ title:
242
+ prefix: "Posts tagged &ldquo;"
243
+ suffix: "&rdquo;"
244
+
245
+ hashtags: true
246
+ ignore:
247
+ - "blahblah"
248
+
249
+ auto:
250
+ keepkey: "@bitcoinkeepkey"
251
+ cryptocurrency: [ "bitcoin", "ethereum", "litecoin" ]
252
+ ethereum:
253
+ - "ethereum"
254
+ - "@ethereumproject"
255
+
256
+
257
+ ```
258
+
259
+ ## Cache
260
+
261
+ *Tweetsert* caches Twitter's timelines and oEmbed results in a hidden folder, `.tweetsert-cache`. You may delete this if you encounter problems that you think might be related to the cache.
262
+
263
+ ## Further configuration
264
+
265
+ The embedded tweet is wrapped inside a `<div class="jekyll-tweetsert">`. You may adjust its appearance via CSS:
266
+
267
+ ```css
268
+ .jekyll-tweetsert {
269
+ clear: both;
270
+ width: auto;
271
+ margin-left: auto;
272
+ margin-right: auto;
273
+ max-width: max-content;
274
+ }
275
+ ```
276
+
277
+ If you'd rather access the embedded tweet directly, use a property:
278
+
279
+ ```yaml
280
+ properties:
281
+ tweet_html: $
282
+ ```
283
+
284
+ and include it as `{{ post.tweet_html }}` or `{{ page.tweet_html }}`
285
+
286
+ You may also want to edit your `home` layout to make the imported tweets look different from the regular ones, for instance,
287
+
288
+ ```html
289
+ {% for post in site.posts %}
290
+ {% if post.tags contains "tweet" %}
291
+ <br/>
292
+ {% else %}
293
+ <!-- normal post header -->
294
+ {% endif %}
295
+ {% endfor %}
296
+ ```
297
+
298
+ See the [author's blog](https://ibrado.org) for a demo.
299
+
300
+ ## Contributing
301
+
302
+ 1. Fork this project: [https://github.com/ibrado/jekyll-tweetsert/fork](https://github.com/ibrado/jekyll-tweetsert/fork)
303
+ 1. Clone it (`git clone git://github.com/your_user_name/jekyll-tweetsert.git`)
304
+ 1. `cd jekyll-tweetsert`
305
+ 1. Create a new branch (e.g. `git checkout -b my-bug-fix`)
306
+ 1. Make your changes
307
+ 1. Commit your changes (`git commit -m "Bug fix"`)
308
+ 1. Build it (`gem build jekyll-tweetsert.gemspec`)
309
+ 1. Install and test it (`gem install ./jekyll-tweetsert-*.gem`)
310
+ 1. Repeat from step 3 as necessary
311
+ 1. Push the branch (`git push -u origin my-bug-fix`)
312
+ 1. Create a Pull Request, making sure to select the proper branch, e.g. `my-bug-fix` (via https://github.com/*your_user_name*/jekyll-tweetsert)
313
+
314
+ Bug reports and pull requests are welcome on GitHub at [https://github.com/ibrado/jekyll-tweetsert](https://github.com/ibrado/jekyll-tweetsert). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
315
+
316
+ ## License
317
+
318
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
319
+
320
+ ## Code of Conduct
321
+ Everyone interacting in the Jekyll::Tweetsert project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/jekyll-tweetsert/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,28 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "jekyll/tweetsert/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "jekyll-tweetsert"
8
+ spec.version = Jekyll::Tweetsert::VERSION
9
+ spec.authors = ["Alex Ibrado"]
10
+ spec.email = ["alex@ibrado.org"]
11
+
12
+ spec.summary = %q{Tweetsert: tweet post generator for Jekyll}
13
+ spec.description = %q{This plugin retrieves tweets from one or more Twitter timelines and inserts them as posts. The tweets may be filtered by content and date, hashtags may be imported, and posts can be automatically categorized or tagged, by default or depending on content. Dark/light themes and custom link colors are supported.}
14
+ spec.homepage = "https://github.com/ibrado/jekyll-tweetsert"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.16"
25
+
26
+ spec.add_runtime_dependency "api_cache", "~> 0.3"
27
+ spec.add_runtime_dependency "moneta", "~> 1.0"
28
+ end
@@ -0,0 +1,439 @@
1
+ require "jekyll/tweetsert/version"
2
+ require 'net/http'
3
+ require "uri"
4
+ require "cgi"
5
+ require "json"
6
+ require "digest"
7
+ require "api_cache"
8
+ require "moneta"
9
+
10
+ module Jekyll
11
+ module Tweetsert
12
+ REQUEST_SIGNER = "https://hook.io/tweetsert/sign".freeze
13
+ TWITTER_OEMBED_API = "https://publish.twitter.com/oembed".freeze
14
+ DEFAULT_REQUEST_HEADERS = { "User-Agent": "Jekyll Tweetsert Plugin/#{VERSION}" }.freeze
15
+
16
+ =begin
17
+ TODO: Move stuff here
18
+ class TweetPost < Jekyll::Document
19
+ def initialize(path, site, docs, date, id, content)
20
+ @path = path
21
+ @site = site
22
+ @collection = docs
23
+
24
+ self.data['date'] = date
25
+ self.data['title'] = "Tweet #{id}"
26
+ self.content = content
27
+ end
28
+ end
29
+ =end
30
+
31
+ def self.debug_state(state)
32
+ @debug = state
33
+ end
34
+
35
+ def self.debug(msg)
36
+ puts "DEBUG> #{msg}" if @debug
37
+ end
38
+
39
+ def self.info(msg)
40
+ Jekyll.logger.info "Tweetsert:", msg
41
+ end
42
+
43
+ def self.warn(msg)
44
+ Jekyll.logger.warn "Tweetsert:", msg
45
+ end
46
+
47
+ def self.error(msg)
48
+ Jekyll.logger.error "Tweetsert:", msg
49
+ end
50
+
51
+ def self.backtrace(e)
52
+ puts e.backtrace if @debug
53
+ end
54
+
55
+ class TweetIndex < Jekyll::Page
56
+ def initialize(site, dir, value)
57
+ @site = site
58
+ @dir = dir
59
+ @base = @site.source
60
+ @name = 'index.html'
61
+ @value = value
62
+
63
+ @config ||= @type
64
+
65
+ self.process(@name)
66
+
67
+ idx_config = site.config['tweetsert'][@config] || {}
68
+
69
+ idx_layout = idx_config["layout"] || @type+"_index"
70
+
71
+ if site.layouts.key?(idx_layout)
72
+ layout_file = idx_layout + site.layouts[idx_layout].ext
73
+ @layout = idx_layout
74
+ end
75
+
76
+ if !@layout.nil?
77
+ self.read_yaml(File.join(@base, '_layouts'), layout_file)
78
+ self.data[@type] = @value
79
+
80
+ prefix = idx_config.has_key?("title") ? idx_config['title']['prefix'] : ""
81
+ suffix = idx_config.has_key?("title") ? idx_config['title']['suffix'] : ""
82
+
83
+ self.data['title'] = prefix + @value + suffix
84
+ end
85
+ end
86
+
87
+ def generate()
88
+ if @layout.nil?
89
+ Tweetsert::warn "#{@type} layout for #{@value} not found"
90
+ else
91
+ self.render(@site.layouts, @site.site_payload)
92
+ self.write(@site.dest)
93
+ @site.pages << self
94
+ end
95
+ end
96
+ end
97
+
98
+ class TweetCategoryIndex < TweetIndex
99
+ def initialize(site, dir, value)
100
+ @type = "category"
101
+ super
102
+ end
103
+ end
104
+
105
+ class TweetTagIndex < TweetIndex
106
+ def initialize(site, dir, value)
107
+ @config = "tags"
108
+ @type = "tag"
109
+ super
110
+ end
111
+ end
112
+
113
+
114
+ class Generator < Jekyll::Generator
115
+
116
+ def generate(site)
117
+ config = site.config["tweetsert"]
118
+
119
+ if config.nil? || !config["enabled"]
120
+ return
121
+ end
122
+
123
+ Tweetsert::debug_state config["debug"]
124
+
125
+ if !config.has_key?("timeline")
126
+ Tweetsert::error "Timeline configuration not found"
127
+ return
128
+ end
129
+
130
+ timeline = config["timeline"]
131
+ if !timeline.has_key?("access_token") && !ENV['JTP_ACCESS_TOKEN']
132
+ Tweetsert::error "Cannot retrieve timelines without access_token"
133
+ Tweetsert::error " Go to http://tweetsert.hook.io/ to get one"
134
+ return
135
+ end
136
+
137
+ @access_token = ENV['JTP_ACCESS_TOKEN'] || timeline["access_token"]
138
+
139
+ APICache.store = Moneta.new(:File, dir: './.tweetsert-cache')
140
+
141
+ no_newer = timeline['no_newer'] || timeline['no_newer'].nil?
142
+ no_older = timeline['no_older'] || timeline['no_older'].nil?
143
+
144
+ if no_newer || no_older
145
+ # Find timeframe, i.e. earliest and latest posts
146
+
147
+ # Random(?) future date
148
+ oldest = DateTime.new(2974,1,30)
149
+ newest = DateTime.new()
150
+
151
+ # "posts.each should be changed to posts.docs.each"
152
+ # TODO? Support older Jekyll versions
153
+ site.posts.docs.each do |post|
154
+ timestamp = post.data["date"].to_datetime
155
+ # All posts have dates or Jekyll will stop
156
+ oldest = [oldest, timestamp].min
157
+ newest = [newest, timestamp].max
158
+ end
159
+ end
160
+
161
+ oldest = DateTime.new() if !no_older || site.posts.docs.empty?
162
+ newest = DateTime.now() if !no_newer || site.posts.docs.empty?
163
+
164
+ handles = [ timeline['handle'], timeline["handles"] ].flatten.compact;
165
+
166
+ cat_config = config["category"] || {}
167
+ category = cat_config['default'] || ""
168
+
169
+ tags_config = config["tags"] || {}
170
+
171
+ includes = timeline["include"].reject { |w| w.nil? } if timeline["include"]
172
+ excludes = timeline["exclude"].reject { |w| w.nil? } if timeline["exclude"]
173
+
174
+ options = {
175
+ oldest: oldest,
176
+ newest: newest,
177
+ limit: timeline["limit"] || 100,
178
+ title: config["title"],
179
+ excerpts: timeline["excerpts"].nil? || timeline["excerpts"],
180
+ category: category,
181
+ dir: tags_config["dir"],
182
+ layout: config["layout"] || 'post',
183
+ tag_index: tags_config["layout"],
184
+ replies: timeline["replies"] ? '1' : '0',
185
+ retweets: timeline["retweets"] ? '1' : '0',
186
+ hashtags: tags_config["hashtags"],
187
+ default_tag: tags_config["default"],
188
+ ignore_tags: tags_config["ignore"] || [],
189
+ auto_tags: tags_config["auto"] || {},
190
+ inclusions: includes,
191
+ exclusions: excludes,
192
+ embed: config["embed"] || {},
193
+ properties: config["properties"] || {}
194
+ }
195
+
196
+ begin
197
+ cat_count = 0
198
+ handles.each do |handle|
199
+ counts = generate_posts(site, handle, options)
200
+ msg = "#{handle}: Generated #{counts[:posts].to_s} post(s), #{counts[:tags].to_s} tag(s)"
201
+ if !category.empty?
202
+ make_cat_index(site, cat_config["dir"] || "categories", category)
203
+ msg += ", 1 category" if !counts[:posts].zero? && cat_count.zero?
204
+ cat_count = 1
205
+ end
206
+ msg += "; excluded #{counts[:excluded].to_s} tweet(s)"
207
+ Tweetsert::info msg
208
+ end
209
+
210
+ rescue Exception => e
211
+ ln = e.backtrace[0].split(':')[1]
212
+ Tweetsert::error "#{e.message} at line #{ln}"
213
+ Tweetsert::backtrace e
214
+ throw e
215
+ end
216
+
217
+ end
218
+
219
+ private
220
+ def md5
221
+ return @md5 ||= Digest::MD5::new
222
+ end
223
+
224
+ private
225
+ def make_tag_index(site, dir, tag)
226
+ TweetTagIndex.new(site, File.join(dir, tag), tag).generate()
227
+ end
228
+
229
+ private
230
+ def make_cat_index(site, dir, category)
231
+ TweetCategoryIndex.new(site, File.join(dir, category), category).generate()
232
+ end
233
+
234
+ private
235
+ def retrieve(type, url, params, headers, cache)
236
+ uri = URI(url)
237
+
238
+ qs = params.map{ |a| a.join('=') }.join('&')
239
+ qs += (qs ? '' : '&') + uri.query if uri.query
240
+ qs = '?'+qs if qs
241
+
242
+ md5.reset
243
+ md5 << type+qs
244
+
245
+ unique_type = type + "-" + md5.hexdigest
246
+
247
+ APICache.get(unique_type, { :cache => cache, :fail => {} }) do
248
+ Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https' ) do |http|
249
+ req = Net::HTTP::Get.new(uri.path + qs)
250
+ headers.merge!(DEFAULT_REQUEST_HEADERS).each { |k, v| req[k] = v }
251
+
252
+ response = http.request(req)
253
+
254
+ case response
255
+ when Net::HTTPSuccess
256
+ JSON.parse(response.body)
257
+ when Net::HTTPUnauthorized
258
+ Jekyll::Tweetsert::warn "Unauthorized: check token"
259
+ {}
260
+ when Net::HTTPNotFound
261
+ Jekyll::Tweetsert::warn "Not found: check handle"
262
+ {}
263
+ else
264
+ Jekyll::Tweetsert::error "Unknown response"
265
+ Jekyll::Tweetsert::error " #{response.inspect}"
266
+ {}
267
+ end
268
+ end
269
+ end
270
+ end
271
+
272
+ private
273
+ def sign_timeline_request(params)
274
+ uri = URI(REQUEST_SIGNER)
275
+
276
+ qs = params.map{ |a| a.join('=') }.join('&')
277
+ qs = '?'+qs unless qs.empty?
278
+
279
+ Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
280
+ req = Net::HTTP::Get.new(uri.path + qs)
281
+ req['X-JTP-Access-Token'] = @access_token
282
+
283
+ response = http.request(req)
284
+
285
+ case response
286
+ when Net::HTTPSuccess
287
+ # contains url and auth
288
+ JSON.parse(response.body)
289
+ else
290
+ Tweetsert::warn "Unable to sign request"
291
+ Tweetsert::debug " #{response.inspect}"
292
+ end
293
+ end
294
+ end
295
+
296
+ private
297
+ def generate_posts(site, handle, o)
298
+ params = {
299
+ handle: handle,
300
+ limit: o[:limit],
301
+ replies: o[:replies],
302
+ retweets: o[:retweets],
303
+ }
304
+
305
+ signed = sign_timeline_request(params)
306
+ if signed.nil?
307
+ Tweetsert::error "Cannot retrieve timeline of #{o[:handle]}"
308
+ return
309
+ end
310
+
311
+ post_count = 0
312
+ tag_count = 0
313
+ exclude_count = 0
314
+
315
+ if tweets = retrieve('timeline', signed["url"], {}, { "Authorization" => signed["auth"] }, 5)
316
+ seen_tags = {}
317
+ tweets.select { |tweet|
318
+ urls = tweet["entities"]["urls"].map { |url| url["expanded_url"] }.join(" ")
319
+
320
+ tweet['timestamp'] = DateTime.parse(tweet["created_at"]).new_offset(DateTime.now.offset)
321
+
322
+ excluded = (tweet["timestamp"] > o[:newest]) || (tweet["timestamp"] < o[:oldest])
323
+
324
+ if !excluded && o[:inclusions]
325
+ excluded = !(o[:inclusions].any? { |w| tweet["full_text"] =~ /([\b#\@]?)#{w}\b/i } ||
326
+ o[:inclusions].any? { |w| urls =~ /\b#{w}/i })
327
+ end
328
+
329
+ if !excluded && o[:exclusions]
330
+ excluded = o[:exclusions].any? { |w| tweet["full_text"] =~ /([\b#\@]?)#{w}\b/i } ||
331
+ o[:exclusions].any? { |w| urls =~ /\b#{w}/i }
332
+ end
333
+
334
+ exclude_count += 1 if excluded
335
+ !excluded
336
+
337
+ }.each do |tweet|
338
+
339
+ id = tweet["id"].to_s
340
+ params = {
341
+ url: "https://twitter.com/#{handle}/status/#{id}",
342
+ theme: o[:embed]['theme'] || "light",
343
+ link_color: o[:embed]["link_color"],
344
+ omit_script: o[:embed]["omit_script"]
345
+ }
346
+
347
+ if oembed = retrieve('oembed', TWITTER_OEMBED_API, params, {}, 864000)
348
+
349
+ # TODO Move stuff over to TweetPost class
350
+
351
+ t = o[:title] || {}
352
+ prefix = t["prefix"] || ""
353
+ words = t["words"] || 10
354
+ suffix = t["suffix"] || ""
355
+ smart = t["smart"]
356
+
357
+ word_limit = (words > 1 ? words - 1 : 9)
358
+
359
+ title_base = tweet["full_text"].gsub(/https?:\/\/\S+/, '').
360
+ split(/\s+/).slice(0 .. word_limit).join(' ') || "Tweet "+id
361
+
362
+ m = /^(.*[\.\!\?])[\b\s$]/.match(title_base)
363
+ title_base = m[1] if m
364
+
365
+ suffix = "" if title_base.eql?(tweet['full_text'])
366
+
367
+ name = (prefix + title_base).gsub(/[^a-z0-9\-\ ]+/i, '').
368
+ gsub(' ', '-').downcase + ".html"
369
+
370
+ tweetpost = Jekyll::Document.new(File.join(site.source, o[:category], name),
371
+ { :site => site, :collection => site.posts })
372
+
373
+ tweetpost.content = '<div class="jekyll-tweetsert">' + oembed["html"] + '</div>'
374
+
375
+ tweetpost.data["title"] = prefix + title_base + suffix
376
+
377
+ tweetpost.data["date"] = tweet['timestamp'].to_time
378
+ tweetpost.data["layout"] = o[:layout]
379
+
380
+ if o[:embed]["excerpts"].nil? || o[:embed]["excerpts"]
381
+ tweetpost.data["excerpt"] = Jekyll::Excerpt.new(tweetpost)
382
+ end
383
+
384
+ tweet_tags = [o[:default_tag]].compact
385
+
386
+ plain_text = tweet["full_text"].downcase.gsub(/&\S[^;]+;/, '');
387
+
388
+ if o[:hashtags]
389
+ tweet_tags << plain_text.scan(/[^&]*?#([A-Z0-9_]+)/i).flatten || []
390
+ tweet_tags.flatten!
391
+ tweet_tags -= o[:ignore_tags].flatten
392
+ end
393
+
394
+ o[:auto_tags].each do |tag, pat|
395
+ [ pat ].flatten.compact.each do |re|
396
+ if plain_text.match(/#{Regexp.escape(re)}/i) && !tweet_tags.include?(tag)
397
+ tweet_tags << tag
398
+ end
399
+ end
400
+ end
401
+
402
+ tweetpost.data["tags"] = tweet_tags
403
+ tweetpost.data["category"] = o[:category]
404
+
405
+ o[:properties].each do |prop, value|
406
+ if value == '$'
407
+ tweetpost.data[prop] = oembed['html']
408
+ else
409
+ tweetpost.data[prop] = value
410
+ end
411
+ end
412
+
413
+ site.posts.docs << tweetpost
414
+
415
+ # Create the tag index file
416
+ tweetpost.data["tags"].each do |tag|
417
+ make_tag_index(site, o[:dir] || "tag", tag) if o[:tag_index]
418
+ if !seen_tags.has_key?(tag)
419
+ tag_count += 1
420
+ seen_tags[o[:default_tag]] = 1
421
+ end
422
+ end
423
+
424
+ post_count += 1
425
+ end
426
+ end
427
+ end
428
+
429
+ return {
430
+ :posts => post_count,
431
+ :tags => tag_count,
432
+ :excluded => exclude_count
433
+ }
434
+
435
+ end
436
+
437
+ end
438
+ end
439
+ end
@@ -0,0 +1,5 @@
1
+ module Jekyll
2
+ module Tweetsert
3
+ VERSION = "1.0.0"
4
+ end
5
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: jekyll-tweetsert
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Alex Ibrado
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-12-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: api_cache
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.3'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: moneta
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.0'
55
+ description: This plugin retrieves tweets from one or more Twitter timelines and inserts
56
+ them as posts. The tweets may be filtered by content and date, hashtags may be imported,
57
+ and posts can be automatically categorized or tagged, by default or depending on
58
+ content. Dark/light themes and custom link colors are supported.
59
+ email:
60
+ - alex@ibrado.org
61
+ executables: []
62
+ extensions: []
63
+ extra_rdoc_files: []
64
+ files:
65
+ - ".gitignore"
66
+ - ".rspec"
67
+ - ".travis.yml"
68
+ - CODE_OF_CONDUCT.md
69
+ - Gemfile
70
+ - LICENSE.txt
71
+ - README.md
72
+ - bin/setup
73
+ - jekyll-tweetsert.gemspec
74
+ - lib/jekyll/tweetsert.rb
75
+ - lib/jekyll/tweetsert/version.rb
76
+ homepage: https://github.com/ibrado/jekyll-tweetsert
77
+ licenses:
78
+ - MIT
79
+ metadata: {}
80
+ post_install_message:
81
+ rdoc_options: []
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ required_rubygems_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ requirements: []
95
+ rubyforge_project:
96
+ rubygems_version: 2.5.1
97
+ signing_key:
98
+ specification_version: 4
99
+ summary: 'Tweetsert: tweet post generator for Jekyll'
100
+ test_files: []