opencode_theme 1.0.5 → 1.0.6

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: b40ffbbf958c96b139e37649102ca426546b89e3
4
- data.tar.gz: e9064f63f91859eb35393adde6732e8f0413f75a
3
+ metadata.gz: 3b31d3bda90a5294781ad0976e613e1d8aad3a86
4
+ data.tar.gz: 0c527af5921856b60d29db88cb1a7457fe25f982
5
5
  SHA512:
6
- metadata.gz: b026b76a48e6b421248e486d31a8dacb9d94892db9989a280acae35d883cc9f6d3ab21827c9cf516bc07059fb9719418495a7f0e5f07e488b42a06f82de48850
7
- data.tar.gz: 229162fd62a8df3dbda8b07fae86e13067c8d1ea7c4762f1adfa60295a786a3f6dab17c3d06b44becd7f04c963edb41a61b66d84f85f2f14b5d9bc222f83086c
6
+ metadata.gz: 05dbbb461ccd12335fa79189680c628c79d3b6705062e780d4cee9fc49cf4a951628ee94d662d6d05f0a476ffa78b50bd557ab1627d45873badf8c4b402fe37d
7
+ data.tar.gz: 9349963d73f29cbc2e5d90692fe8624b5c613c0cb5a95ec9c8fe11fdd65909be980523b42df4c03f2dd8b90d627cea6ffee318fb4c52e18abe9259d296479b6c
data/bin/opencode CHANGED
@@ -8,7 +8,7 @@ def fallback_load_path(path)
8
8
  yield
9
9
  rescue LoadError
10
10
  unless retried
11
- $: << path
11
+ $LOAD_PATH << path
12
12
  retried = true
13
13
  retry
14
14
  end
@@ -19,4 +19,4 @@ fallback_load_path(File.join(File.dirname(__FILE__), '..', 'lib')) do
19
19
  require 'opencode_theme'
20
20
  require 'opencode_theme/cli'
21
21
  end
22
- OpencodeTheme::Cli.start(ARGV)
22
+ OpencodeTheme::Cli.start(ARGV)
@@ -3,7 +3,7 @@ require 'opencode_theme/base_service'
3
3
 
4
4
  module OpencodeTheme
5
5
 
6
- NOOPParser = Proc.new {|data, format| {} }
6
+ NOOPParser = Proc.new { |data, format| {} }
7
7
  TIMER_RESET = 10
8
8
  PERMIT_LOWER_LIMIT = 3
9
9
  CONFIG_FILE = 'config.yml'
@@ -12,10 +12,6 @@ module OpencodeTheme
12
12
  ENV['test']
13
13
  end
14
14
 
15
- def self.critical_permits?
16
- @@total_api_calls.to_i - @@current_api_call_count.to_i < PERMIT_LOWER_LIMIT
17
- end
18
-
19
15
  def self.passed_api_refresh?
20
16
  delta_seconds > TIMER_RESET
21
17
  end
@@ -40,7 +36,7 @@ module OpencodeTheme
40
36
  config = YAML.load(File.read(CONFIG_FILE))
41
37
  config
42
38
  else
43
- puts "#{CONFIG_FILE} does not exist!" unless test?
39
+ puts "#{CONFIG_FILE} não encontrado!" unless test?
44
40
  {}
45
41
  end
46
42
  end
@@ -71,4 +67,4 @@ module OpencodeTheme
71
67
  (config[:whitelist_files] || []).compact
72
68
  end
73
69
 
74
- end
70
+ end
@@ -1,56 +1,73 @@
1
1
  require 'httparty'
2
+
2
3
  module OpencodeTheme
3
4
  include HTTParty
4
5
  default_options.update(verify: false)
5
6
  @@current_api_call_count = 0
6
- @@total_api_calls = 40
7
7
  URL_API = 'https://opencode.tray.com.br'
8
8
 
9
9
  def self.api_usage
10
- "[API Limit: #{@@current_api_call_count || '??'}/#{@@total_api_calls || '??'}]"
10
+ ''
11
11
  end
12
12
 
13
13
  def self.check_config
