subs 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: facdb8dca51a4b869a8a9e2a5fdb3e080f74233bbe2bb31623fdf8936fd5140a
4
+ data.tar.gz: 591083900e3632a7f02baecbdec45b71a0c6591db930a3c384d4388e9d8f40c7
5
+ SHA512:
6
+ metadata.gz: c51953160fc97bfe8fa880e3048b89059674723edd572b2a509c5099e19b10bc27b5f69441c4d4b5b6620eb3eae87cdf12ca930c83afd690a2db8e5112dd77a8
7
+ data.tar.gz: ec3192fe49b366d8c7c1657bfe36a3a1da17c7f7e43a33627b55c35e69fc2a2787fc98e623fb7a73e10dd41289f4f4fb09124a960186d54dba26f51500f8aad6
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /.idea
5
+ /.vs
6
+ /.vscode
7
+ /coverage/
8
+ /doc/
9
+ /pkg/
10
+ /spec/reports/
11
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 2.0.1
@@ -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 efreed09@gmail.com. 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,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Gem dependencies specified in in subs.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 ForeverZer0
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.
data/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # Subs
2
+
3
+ Subs aims for making fetching subtitles for all your favorite movies and television shows a few keystrokes away using a simple and intuitive command-line interface. It uses multiple search algorithms for determining the best matching subtitle for video files that it finds, including using provider hashing algorithms (preferred), filename and name, and IMDb IDs.
4
+
5
+ It currently ships with two primary providers that it can utilize, [SubDB](http://thesubdb.com/) and [OpenSubtitles](https://www.opensubtitles.org), as they both are open-source, and contain some of the largest collections of subtitles available anywhere. They both also expose a public API and custom hashing algorithm to drastically increase quality of results, and are much faster and more accurate than web-scraping. More providers will likely be added in the future.
6
+
7
+ Subs also comes with a utility for easily re-syncing existing SubRip (.srt) subtitle files if they do not match the video audio exactly. This feature is often included in video players, but this will allow for permanently saving the file with the corrected offset extremely easily.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'subs'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install subs
24
+
25
+ ## Usage
26
+
27
+ Once installed, open a terminal/command window and use the following basic syntax:
28
+ ```
29
+ subs COMMAND [ARGUMENTS] [OPTIONS]
30
+ ```
31
+
32
+ Subs can run in a fully-automatic mode that will recursively search folders for video files, find matching subtitles, and download/rename them appropriately, or fully-manual one file at a time and you select the subtitle from a list, or anywhere in between, the choice is yours.
33
+
34
+ You are encouraged to the view the [Wiki](https://github.com/ForeverZer0/subs/wiki) for a full explanation of each command, but to quickly see a list of available commands, use the following command:
35
+ ```
36
+ subs --help
37
+ ```
38
+ or...
39
+ ```
40
+ subs --help COMMAND
41
+ ```
42
+ ...to see a brief explanation of the specified command and its options.
43
+
44
+
45
+ ## Contributing
46
+
47
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ForeverZer0/subs. 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.
48
+
49
+ ## License
50
+
51
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
52
+
53
+ ## Code of Conduct
54
+
55
+ Everyone interacting in the Subs project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/osdb_client/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
data/bin/subs ADDED
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'thor'
4
+ require 'json'
5
+ require_relative '../lib/subs'
6
+
7
+ module Subs
8
+ class CLI < Thor
9
+
10
+ class_option :version, type: :boolean, desc: 'Display version string', aliases: '-v'
11
+ class_option :quiet, type: :boolean, desc: 'Do not show any output', aliases: '-q'
12
+ class_option :debug, type: :boolean, desc: 'Show more verbose output', aliases: '-d'
13
+
14
+ if Dir.exist?(File.expand_path('~/.config'))
15
+ CONFIG_PATH = File.expand_path('~/.config/subs.json')
16
+ else
17
+ CONFIG_PATH = File.expand_path('~/.subs')
18
+ end
19
+
20
+ PROVIDERS = [SubDB, OpenSubtitles]
21
+
22
+ def initialize(*args)
23
+ super(*args)
24
+
25
+ if options[:quiet]
26
+ Subs.create_log(STDOUT, :fatal)
27
+ elsif options[:debug]
28
+ Subs.create_log(STDOUT, :debug)
29
+ end
30
+
31
+ if options[:version] != options[:quiet]
32
+ say "Subs v.#{Subs::VERSION}"
33
+ end
34
+
35
+ begin
36
+ @config = JSON.parse(File.read(CONFIG_PATH), symbolize_names: true)
37
+ Subs.log.debug { "Configuration loaded successfully" }
38
+ rescue
39
+ Subs.log.debug { "Failed to load user configuration, using default" }
40
+ @config = default_config
41
+ File.open(CONFIG_PATH, 'wb') { |io| io.write(JSON.pretty_generate(@config)) } rescue nil
42
+ end
43
+ end
44
+
45
+ desc 'find [PATH1 [,PATH2]]... [OPTIONS]', 'Input file/directory path(s) that video files will be searched for'
46
+ method_option :recursive, type: :boolean, desc: 'Search directories recursively', aliases: '-r', default: false
47
+ method_option :clobber, type: :boolean, desc: 'Overwrite existing subtitles', aliases: '-c', default: false
48
+ method_option :auto, type: :boolean, desc: 'Automatically select best match and fetch without prompt', aliases: '-a', default: true
49
+ method_option :method, type: :string, desc: 'Sets the search method', aliases: '-m', enum: %w(hash name any), default: 'hash'
50
+ method_option :provider, type: :string, desc: 'Set which subtitles provider(s) are used', aliases: '-p', enum: %w(all subdb osdb), default: 'all'
51
+ method_option :language, type: :string, desc: 'ISO-639 language code for desired subtitle language', aliases: '-l'
52
+ method_option :test, type: :boolean, desc: 'Perform a dry-run without writing anything to disk', aliases: '-t'
53
+ def find(*paths)
54
+ # Compile list of videos to process
55
+ paths.push(Dir.pwd) if paths.empty?
56
+ videos = build_video_list(*paths)
57
+ # Parse our arguments
58
+ language = get_language(options[:language] || @config[:language])
59
+ providers = get_providers(options[:provider])
60
+ Subs.log.info { "Found #{videos.size.to_s.light_blue} videos to query"}
61
+ # Perform search
62
+ results = {}
63
+ videos.each do |video|
64
+ # Skip searching for videos that already have subtitles unless --clobber flag was passed
65
+ if !options[:clobber] && Subs.subtitle_exist?(video, language)
66
+ Subs.log.info { "Skipping #{File.basename(video).yellow}" }
67
+ next
68
+ end
69
+ # Create instance of each provider, and apply specified search methods for each
70
+ results[video] = []
71
+ providers.each do |klass|
72
+ klass.new do |provider|
73
+ results[video] += search(provider, video, language, options[:method].to_sym)
74
+ end
75
+ end
76
+ Subs.log.info { "Found #{results[video].size.to_s.light_blue} results for #{File.basename(video).yellow}"}
77
+ end
78
+ process_results(results)
79
+ end
80
+
81
+ desc 'sync <path> [+|-]<ms>', 'Offsets SubRip subtitle timings by number of milliseconds'
82
+ method_option :backup, type: :boolean, desc: 'Backup original file', aliases: '-b'
83
+ def sync(path, ms)
84
+ unless File.exist?(path)
85
+ Subs.log.error { "Cannot resolve path '#{path}'"}
86
+ return
87
+ end
88
+ return if options[:backup] && !backup_file(path)
89
+ match = /^([+-])?(\d+)$/.match(ms)
90
+ unless match
91
+ Subs.log.error { "Invalid offset parameter #{ms}".red }
92
+ exit
93
+ end
94
+ offset = Integer(ms)
95
+ regex = /^(\d{2}):(\d{2}):(\d{2}),(\d+) --> (\d{2}):(\d{2}):(\d{2}),(\d+)$/
96
+ buffer = StringIO.new
97
+
98
+ begin
99
+ File.open(path, 'rb').each do |line|
100
+
101
+ match = regex.match(line)
102
+ unless match
103
+ buffer.write(line)
104
+ next
105
+ end
106
+
107
+ t1 = Subs::SubRipTime.new(*match[1..4].map(&:to_i)) + offset
108
+ t2 = Subs::SubRipTime.new(*match[5..8].map(&:to_i)) + offset
109
+ buffer.write("#{t1} --> #{t2}\n")
110
+ end
111
+
112
+ buffer.seek(0, IO::SEEK_SET)
113
+ File.open(path, 'wb') { |io| io.write(buffer.read) }
114
+ rescue
115
+ Subs.log.error { "Error occurred during subtilte re-sync".red }
116
+ end
117
+ end
118
+
119
+ desc 'config <name> <value>', 'Sets and stores a configuration option to persist across each run'
120
+ def config(name, value)
121
+ begin
122
+ key = name.to_sym
123
+ if value.nil? && @config.has_key?(key)
124
+ @config.delete(key)
125
+ return
126
+ end
127
+ @config[key] = value
128
+ File.open(CONFIG_PATH, 'wb') { |io| io.write(JSON.pretty_generate(@config)) }
129
+ rescue
130
+ Subs.log.error { 'Error occurred setting configuration option' }
131
+ end
132
+ end
133
+
134
+ no_commands do
135
+
136
+ def default_config
137
+ # Make half-attempt at getting the actual system language, otherwise just go with English
138
+ begin
139
+ env = ENV['LANG']
140
+ match = /([a-z]{2})_[A-Z][A-Z]\..+/.match(env)
141
+ language = Language.from_alpha2(match[1]).alpha3
142
+ rescue
143
+ language = 'eng'
144
+ end
145
+ {
146
+ language: language,
147
+ credentials: {}
148
+ }
149
+ end
150
+
151
+ def build_video_list(*paths)
152
+ videos = []
153
+ paths.each do |path|
154
+ if File.directory?(path)
155
+ videos += Subs.video_search(path, options[:recursive])
156
+ elsif File.exist?(path)
157
+ ext = File.extname(path)
158
+ Subs.log.warn { "Unrecognized video extension: ''#{ext}''" } unless Subs::VIDEO_EXTENSIONS.include?(ext)
159
+ videos << File.expand_path(path)
160
+ else
161
+ Subs.log.warn { "Unable to resolve path '#{path}', skipping" }
162
+ end
163
+ end
164
+ videos
165
+ end
166
+
167
+ def prune_list(videos)
168
+ # Reject videos that already have subtitles unless "clobber" option is present
169
+ count = videos.count
170
+ videos.reject! { |v| Subs.subtitle_exist?(v, *options[:lang]) }
171
+ if videos.count != count
172
+ diff = count - videos.count
173
+ Subs.log.info { "Existing subtitles found for #{diff.to_s.light_blue}, skipping." }
174
+ end
175
+ end
176
+
177
+ def backup_file(path)
178
+ unless File.exist?(path)
179
+ Subs.log.error { "Cannot resolve path '#{path}'"}
180
+ return false
181
+ end
182
+ bak = File.expand_path(path) + '.bak'
183
+ if File.exist?(bak)
184
+ Subs.log.debug { "Backup file '#{bak}' already exists" }
185
+ return true
186
+ end
187
+
188
+ begin
189
+ File.open(bak, 'wb') do |dest|
190
+ File.open(path, 'rb') { |src| dest.write(src.read) }
191
+ end
192
+ Subs.log.debug { "Back up of #{path.yellow} was successful" }
193
+ return true
194
+ rescue
195
+ Subs.log.error { "Error occurred during backup of '#{path}'"}
196
+ return false
197
+ end
198
+ end
199
+
200
+ def get_providers(name)
201
+ return case name
202
+ when 'all' then PROVIDERS
203
+ when 'subdb' then [SubDB]
204
+ when 'osdb' then [OpenSubtitles]
205
+ else
206
+ Subs.log.error { "Invalid provider: #{name}" }
207
+ exit
208
+ end
209
+ end
210
+
211
+ def get_language(code)
212
+ code = code || @config[:language]
213
+ iso639 = case code.size
214
+ when 2 then Language.from_alpha2(code)
215
+ when 3 then Language.from_alpha3(code)
216
+ else nil
217
+ end
218
+ unless iso639
219
+ Subs.log.error { "Unsupported language code specified: #{code}"}
220
+ exit
221
+ end
222
+ iso639
223
+ end
224
+
225
+ def search(provider, video, language, method)
226
+ results = []
227
+ # Search by hash if :hash or :any flag
228
+ if provider.is_a?(HashSearcher) && (method == :hash || method == :any)
229
+ results += provider.hash_search(video, language)
230
+ end
231
+ # Search by filename if :name flag, or :any flag and hash search failed
232
+ if provider.is_a?(FilenameSearcher) && (method == :name || (method == :any && results.empty?))
233
+ results += provider.filename_search(video, language)
234
+ end
235
+ results
236
+ end
237
+
238
+ def process_results(results)
239
+ choices = []
240
+ results.each_pair do |video, list|
241
+ # Continue if no results for video
242
+ next if list.empty?
243
+ # Pick the first result (most probable) if --auto switch is set
244
+ if options[:auto]
245
+ choices << list.first
246
+ next
247
+ end
248
+ say
249
+ say "Select subtitle for #{File.basename(video).yellow}"
250
+ list.each_with_index do |result, i|
251
+ puts " #{(i + 1).to_s.rjust(2).light_blue}. #{result.name} (#{result.provider_name.blue})"
252
+ end
253
+ say
254
+ input = ask 'Input number of choice, or leave blank to skip: '
255
+ i = input.chomp.strip.to_i rescue 0
256
+ choices << list[i - 1] if i > 0
257
+ end
258
+ # Process the pruned results
259
+ process_choices(choices.compact)
260
+ end
261
+
262
+ def process_choices(results)
263
+ Subs.log.info { "Processing #{results.size.to_s.light_blue} results..." }
264
+ # Group results by which provider they use
265
+ results.group_by(&:provider).each_pair do |klass, list|
266
+ klass.new do |provider|
267
+ # Instantiate the provider and process the results
268
+ list.each do |result|
269
+ name = File.basename(result.video).yellow
270
+ begin
271
+ path = Subs.build_subtitle_path(result.video, result.language)
272
+ File.open(path, 'wb') { |io| provider.process_result(io, result) }
273
+ Subs.log.info { " Successfully processed #{name}".green }
274
+ rescue
275
+ Subs.log.error { " Failed to process #{name}".red }
276
+ end
277
+ end
278
+ end
279
+ end
280
+ Subs.log.info { "Processing complete" }
281
+ end
282
+ end
283
+ end
284
+ end
285
+
286
+ Subs::CLI.start(ARGV)