-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStippleAPI.lua
501 lines (377 loc) · 15 KB
/
StippleAPI.lua
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
-- Lightroom SDK
local LrBinding = import 'LrBinding'
local LrDate = import 'LrDate'
local LrDialogs = import 'LrDialogs'
local LrErrors = import 'LrErrors'
local LrFunctionContext = import 'LrFunctionContext'
local LrHttp = import 'LrHttp'
local LrMD5 = import 'LrMD5'
local LrPathUtils = import 'LrPathUtils'
local LrView = import 'LrView'
local LrXml = import 'LrXml'
local prefs = import 'LrPrefs'.prefsForPlugin()
local bind = LrView.bind
local share = LrView.share
local logger = import 'LrLogger'( 'StippleAPI' )
logger:enable('print')
local JSON = require 'json'
local urlBase = 'https://stipple.com'
--============================================================================--
StippleAPI = {}
--------------------------------------------------------------------------------
local appearsAlive
--------------------------------------------------------------------------------
local function formatError( nativeErrorCode )
return LOC "$$$/Stipple/Error/NetworkFailure=Could not contact the Stipple web service. Please check your Internet connection."
end
--------------------------------------------------------------------------------
local function trim( s )
return string.gsub( s, "^%s*(.-)%s*$", "%1" )
end
--------------------------------------------------------------------------------
function StippleAPI.showApiKeyDialog( message )
LrFunctionContext.callWithContext( 'StippleAPI.showApiKeyDialog', function( context )
local f = LrView.osFactory()
local properties = LrBinding.makePropertyTable( context )
properties.apiKey = prefs.apiKey
local contents = f:column {
bind_to_object = properties,
spacing = f:control_spacing(),
fill = 1,
f:static_text {
title = LOC "$$$/Stipple/ApiKeyDialog/Message=In order to use the Stipple plug-in, you must obtain an API key from Stipple.com. Sign on to Stipple and register for a key.",
fill_horizontal = 1,
width_in_chars = 55,
height_in_lines = 2,
size = 'small',
},
message and f:static_text {
title = message,
fill_horizontal = 1,
width_in_chars = 55,
height_in_lines = 2,
size = 'small',
text_color = import 'LrColor'( 1, 0, 0 ),
} or 'skipped item',
f:row {
spacing = f:label_spacing(),
f:static_text {
title = LOC "$$$/Stipple/ApiKeyDialog/Key=API Key:",
alignment = 'right',
width = share 'title_width',
},
f:edit_field {
fill_horizonal = 1,
width_in_chars = 35,
value = bind 'apiKey',
},
},
}
local result = LrDialogs.presentModalDialog {
title = LOC "$$$/Stipple/ApiKeyDialog/Title=Enter Your Stipple API Key",
contents = contents,
accessoryView = f:push_button {
title = LOC "$$$/Stipple/ApiKeyDialog/GoToStipple=Get Stipple API Key...",
action = function()
LrHttp.openUrlInBrowser( urlBase .. "/api_docs/v1" )
end
},
}
if result == 'ok' then
prefs.apiKey = trim ( properties.apiKey )
else
LrErrors.throwCanceled()
end
end )
end
--------------------------------------------------------------------------------
function StippleAPI.getApiKeyAndSecret()
local apiKey = prefs.apiKey
while not(type( apiKey ) == 'string' and #apiKey > 10) do
local message
if apiKey then
message = LOC "$$$/Stipple/ApiKeyDialog/Invalid=The key below is not valid."
end
StippleAPI.showApiKeyDialog( message )
apiKey = prefs.apiKey
end
return apiKey
end
function StippleAPI.resetApiKey()
prefs.apiKey = ''
StippleAPI.getApiKeyAndSecret()
end
--------------------------------------------------------------------------------
function StippleAPI.makeApiSignature( params )
local apiKey = StippleAPI.getApiKeyAndSecret()
if not params.api_key then
params.api_key = apiKey
end
-- Get list of arguments in sorted order.
local argNames = {}
for name in pairs( params ) do
table.insert( argNames, name )
end
table.sort( argNames )
-- Build the secret string to be MD5 hashed.
local allArgs = sharedSecret
for _, name in ipairs( argNames ) do
if params[ name ] then -- might be false
allArgs = string.format( '%s%s%s', allArgs, name, params[ name ] )
end
end
return LrMD5.digest( allArgs )
end
--------------------------------------------------------------------------------
function StippleAPI.getRestMethod( propertyTable, params )
local apiKey = StippleAPI.getApiKeyAndSecret()
if not params.api_key then
params.api_key = apiKey
end
local suppressError = params.suppressError
local suppressErrorCodes = params.suppressErrorCodes
local skipAuthToken = params.skipAuthToken
params.suppressError = nil
params.suppressErrorCodes = nil
params.skipAuthToken = nil
local url = string.format( urlBase .. '/api/v1/%s', assert( params.url ) )
for name, value in pairs( params ) do
local query_seperator = '?'
if name ~= 'url' and value then
local gsubString = '([^0-9A-Za-z])'
value = tostring( value )
if name ~= 'tag_id' then
value = string.gsub( value, gsubString, function( c ) return string.format( '%%%02X', string.byte( c ) ) end )
end
value = string.gsub( value, ' ', '+' )
params[ name ] = value
url = string.format( '%s%s%s=%s', url, query_seperator, name, value )
query_seperator = '&'
end
end
logger:info( 'calling Stipple API via URL:', url )
local response, hdrs = LrHttp.get( url )
logger:info( 'Stipple response:', response )
if not response then
appearsAlive = false
if suppressError then
return { stat = "noresponse" }
else
if hdrs and hdrs.error then
LrErrors.throwUserError( formatError( hdrs.error.nativeCode ) )
end
end
end
-- Mac has different implementation with that on Windows when the server refuses the request.
if hdrs.status ~= 200 then
if hdrs.status == 401 then
StippleAPI.resetApiKey()
else
LrErrors.throwUserError( formatError( hdrs.status ) )
end
end
appearsAlive = true
local json = JSON:decode(response)
if suppressErrorCodes then
local errorCode = simpleXml and simpleXml.err and tonumber( simpleXml.err.code )
if errorCode and suppressErrorCodes[ errorCode ] then
suppressError = true
end
end
if tonumber(json.status) == 200 or suppressError then
logger:info( 'Stipple API returned status ' .. json.status )
return json, response
else
logger:warn( 'Stipple API returned error', tostring(json.status) )
LrErrors.throwUserError( LOC( "$$$/Stipple/Error/API=Stipple API returned an error message (function ^1, status ^2, error ^3)",
tostring(params.url), tostring(json.status), tostring(json.error)))
end
end
--------------------------------------------------------------------------------
function StippleAPI.postRestMethod( propertyTable, params )
assert( type( params ) == 'table', 'StippleAPI.postRestMethod: params must be a table' )
local apiKey = StippleAPI.getApiKeyAndSecret()
local url = string.format( urlBase .. '/api/v1/%s', assert( params.url ) )
params.url = nil
if not params.api_key then
params.api_key = apiKey
end
local suppressError = params.suppressError
local suppressErrorCodes = params.suppressErrorCodes
local skipAuthToken = params.skipAuthToken
params.suppressError = nil
params.suppressErrorCodes = nil
params.skipAuthToken = nil
local chunks = {}
for key, value in pairs(params) do
if (type(value) == 'table') then
for attribute, val in pairs(value) do
if (type(attribute) == 'number') then
attribute = ''
end
table.insert(chunks, { name = key .. '[' .. attribute .. ']', value = val })
end
else
table.insert(chunks, {name = key, value = value })
end
end
local response, hdrs = LrHttp.postMultipart( url, chunks ) -- Post it and wait for confirmation.
if not response then
if hdrs and hdrs.error then
LrErrors.throwUserError( formatError( hdrs.error.nativeCode ) )
end
end
local json = JSON:decode(response)
if tonumber(json.status) == 200 then
return json
else
return json
end
end
--------------------------------------------------------------------------------
function StippleAPI.uploadPhoto( propertyTable, params )
assert( type( params ) == 'table', 'StippleAPI.uploadPhoto: params must be a table' )
local apiKey = StippleAPI.getApiKeyAndSecret()
local postUrl = ''
if not not params.id then
postUrl = urlBase .. '/api/v1/photos/update'
else
postUrl = urlBase .. '/api/v1/photos/upload/'
end
local originalParams = params.id and table.shallowcopy( params )
logger:info( 'uploading photo', params.filePath )
local filePath = assert( params.filePath )
params.filePath = nil
local fileName = LrPathUtils.leafName( filePath )
local mimeChunks = {}
for argName, argValue in pairs( params ) do
if argName ~= 'api_key' and argName ~= 'photo' and argValue then
mimeChunks[ #mimeChunks + 1 ] = { name = argName, value = argValue }
end
end
mimeChunks[ #mimeChunks + 1 ] = { name = 'api_key', value = apiKey }
if params.photo.caption then
mimeChunks[ #mimeChunks + 1 ] = { name = 'photo[caption]', value = params.photo.caption }
end
mimeChunks[ #mimeChunks + 1 ] = { name = 'photo[source_page]', value = params.photo.source_page }
mimeChunks[ #mimeChunks + 1 ] = { name = 'file', fileName = fileName, filePath = filePath, contentType = 'application/octet-stream' }
local response, hdrs = LrHttp.postMultipart( postUrl, mimeChunks ) -- Post it and wait for confirmation.
if not response then
if hdrs and hdrs.error then
LrErrors.throwUserError( formatError( hdrs.error.nativeCode ) )
end
end
-- Parse Stipple response for photo ID.
local json = JSON:decode(response)
if tonumber(json.status) == 200 then
return tostring(json.data.photo.id)
elseif params.id and json.error and tonumber(hdrs.error.nativeCode) == 422 then
-- Photo is missing. Most likely, the user deleted it outside of Lightroom. Just repost it.
-- originalParams.id = nil
-- return StippleAPI.uploadPhoto( propertyTable, originalParams )
LrErrors.throwUserError( LOC( "$$$/Stipple/Error/API/Upload=Stipple API Falling into the elseif case"))
else
logger:info( 'uploading photo', json.status )
LrErrors.throwUserError( LOC( "$$$/Stipple/Error/API/Upload=Stipple API returned an error message (function supload, message ^1)",
tostring( json.status )))
end
end
--------------------------------------------------------------------------------
function StippleAPI.getSetPhotos( propertyTable, params )
local response = StippleAPI.getRestMethod( nil, { url = params.url or 'sets/' .. params.setId })
if response.data and response.data.set and response.data.set.photos and #response.data.set.photos < 1 then
return
end
for _,photo in pairs(response.data.set.photos) do
tryAddPhoto(photo)
end
end
--------------------------------------------------------------------------------
function StippleAPI.openAuthUrl()
local response = StippleAPI.getRestMethod( nil, { url = 'users/me' } )
return response.data
end
--------------------------------------------------------------------------------
local function getPhotoInfo( propertyTable, params )
return nil, nil
end
--------------------------------------------------------------------------------
function StippleAPI.constructPhotoURL( propertyTable, params )
return urlBase .. '/photos/' .. params.id
end
--------------------------------------------------------------------------------
function StippleAPI.constructPhotosetURL( propertyTable, photosetId )
return urlBase .. "/photos/" .. propertyTable.nsid .. "/sets/" .. photosetId
end
--------------------------------------------------------------------------------
function StippleAPI.constructPhotostreamURL( propertyTable )
return urlBase .. "/a#library/untagged"
end
-------------------------------------------------------------------------------
local function traversePhotosetsForTitle( node, title )
return ''
end
--------------------------------------------------------------------------------
function StippleAPI.createOrUpdatePhotoset( propertyTable, params )
local response = {}
if params.photosetId then
StippleAPI.postRestMethod(nil, { url = "sets/update", id = params.photosetId, set = { name = params.title } })
return params.photosetId, StippleAPI.constructPhotosetURL(propertyTable, params.photosetId)
end
response = StippleAPI.postRestMethod(nil, { url = "sets/create", set = params })
return tostring(response.data.set.id), StippleAPI.constructPhotosetURL(propertyTable, tostring(response.data.set.id))
end
--------------------------------------------------------------------------------
function StippleAPI.listPhotosFromPhotoset( propertyTable, params )
local response, photos = {}, {}
response = StippleAPI.getRestMethod(nil, {url = 'sets/' .. params.photosetId})
for _,photo in pairs(response.data.set.photos) do
table.insert(photos,photo)
end
return photos
end
--------------------------------------------------------------------------------
function StippleAPI.setPhotosetSequence( propertyTable, params )
return true
end
--------------------------------------------------------------------------------
function StippleAPI.addPhotosToSet( propertyTable, params )
local data = {}
data = StippleAPI.postRestMethod(nil, { url = 'sets/add', id = params.photosetId, photo_ids = params.photoId })
return true
end
--------------------------------------------------------------------------------
function StippleAPI.deletePhotoFromPhotoset( propertyTable, params )
local data = {}
data = StippleAPI.postRestMethod(nil, { url = 'sets/remove', id = params.photosetId, photo_ids = params.photoId })
return true
end
--------------------------------------------------------------------------------
function StippleAPI.deletePhotoset( propertyTable, params )
data = StippleAPI.postRestMethod(nil, {url = 'sets/delete', id = params.photosetId})
return true
end
--------------------------------------------------------------------------------
local function removePhotoTags( propertyTable, node, previous_tag )
return false
end
--------------------------------------------------------------------------------
function StippleAPI.setImageTags( propertyTable, params )
return true
end
--------------------------------------------------------------------------------
function StippleAPI.getUserInfo( propertyTable, params )
return { }
end
--------------------------------------------------------------------------------
function StippleAPI.getComments( propertyTable, params )
return nil
end
--------------------------------------------------------------------------------
function StippleAPI.addComment( propertyTable, params )
return
end
--------------------------------------------------------------------------------
function StippleAPI.testStippleConnection( propertyTable )
return true
end