14
- response = opencode_theme.post('/api/check', query: { theme_id: config[:theme_id],
15
- gem_version: OpencodeTheme::VERSION })
16
- { success: response.success?, response: JSON.parse(response.body) }
14
+ response = opencode_theme.post('/api/check', query: { theme_id: config[:theme_id], gem_version: OpencodeTheme::VERSION })
15
+ { success: response.success?, response: parser_json(response.body) }
17
16
  end
18
17
 
19
18
  def self.list
20
19
  response = opencode_theme.get('/api/list', query: { gem_version: OpencodeTheme::VERSION })
21
- { success: response.success?, response: JSON.parse(response.body) }
20
+ { success: response.success?, response: parser_json(response.body) }
21
+ end
22
+
23
+ def self.list_opencode_components
24
+ response = opencode_theme.get('/api/themes/'+config[:theme_id]+'/components', query: { gem_version: OpencodeTheme::VERSION })
25
+ { success: response.success?, response: parser_json(response.body) }
26
+ end
27
+
28
+ def self.install_opencode_components(name, user= nil, origin = nil)
29
+ return unless name
30
+ query_default = { gem_version: OpencodeTheme::VERSION }
31
+ query = query_default.merge({ origin: origin, user: user })
32
+ response = opencode_theme.post("/api/themes/#{config[:theme_id]}/components/#{name}/install", query: query)
33
+ response
34
+ end
35
+
36
+ def self.install_opencode_components_notification(name, user= nil, origin = nil)
37
+ return unless name
38
+ query_default = { gem_version: OpencodeTheme::VERSION }
39
+ query = query_default.merge({ origin: origin, user: user, download_component: true })
40
+ opencode_route = "/api/themes/#{config[:theme_id]}/components/#{name}/install/notification"
41
+ response = opencode_theme.post(opencode_route, query: query)
22
42
  end
23
43
 
24
44
  def self.clean
25
- response = opencode_theme.post('/api/clean_cache', query: { theme_id: config[:theme_id],
26
- gem_version: OpencodeTheme::VERSION })
27
- { success: response.success?, response: JSON.parse(response.body) }
45
+ response = opencode_theme.post('/api/clean_cache', query: { theme_id: config[:theme_id], gem_version: OpencodeTheme::VERSION })
46
+ { success: response.success?, response: parser_json(response.body) }
28
47
  end
29
48
 
30
49
  def self.theme_delete(theme_id)
31
50
  response = opencode_theme.delete("/api/themes/#{theme_id}", parser: NOOPParser, query: { gem_version: OpencodeTheme::VERSION })
32
- { success: response.success?, response: JSON.parse(response.body) }
51
+ { success: response.success?, response: parser_json(response.body) }
33
52
  end
34
53
 
35
- def self.theme_new(theme_base, theme_name)
36
- response = opencode_theme.post('/api/themes',
37
- query: { gem_version: OpencodeTheme::VERSION },
38
- body: { theme: { theme_base: theme_name, name: theme_name, gem_version: OpencodeTheme::VERSION } }.to_json,
39
- headers: { 'Content-Type' => 'application/json'},
40
- parser: NOOPParser )
41
- assets = response.code == 200 ? JSON.parse(response.body)["assets"] : {}
42
- { success: response.success?, assets: assets, response: JSON.parse(response.body) }
54
+ def self.theme_new(_theme_base, theme_name)
55
+ response = opencode_theme.post('/api/themes', query: { gem_version: OpencodeTheme::VERSION }, body: { theme: { theme_base: theme_name, name: theme_name, gem_version: OpencodeTheme::VERSION } }.to_json, headers: { 'Content-Type' => 'application/json'}, parser: NOOPParser)
56
+ assets = response.code == 200 ? JSON.parse(response.body)['assets'] : {}
57
+ { success: response.success?, assets: assets, response: parser_json(response.body) }
43
58
  end
44
59
 
45
60
  def self.asset_list
46
61
  response = opencode_theme.get(path, parser: NOOPParser, query: { gem_version: OpencodeTheme::VERSION })
47
- assets = response.code == 200 ? JSON.parse(response.body)['assets'].collect {|a| a['key'][1..a['key'].length] } : response.body
48
- assets
62
+ if response.code == 200
63
+ assets = response.code == 200 ? parser_json(response.body)['assets'].map { |a| a['key'][1..a['key'].length] } : response.body
64
+ assets
65
+ end
49
66
  end
