forked from a4agarwal/dropzone-user-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYandexFotki.dropzone
194 lines (158 loc) · 6.77 KB
/
YandexFotki.dropzone
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env ruby
# Dropzone Destination Info
# Name: Yandex.Fotki
# Description: Drag photos to upload them to the Yandex.Fotki (http://fotki.yandex.ru). Hold "Option" key to make phot private.
# Handles: NSFilenamesPboardType
# Events: Clicked, Dragged
# KeyModifiers: Option
# Creator: Alexander Artemenko <[email protected]>
# URL: http://svetlyak.ru
# IconURL: http://img-fotki.yandex.ru/get/5601/alexander-artemenko.d/0_6afc4_6adf389_orig
require 'net/http'
require 'yaml'
require 'logger'
class YandexFotki
@@config_filename = File.expand_path("~/.dz_yandex_fotki")
@@client_id = 'cd414e3ca88a451aa9256f673f40edd6'
@@api_host = 'api-fotki.yandex.ru'
@@api_port = 80
@@log = Logger.new(File.expand_path('~/Library/Application Support/Dropzone/YandexFotki.log'), 10, 1024000)
class << self
def get_last_url
config = load_config()
config['last_image_url']
end
def log(message)
@@log.info(message)
end
def post_files(filenames, access_public)
config = load_config()
log("post_files")
http = Net::HTTP.new(@@api_host, @@api_port)
request = Net::HTTP::Get.new('/api/me/')
request['Authorization'] = 'OAuth ' + config['token']
response = http.request(request)
if response.code.to_i == 400 or response.code.to_i == 401
config['token'] = nil
save_config(config)
$dz.error("Access Denied", "Token is invalid.")
end
log("/api/me/ response code: #{response.code}")
user = URI.parse(response['location']).request_uri
log("user document #{user}")
request = Net::HTTP::Post.new(user + 'photos/')
request['Authorization'] = 'OAuth ' + config['token']
request['Content-Type'] = 'image/jpeg'
for filename in filenames:
basename = File.basename(filename)
$dz.begin("Uploading #{basename}")
if File.readable?(filename)
request.body = File.open(filename).read.chomp
else
raise "Error: unable to read #{basename}"
end
request['Slug'] = basename
response = http.request(request)
log("response: #{response.body}")
if response.code.to_i == 201
image_url = response['Content-Location']
config['last_image_url'] = image_url
save_config(config)
log("access_public = #{access_public}")
entry = response.body
if access_public
entry = entry.gsub('f:access value="private"', 'f:access value="public"')
end
entry = entry.gsub('<title>Фотка</title>', "<title>#{basename}</title>")
photo_uri = URI.parse(response['location']).request_uri
log("updating photo #{photo_uri} meta")
update_request = Net::HTTP::Put.new(photo_uri)
update_request['Authorization'] = 'OAuth ' + config['token']
update_request['Content-Type'] = 'application/atom+xml; charset=utf-8; type=entry'
update_request.body = entry
response = http.request(update_request)
log("Response code: #{response.code}, #{response.body}")
else
log("Error: #{response.code}, #{response.body}")
if response.code.to_i == 401
config['token'] = nil
save_config(config)
$dz.error("Access Denied", "Token is invalid.")
else
raise "Error: #{response.code}, #{response.body}"
end
end
end
image_url
end
private
def request_token
output = `./CocoaDialog msgbox --float --text "Авторизация" --e --informative-text "Для работы мне нужно подтверждение полномочий. Нажмите кнопку \"Продолжить\", в открывшемся окне браузера подтвердите мои полномочия на загрузку картинок, скопируйте полученный токен в буфер обмена, а потом в мои настройки." --button1 "Продолжить"`
system("open 'https://oauth.yandex.ru/authorize?client_id=#{@@client_id}&response_type=token'")
output = `./CocoaDialog standard-inputbox --float --title "Введите авторизационный токен" --e --informative-text "Авторизационный токен:"`
output.split("\n")[1]
end
def load_config
if File.readable?(@@config_filename)
config = YAML.load(File.open(@@config_filename).read)
else
config = {}
end
if not config['token']
config['token'] = request_token
if not config['token']:
$dz.error('Token required')
exit
end
save_config config
end
config
end
def save_config(config)
File.open(@@config_filename, 'w') do |f|
f.puts YAML.dump config
end
end
def read_files(filenames)
params = {}
for filename in filenames
basename = File.basename(filename)
if File.readable?(filename)
params["files[#{basename}]"] = File.open(filename).read.chomp
else
raise "Error: unable to read #{basename}"
end
end
params
end
def fake_file(filename, content)
{"files[#{filename}]" => content}
end
end
end
# DZ events
def dragged
$dz.begin("Uploading files...")
begin
case ENV['DRAGGED_TYPE']
when 'NSFilenamesPboardType'
url = YandexFotki.post_files($items, ENV['KEY_MODIFIERS'] == "")
end
$dz.finish("URL is now on clipboard")
$dz.url(url)
rescue Exception => e
message = "Error uploading photo! %s" % e
YandexFotki.log(message)
$dz.finish(message)
$dz.url(false)
exit
end
end
def clicked
url = YandexFotki.get_last_url
if url
$dz.finish("URL is now on clipboard")
$dz.url(url)
system("open #{url}")
end
end