50
67
 
51
68
  def self.get_asset(asset)
52
69
  response = opencode_theme.get(path, query: { key: "/#{asset}", gem_version: OpencodeTheme::VERSION }, parser: NOOPParser)
53
- asset = response.code == 200 ? JSON.parse(response.body) : JSON.parse(response.body)
70
+ asset = parser_json(response.body)
54
71
  asset
55
72
  end
56
73
 
@@ -65,11 +82,15 @@ module OpencodeTheme
65
82
  response
66
83
  end
67
84
 
85
+ def self.parser_json(body)
86
+ JSON.parse(body)
87
+ end
88
+
68
89
  private
69
90
 
70
91
  def self.opencode_theme
71
92
  base_uri URL_API
72
- headers "Authorization" => "Token token=#{config[:api_key]}_#{config[:password]}"
93
+ headers 'Authorization' => "Token token=#{config[:api_key]}_#{config[:password]}"
73
94
  OpencodeTheme
74
95
  end
75
96
  end
@@ -15,38 +15,43 @@ MimeMagic.add('application/font-woff2', extensions: %w(woff2), parents: 'font/op
15
15
  MimeMagic.add('application/vnd.ms-fontobject', extensions: %w(eot), parents: 'font/opentype')
16
16
 
17
17
  module OpencodeTheme
18
+
19
+ module_function
20
+
18
21
  class Cli < Thor
19
22
  include Thor::Actions
20
23
 
21
- IGNORE = %w(config.yml)
22
- DEFAULT_WHITELIST = %w(configs/ css/ elements/ img/ layouts/ pages/ js/)
23
- TIMEFORMAT = '%H:%M:%S'
24
-
25
- tasks.keys.abbrev.each do |shortcut, command|
26
- map shortcut => command.to_sym
27
- end
24
+ IGNORE = %w(config.yml).freeze
25
+ DEFAULT_WHITELIST = %w(configs/ css/ elements/ img/ layouts/ pages/ js/).freeze
26
+ TIMEFORMAT = '%H:%M:%S'.freeze
28
27
 
29
28
  map 'new' => :bootstrap
30
29
  map 'rm' => :remove
31
30
 
31
+ tasks.keys.abbrev.each { |shortcut, command| map shortcut => command.to_sym }
32
+ desc 'components', "Listagem (opencode components list) ou instalação de componentes(opencode components install nome) "
33
+ def components(action = 'list', name = nil, user = 'tray-desenvolvedores', origin = 'github')
34
+ return show_list_components if action == 'list'
35
+ return install_component(name, user, origin) if action == 'install' && !name.nil?
36
+ return components_install if action == 'install' && name.nil?
37
+ end
38
+
32
39
  desc 'configure API_KEY PASSWORD THEME_ID', 'Configura o tema que sera modificado'
33
40
  def configure(api_key = nil, password = nil, theme_id = nil)
34
41
  config = { api_key: api_key, password: password, theme_id: theme_id }
35
-
36
42
  if api_key.nil? || password.nil? || theme_id.nil?
37
43
  response = {}
38
- response["message"] = 'necessário informar api_key e password e theme_id.'
39
- return report_error(Time.now, 'Configuration [FAIL]', response)
44
+ response['message'] = 'necessário informar api_key e password e theme_id.'
45
+ return report_error(Time.now, 'Configuração [FALHOU]', response)
40
46
  end
41
47
  OpencodeTheme.config = config
42
-
43
48
  response = OpencodeTheme.check_config
44
49
  if response[:success]
45
- config.merge!(preview_url: response[:response]['preview'])
50
+ config[:preview_url] = response[:response]['preview']
46
51
  create_file('config.yml', config.to_yaml, force: true)
47
52
  say('Configuration [OK]', :green)
48
53
  else
49
- report_error(Time.now, 'Configuration [FAIL]', response[:response])
54
+ report_error(Time.now, 'Configuração [FALHOU]', response[:response])
50
55
  end
51
56
  end
52
57
 
@@ -54,12 +59,11 @@ module OpencodeTheme
54
59
  def list
55
60
  config = OpencodeTheme.config
56
61
  response = OpencodeTheme.list
57
- if response[:response]["authentication"] == false
58
- response = {}
59
- response["message"] = 'necessário autenticação'
60
- return report_error(Time.now, 'Configuration [FAIL]', response)
61
- end
62
-
62
+ if response[:response]['authentication'] == false
63
+ response = {}
64
+ response['message'] = 'necessário autenticação'
65
+ return report_error(Time.now, 'Configuração [FALHOU]', response)
66
+ end
63
67
  if response[:success]
64
68
  say("\n")
65
69
  response[:response]['themes'].each do |theme|
@@ -77,9 +81,8 @@ module OpencodeTheme
77
81
  end
78
82
 
79
83
  desc 'clean', 'Limpa o cache de arquivos estáticos'
80
-
81
84
  def clean
82
- config = OpencodeTheme.config
85
+ OpencodeTheme.config
83
86
  response = OpencodeTheme.clean
84
87
  if response[:success]
85
88
  say('Clean cache [OK]\n', :green)
@@ -93,31 +96,25 @@ module OpencodeTheme
93
96
  def bootstrap(api_key = nil, password = nil, theme_name = 'default', theme_base = 'default')
94
97
  OpencodeTheme.config = { api_key: api_key, password: password }
95
98
  check_config = OpencodeTheme.check_config
96
-
97
99
  if check_config[:success]
98
100
  say('Configuration [OK]', :green)
99
101
  else
100
102
  report_error(Time.now, 'Configuration [FAIL]', check_config[:response])
101
103
  return
102
104
  end
103
-
104
105
  response = OpencodeTheme.theme_new(theme_base, theme_name)
105
-
106
106
  if response[:success]
107
107
  say("Create #{theme_name} theme on store", :green)
108
108
  else
109
109
  report_error(Time.now, 'Could not create a new theme', response[:response])
110
110
  return
111
111
  end
112
-
113
- say("Creating directory named #{theme_name}", :green)
112
+ say("Criando diretório do tema:#{theme_name}", :green)
114
113
  empty_directory(theme_name)
115
-
116
- say("Saving configuration to #{theme_name}", :green)
114
+ say("Salvando configuração para o tema: #{theme_name}", :green)
117
115
  OpencodeTheme.config.merge!(theme_id: response[:response]['theme_id'], preview_url: response[:response]['preview'])
118
116
  create_file("#{theme_name}/config.yml", OpencodeTheme.config.to_yaml)
119
-
120
- say("Downloading #{theme_name} assets from Opencode")
117
+ say("Downloading arquivos do tema #{theme_name}")
121
118
  Dir.chdir(theme_name)
122
119
  download
123
120
  end
@@ -133,25 +130,30 @@ module OpencodeTheme
133
130
  method_option :quiet, type: :boolean, default: false
134
131
  method_option :exclude
135
132
  def download(*keys)
136
- assets = keys.empty? ? OpencodeTheme.asset_list : keys
137
- if assets.is_a? String
138
- return report_error(Time.now, "List Could not download", JSON.parse(assets))
139
- end
140
- if options['exclude']
141
- assets = assets.delete_if { |asset| asset =~ Regexp.new(options['exclude']) }
142
- end
143
- assets.each do |asset|
144
- asset = URI.decode(asset)
145
- begin
146
- download = download_asset(asset)
147
- if download
148
- say("#{OpencodeTheme.api_usage} Downloaded: #{asset}", :green) unless options['quiet'] || !download
149
- say('Done.', :green) unless options['quiet']
150
- end
151
- rescue
152
- say("Error: #{asset}", :red) unless options['quiet']
153
- end
133
+ assets = if keys.empty?
134
+ say('Aguarde enquanto listamos os arquivos...', :green)
135
+ start_time = Time.now
136
+ assets_list = OpencodeTheme.asset_list
137
+ total_assets = assets_list.count
138
+ assets_list
139
+ else
140
+ keys
141
+ end
142
+ say("encontrado: #{total_assets} arquivos" , :green)
143
+ say("o tempo de download depende da quantidade de arquivos, por favor aguarde:" , :green)
144
+ start_time = Time.now
145
+ return report_error(Time.now, 'Não foi possível listar os arquivos', JSON.parse(assets)) if assets.is_a? String
146
+ assets = assets.delete_if { |asset| asset =~ Regexp.new(options['exclude']) } if options['exclude']
147
+
148
+ assets.to_enum.with_index(1).map do |asset, accumator|
149
+ download = download_asset(URI.decode(asset))
150
+ return say("Error: #{asset}", :red) unless options['quiet'] unless download
151
+ say("[#{total_assets}/#{accumator}] Downloaded: #{asset}", :green) unless options['quiet'] #|| !download
154
152
  end
153
+
154
+ finish_time = Time.now
155
+ elapsed_seconds = ((finish_time.to_f - start_time.to_f)).to_i
156
+ say("tempo total de download: #{elapsed_seconds.to_i}s")
155
157
  end
156
158
 
157
159
  desc 'upload FILE', 'Sobe o arquivo informado ou todos se FILE for omitido'
@@ -159,12 +161,12 @@ module OpencodeTheme
159
161
  def upload(*keys)
160
162
  assets = keys.empty? ? local_assets_list : keys
161
163
  assets.each do |asset|
162
- send_asset("#{asset}", options['quiet'])
164
+ send_asset(asset.to_s, options['quiet'])
163
165
  end
164
166
  say('Done.', :green) unless options['quiet']
165
167
  end
166
168
 
167
- desc 'rm FILE', 'Remove um arquivo do tema (apenas se o tema nao estiver publicado)'
169
+ desc 'rm FILE', 'Remove um arquivo do tema'
168
170
  method_option :quiet, type: :boolean, default: false
169
171
  def remove(*keys)
170
172
  keys.each do |key|
@@ -176,64 +178,40 @@ module OpencodeTheme
176
178
  desc 'watch', 'Baixa e sobe um arquivo sempre que ele for salvo'
177
179
  method_option :quiet, type: :boolean, default: false
178
180
  method_option :keep_files, type: :boolean, default: false
179
-
180
-
181
- # def watch
182
- # watcher do |filename, event|
183
- # filename = filename.gsub("#{Dir.pwd}/", '')
184
- # unless local_assets_list.include?(filename)
185
- # say("Unknown file [#{filename}]", :red)
186
- # next
187
- # end
188
- # action = if [:changed, :new].include?(event)
189
- # :send_asset
190
- # elsif event == :delete
191
- # :delete_asset
192
- # else
193
- # raise NotImplementedError, "Unknown event -- #{event} -- #{filename}"
194
- # end
195
- # send(action, filename, options['quiet'])
196
- # end
197
- # end
198
181
  def watch
199
182
  watcher do |filename, event|
200
- filename = filename.gsub("#{Dir.pwd}/", '')
201
- if is_file?(filename)
202
-
203
- action = if [:changed, :new].include?(event)
204
- :send_asset
205
- elsif event == :delete
206
- :delete_asset
207
- else
208
- say("This is not file [#{filename}]", :blue)
209
- raise NotImplementedError, "Unknown event -- #{event} -- #{filename}"
210
- end
183
+ filename = filename.sub(Dir.pwd.to_s + '/', '')
184
+ next if components_temporary_file?(filename)
185
+ next unless file?(filename)
186
+ action =
187
+ if [:changed, :new].include?(event)
188
+ :send_asset
189
+ elsif event == :delete
190
+ :delete_asset
191
+ else
192
+ say("This is not file [#{filename}]", :blue)
193
+ raise NotImplementedError, "Evento Desconhecido -- #{event} -- #{filename}"
194
+ end
211
195
  send(action, filename, options['quiet'])
212
- else
213
- next
214
- end
215
-
216
-
217
196
  end
218
197
  end
219
198
 
220
- desc 'systeminfo', 'Mostra informacoes do sistema'
199
+ desc 'systeminfo', 'Mostra informações do sistema'
221
200
  def systeminfo
222
- ruby_version = "#{RUBY_VERSION}"
201
+ ruby_version = RUBY_VERSION.to_s
223
202
  ruby_version += "-p#{RUBY_PATCHLEVEL}" if RUBY_PATCHLEVEL
224
- puts "Ruby: v#{ruby_version}"
225
- puts "OpencodeTheme: v:" + OpencodeTheme::VERSION
226
-
227
- puts "Operating System: #{RUBY_PLATFORM}"
203
+ say( 'Ruby: v' + ruby_version.to_s)
204
+ say('OpencodeTheme: v' + OpencodeTheme::VERSION.to_s)
205
+ say('Operating System: ' + RUBY_PLATFORM)
228
206
  %w(HTTParty Launchy).each do |lib|
229
207
  require "#{lib.downcase}/version"
230
- puts "#{lib}: v" + Kernel.const_get("#{lib}::VERSION")
208
+ say("#{lib}: v" + Kernel.const_get("#{lib}::VERSION"))
231
209
  end
232
210
  end
233
211
 
234
212
  protected
235
213
 
236
- def is_file?(filename)
214
+ def file?(filename)
237
215
  !FileTest.directory?(filename)
238
216
  end
239
217
 
@@ -243,6 +221,50 @@ module OpencodeTheme
243
221
 
244
222
  private
245
223
 
224
+ def show_list_components
225
+ response = OpencodeTheme.list_opencode_components
226
+ say('Nome: Descrição:', :blue)
227
+ response[:response]['list'].map do |list|
228
+ say(list["name"] + ' ' + list['description'] , :blue)
229
+ end
230
+ end
231
+
232
+ def install_component(name, user = nil, origin = nil)
233
+ OpencodeTheme.config = config
234
+ components = OpencodeTheme.install_opencode_components(name, user, origin)
235
+ return say("Atenção: Não foi possivel instalar o componente: #{name}", :yellow) unless components.success?
236
+ files = components["files"]["tree"].map { |file| { path: file['path'], type: file['type'], url: components["url_base"]+file['path'] } }
237
+ if components[:success]
238
+ OpencodeTheme.install_opencode_components_notification(name, user, origin)
239
+ end
240
+ files.map do |file|
241
+ if file[:type] == "tree"
242
+ FileUtils.mkpath(file[:path])
243
+ else
244
+ content = HTTParty.get(file[:url])
245
+ IO.write(file[:path], content)
246
+ say("Componente #{name} Downloaded: #{file[:path]}", :green)
247
+ end
248
+ end
249
+ end
250
+
251
+ def components_install
252
+ require 'yaml'
253
+ manifest = YAML.load_file('opencode.yml') if File.exist?('opencode.yml')
254
+ return say('opencode.yml not found.', :red) unless manifest
255
+ if manifest['components'].has_key?('tray')
256
+ repos_tray = manifest['components']['tray']
257
+ manifest['components']['tray'].map { |tray_repo| install_component(tray_repo, 'tray-desenvolvedores', 'github') }
258
+ end
259
+ if manifest['components'].has_key?('github')
260
+ manifest['components']['github'].map { |user_repo, repos| repos.map{|repo| install_component(repo, user_repo, 'github') } }
261
+ end
262
+ end
263
+
264
+ def components_temporary_file?(filename)
265
+ ['github', 'opencode-components-', 'opencode.yml'].any? { |word| filename.include?(word) }
266
+ end
267
+
246
268
  def notify_and_sleep(message)
247
269
  say(message, :red)
248
270
  OpencodeTheme.sleep
@@ -253,62 +275,62 @@ module OpencodeTheme
253
275
  end
254
276
 
255
277
  def opencode_theme_url
256
- hash_no_cache = rand(10000)
278
+ hash_no_cache = rand(100_000)
257
279
  config[:preview_url].concat("&#{hash_no_cache}")
258
280
  end
259
281
 
260
282
  def send_asset(asset, quiet = false)
261
- if valid_name?(asset)
262
- return unless is_file?(asset)
263
- return unless valid_name?(asset)
264
- data = { key: "/#{asset}" }
265
- content = File.read("#{asset}")
266
- if binary_file?(asset) || OpencodeTheme.is_binary_data?(content)
267
- content = File.open("#{asset}", "rb") { |io| io.read }
268
- data.merge!(attachment: Base64.encode64(content))
269
- else
270
- data.merge!(value: Base64.encode64(content))
271
- end
272
- response = show_during("[#{timestamp}] Uploading: #{asset}", quiet) do
273
- OpencodeTheme.send_asset(data)
274
- end
275
- if response.success?
276
- say("[#{timestamp}] File uploaded: #{asset}", :green) unless quiet
277
- else
278
- report_error(Time.now, "Could not upload #{asset}", response)
279
- end
283
+ return unless valid_name?(asset)
284
+ return unless valid?(asset)
285
+ return unless file?(asset)
286
+ data = { key: "/#{asset}" }
287
+ content = File.read(asset.to_s)
288
+ if binary_file?(asset) || OpencodeTheme.is_binary_data?(content)
289
+ content = File.open(asset.to_s, 'rb', &:read)
290
+ data[:attachment] = Base64.encode64(content)
291
+ else
292
+ data[:value] = Base64.encode64(content)
280
293
  end
294
+ response = show_during("[#{timestamp}]Enviando: #{asset}", quiet) { OpencodeTheme.send_asset(data) }
295
+ if response.success?
296
+ say("[#{timestamp}] Arquivo enviado: #{asset}", :green) unless quiet
297
+ else
298
+ report_error(Time.now, "Nao foi possível fazer upload #{asset}", response)
299
+ end
300
+ end
301
+
302
+ def temp_files?(file_name)
281
303
  end
282
304
 
283
305
  def temporary_file?(asset)
284
306
  false unless asset.include?('~')
285
307
  end
286
308
 
287
- def delete_asset(key, quiet = false)
288
- return say("[#{timestamp}] Folder removed/rename: #{key}", :green) unless key.include?('.')
309
+ def delete_asset(key, _quiet = false)
310
+ return say("[#{timestamp}] Diretório removido/renomeado: #{key}", :green) unless key.include?('.')
289
311
  return exec_delete_file(key) if valid_name?(key)
290
312
  end
291
313
 
292
314
  def exec_delete_file(key, quiet = false)
293
- response = show_during("[#{timestamp}] Removing: #{key}", quiet) do
315
+ response = show_during("[#{timestamp}] Removendo: #{key}", quiet) do
294
316
  OpencodeTheme.delete_asset(key)
295
317
  end
296
318
  if response.success?
297
- say("[#{timestamp}] File removed: #{key} ", :green) unless quiet
319
+ say("[#{timestamp}] Arquivo removido: #{key} ", :green) unless quiet
298
320
  else
299
- report_error(Time.now, "Could not remove #{key}", response)
321
+ report_error(Time.now, "Não foi possível remover: #{key}", response)
300
322
  end
301
323
  end
302
324
 
303
325
  def watcher
304
326
  FileWatcher.new(Dir.pwd).watch do |filename, event|
305
- yield("#{filename}", event)
327
+ yield(filename.to_s, event)
306
328
  end
307
329
  end
308
330
 
309
331
  def local_assets_list
310
332
  local_files.reject do |p|
311
- @permitted_files ||= (DEFAULT_WHITELIST | OpencodeTheme.whitelist_files).map{ |pattern| Regexp.new(pattern)}
333
+ @permitted_files ||= (DEFAULT_WHITELIST | OpencodeTheme.whitelist_files).map { |pattern| Regexp.new(pattern) }
312
334
  @permitted_files.none? { |regex| regex =~ p } || OpencodeTheme.ignore_files.any? { |regex| regex =~ p }
313
335
  end
314
336
  end
@@ -320,11 +342,10 @@ module OpencodeTheme
320
342
  end
321
343
 
322
344
  def valid?(key)
323
- return true
324
- #return true if DEFAULT_WHITELIST.include?(key.split('/').first + "/")
325
- # say("'#{key}' is not in a valid file for theme uploads", :yellow)
326
- # say("Files need to be in one of the following subdirectories: #{DEFAULT_WHITELIST.join(' ')}", :yellow)
327
- # false
345
+ return true if DEFAULT_WHITELIST.include?(key.split('/').first + "/")
346
+ say("'#{key}' não é um arquivo válido para ser enviado", :yellow)
347
+ say("subdiretórios permitidos: #{DEFAULT_WHITELIST.join(' ')}", :yellow)
348
+ false
328
349
  end
329
350
 
330
351
  def timestamp(time = Time.now)
@@ -334,37 +355,33 @@ module OpencodeTheme
334
355
  def valid_name?(key)
335
356
  return if temporary_file?(key)
336
357
  name = key.split('/').last
337
- if name =~ /^[0-9a-zA-Z\-_.]+\.(ttf|otf|eot|svg|woff|woff2|css|scss|styl|html|js|jpg|gif|png|json|TTF|OTF|EOT|SVG|WOFF|WOFF2|CSS|SCSS|STYL|HTML|JS|PNG|GIF|JPG|JSON)$/
338
- valid = true
339
- else
340
- response = {}
341
- response["message"] = 'verifique as regras de nome de arquivos:'
342
- response["more_info"] = 'https://sites.google.com/a/tray.net.br/tecnologia/open-code/api?pli=1#00313'
343
- report_error(Time.now, "Invalid name: #{name}", response)
344
- end
345
- valid
358
+ return true if extension_valid?(name)
359
+ response = {}
360
+ response['message'] = 'verifique as regras de nome de arquivos:'
361
+ response['more_info'] = 'https://tray-desenvolvedores.github.io/frontend/console-tool/#error'
362
+ report_error(Time.now, "Invalid name: #{name}", response)
363
+ end
364
+
365
+
366
+ def extension_valid?(name)
367
+ /^[0-9a-zA-Z\-_.]+\.(ttf|otf|eot|svg|woff|woff2|css|scss|styl|html|js|jpg|gif|png|json|TTF|OTF|EOT|SVG|WOFF|WOFF2|CSS|SCSS|STYL|HTML|JS|PNG|GIF|JPG|JSON)$/ === name
346
368
  end
347
369
 
348
370
  def download_asset(key)
349
- if valid_name?(key)
350
- return unless valid?(key)
351
- notify_and_sleep('Approaching limit of API permits. Naptime until more permits become available!') if OpencodeTheme.needs_sleep?
352
- response = OpencodeTheme.get_asset(URI.encode(key))
353
- unless response['key']
354
- report_error(Time.now, "Could not download #{key}", response)
355
- return false
356
- end
357
- if response['content']
358
- content = Base64.decode64(response['content'])
359
- content = content.force_encoding('ISO-8859-1')
360
- format = 'w+b:ISO-8859-1'
361
- elsif response['attachment']
362
- content = Base64.decode64(response['attachment'])
363
- format = 'w+b'
364
- end
365
- FileUtils.mkdir_p(File.dirname(URI.decode(key)))
366
- File.open(key, format) { |f| f.write content } if content
371
+ return unless valid_name?(key)
372
+ return unless valid?(key)
373
+ response = OpencodeTheme.get_asset(URI.encode(key))
374
+ return report_error(Time.now, "Não foi possível efetuar o download do arquivo: #{key}", response) unless response['key']
375
+ if response['content']
376
+ content = Base64.decode64(response['content'])
377
+ content = content.force_encoding('ISO-8859-1')
378
+ format = 'w+b:ISO-8859-1'
379
+ elsif response['attachment']
380
+ content = Base64.decode64(response['attachment'])
381
+ format = 'w+b'
367
382
  end
383
+ FileUtils.mkdir_p(File.dirname(URI.decode(key)))
384
+ File.open(key, format) { |f| f.write content }
368
385
  end
369
386
 
370
387
  def show_during(message = '', quiet = false, &block)
@@ -375,10 +392,10 @@ module OpencodeTheme
375
392
  end
376
393
 
377
394
  def report_error(time, message, response)
378
- say("[#{timestamp(time)}] Error: #{message}", :red) if message
395
+ say("[#{timestamp(time)}] Error: #{message}", :red) if message
379
396
  if response
380
- message_details = response["message"]
381
- message_details = "#{message_details} \n #{response["more_info"]}" if !response["more_info"].nil?
397
+ message_details = response['message']
398
+ message_details = "#{message_details} \n #{response['more_info']}" unless response['more_info'].nil?
382
399
  say("Error Details: #{message_details}", :yellow)
383
400
  end
384
401
  end