-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions-Copy1.lua
1189 lines (1016 loc) · 42 KB
/
functions-Copy1.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- special helper functions for the LR-SDK-API
---
local LrApplication = import( 'LrApplication' )
local LrFileUtils = import 'LrFileUtils'
local LrHttp = import 'LrHttp'
local LrDate = import 'LrDate'
local LrTasks = import 'LrTasks'
local LrPhotoInfo = import 'LrPhotoInfo'
--JSON=require 'JSON'
----- Debug -----------
--require 'strict'
--require 'Logger'
--local DebugSync = logDebug
--local LrMobdebug = import 'LrMobdebug' -- Import LR/ZeroBrane debug module
--LrMobdebug.start()
--local inspect = require 'inspect'
----- Debug -----------
---------------------------------------------------------
-- Write LR Metadata of photo to WP Mediacat via REST-API
function WritephotoMetaToWp( publishSettings, wpid, photoMeta )
-- Parameters: wpid: Number evtl. auch String, aber dann zu Number wandelbar
-- photoMeta: Tabelle mit Metadaten als key-value-pair
-- publishSettings: Tabelle ähnlich den Lr-Lua-PublishSettings, hier aber kopiert, da Original nicht bereitsteht
-- LR caption kommt in den alt-tag und in die Beschreibung bzw. description.raw
-- SEO: alt-tag leerlassen, wenn das Bild als dekoratives Element dient!
-- Example: http-POST: http://127.0.0.1/wordpress/wp-json/wp/v2/media/4224?gallery=paularo&description=cat=paularo
-- Example: http-POST: http://127.0.0.1/wordpress/wp-json/wp/v2/media/4224?title=MPaul
-- Example: http-POST: http://127.0.0.1/wordpress/wp-json/wp/v2/media/4474?alt_text=alternate-text
--LrMobdebug.on()
local success = false
local docaption = publishSettings['doCaption']
if type(wpid) ~= 'string' then
wpid = tostring(wpid)
end
if photoMeta == {} or publishSettings == {} or publishSettings['hash'] == '' or publishSettings['siteURL'] == '' then
local phMeta = inspect( photoMeta)
local id = inspect(wpid)
Log('WritephotoMetaToWp failed for ' .. id .. ' with type ' .. type(wpid) )
Log('Meta was: ', phMeta)
Log('hash ', publishSettings['hash'])
Log('siteURL ', publishSettings['siteURL'])
return success
end
-- check reachability of WP-site and Plugin
local result = CheckLogin( publishSettings )
if tableHasKey( result, 'error' ) then
Log('WritephotoMetaToWp: ', result['error'])
wpid = result['error']
return wpid, restData
end
if not publishSettings.wpplugin then
Log('WritephotoMetaToWp: WP-Plugin not available')
wpid = 'WP-Plugin not available'
return wpid, restData
end
local n = 0
local hash = 'Basic ' .. publishSettings['hash']
local httphead = {
{field='Authorization', value=hash},
}
local result
local headers
local url = publishSettings['siteURL'] .. "/wp-json/wp/v2/media/" .. wpid
local WPalt = publishSettings['WPalt'][1]
local WPdescr = publishSettings['WPdescr'][1]
local WPcap = publishSettings['WPcap'][1]
for k, v in pairs(photoMeta) do
-- LR Caption (caption) to write into WordPress REST-Fields
if k == 'caption' and v ~= '' and v ~= nil and v ~= 'nil' then
v = urlencode(v) -- der wert muss für dt. Umlaute und leerzeichen encoded werden, aber nur der Wert!
-- select which WP REST-Field will be filled with caption
if WPalt == 'LRcap' then
local str = 'alt_text=' .. v
url = url .. pre(n) .. str
n = n + 1
end
if WPdescr == 'LRcap' then
local str = 'description=' .. v
url = url .. pre(n) .. str
n = n + 1
end
if WPcap == 'LRcap' then
local str = 'caption=' .. v
url = url .. pre(n) .. str
n = n + 1
if docaption then
url = url .. "&docaption=true"
end
end
end
-- LR Title to write into WordPress REST-Fields
if k == 'title' and v ~= '' and v ~= nil and v ~= 'nil' then
v = urlencode(v) -- der wert muss für dt. Umlaute und leerzeichen encoded werden, aber nur der Wert!
local str = 'title=' .. v -- der Titel wird immer fix in den Titel geschrieben
url = url .. pre(n) .. str
n = n + 1
-- select which WP REST-Field will be filled with title
if WPalt == 'LRtit' then
local str = 'alt_text=' .. v
url = url .. pre(n) .. str
n = n + 1
end
if WPdescr == 'LRtit' then
local str = 'description=' .. v
url = url .. pre(n) .. str
n = n + 1
end
if WPcap == 'LRtit' then
local str = 'caption=' .. v
url = url .. pre(n) .. str
n = n + 1
if docaption then
url = url .. "&docaption=true"
end
end
end
---------------------------------
if k == 'gallery' and v ~= '' and v ~= nil and v ~= 'nil' then
v = urlencode(v)
local str = 'gallery=' .. v
url = url .. pre(n) .. str
n = n + 1
end
if k == 'sortorder' and v ~= '' and v ~= nil and v ~= 'nil' then -- hier wird nur eine Nummer als integer übergeben
v = urlencode( tostring(v))
local str = 'gallery_sort=' .. v
url = url .. pre(n) .. str
n = n + 1
end
end
if n>0 then
result, headers = LrHttp.post( url, '', httphead )
if headers.status == 200 then -- der POST-Request wird in diesem Fall immer mit status = 200 beantwortet
success = true
Log('Wrote Meta to Rest: ' .. url)
else
success = false
Log('Could not write Meta to Rest: ' .. url)
end
else
success = true
Log('No Meta to update: ' .. url)
end
return success
end
-- REST JSON array with keys
function ExtractDataFromREST( restdata )
-- aus einer REST-Antwort zu einer Datei die Daten für customMetadata extrahieren
-- Parameter restdata: JSON-Format der REST-Antwort. liefert array zurück
local i = 1
local result = {}
result[i] = restdata
local row = {}
local lrid, fname, n
if restdata == nil
or restdata == ''
or restdata == 'nil'
or restdata == {}
or result[i].media_details == nil
or result[i].media_type == 'file'
or result[i].mime_type == "image/x-icon"
then -- mime_type = \"image/x-icon\"
return row
end
local str = inspect(result[i]) -- JSON-Rückgabe für ein Image in str umwandeln
local ii,j = string.find(str,'original_image') -- den vollen Filename suchen
if ii ~= nil then
fname = result[i].media_details.original_image
else
fname = result[i].media_details.file
if fname == nil or fname == 'nil' then Log(str)
else
fname = getfile(fname)
fname, n = fname:gsub('-scaled','')
end
end
local function findTextinHTML( html )
-- find text in HTML-Tag from REST-Api-Data
-- Parameter: html : string
local w1, w2, text
w1, w2 = string.find(html, '<p>.*</p>')
if w1 ~=nil and w2 ~= nil then
text = string.sub(html,w1+3,w2-4)
else
text = ''
end
return text
end
local _descr = result[i].description.rendered
_descr = findTextinHTML(_descr)
local _caption = result[i].caption.rendered
_caption = findTextinHTML(_caption)
row = { lrid = {},
id = result[i].id,
upldate = result[i].date,
width = result[i].media_details.width,
height = result[i].media_details.height,
slug = result[i].slug,
post = result[i].post,
gallery = result[i].gallery,
phurl = result[i].source_url,
filen = fname,
datemod = result[i].modified,
datecreated = result[i].media_details.image_meta.created_timestamp,
title = result[i].title.rendered,
descr = _descr,
caption = _caption,
alt = result[i].alt_text,
origfile = fname,
origurl = result[i].guid.rendered,
MD5 = result[i].md5_original_file, -- table contains MD5 und filesize of fname on server
mime = result[i].mime_type,
}
return row
end
-- Write extracted Rest-meta-Data to customMetadata in Lightroom Catalog
function WriteCustomMetaData( publishSettings, photo, restmetadata )
-- Achung: muss innerhalb von catalog:withWriteAccessDo('unique-ID', function () ... end) aufgerufen werden
local i = 1
local foundph = {}
foundph[i] = restmetadata
local date = tostring(foundph[i].upldate)
date = iso8601ToTime(date)
local dateday = LrDate.formatShortDate(date)
local datetime = LrDate.formatMediumTime( date )
local url = publishSettings['siteURL'] or publishSettings.siteURL
photo:setPropertyForPlugin( _PLUGIN, 'wpid', tostring(foundph[i].id) )
photo:setPropertyForPlugin( _PLUGIN,'upldate', dateday .. " / " .. datetime)
photo:setPropertyForPlugin( _PLUGIN,'wpwidth', tostring(foundph[i].width))
photo:setPropertyForPlugin( _PLUGIN,'wpheight', tostring(foundph[i].height))
photo:setPropertyForPlugin( _PLUGIN,'slug', tostring(foundph[i].slug))
photo:setPropertyForPlugin( _PLUGIN,'gallery', tostring(foundph[i].gallery) )
if mytonumber(foundph[i].post) ~= 'nil' then
photo:setPropertyForPlugin( _PLUGIN,'post', url .. "/?p=" .. tostring(foundph[i].post)) --
else
photo:setPropertyForPlugin( _PLUGIN,'post', '')
end
--photo:setPropertyForPlugin( _PLUGIN,'wpimgurl', tostring(foundph[i].phurl))
-- set to: http://127.0.0.1/wordpress/wp-admin/post.php?post=4522&action=edit
-- https://www.mvb1.de/wp-admin/post.php?post=4884&action=edit
url = url .. '/wp-admin/post.php?post=' .. tostring(foundph[i].id) .. '&action=edit'
photo:setPropertyForPlugin( _PLUGIN,'wpimgurl', url )
end
-- Add Media File to WP-Media-Catalog via REST-API
function AddNewMedia( publishSettings, filename, path, defaultcoll, folder )
--LrMobdebug.on()
-- Folgende Annahmen: Nach dem ersten SYNC wird mit WP nicht mehr im Media-Cat gearbeitet. NIE!
-- Auch mit FTP wird nicht mehr hochgeladen. NIE!
-- Nur dann, KANN es keine Dateien geben, die zwar im Folder sind aber noch nicht in WP sind oder LR nicht zugeordnet wurden, d.h. WP und LR sind dann immer synchron.
-- Wenn das geünscht wird, muss im WP-Plugin die Funktion bei der Route 'addtofolder' erweitert werden
-- Bei GET: Liefert alle WPIDs zu allen Original-Files im Folder. Zusätzlich werden alle Dateien, die nicht in WP sind gelistet als eigener Key in der REST-Antwort
-- Bei POST mit addtofolder, wird mit dem JPG-Body das WP-Bild mit WPID entweder updated oder ohne WPID die bestehende JPG-Datei überschrieben und dann zu WP ergänzt
-- In beiden Fällen bei POST wird die WPID als ID zurückgeliefert und der Ablauf in LR-LUA in dieser Funktion kann gleichbleiben!
Log('AddNewMedia called')
local hash = 'Basic ' .. publishSettings['hash']
local filen = filename
local wpid = 0
local restData = {}
local url = ''
local httphead
local mime = 'image/jpeg'
local doConversion = publishSettings['doConversion']
local conversionQuality = publishSettings['conversionQuality']
local fileFormat = publishSettings['fileFormat']
local reduceMetaData = publishSettings['reduceMetaData']
local generateSubsizes = publishSettings['generateSubsizes']
-- check parameters
if publishSettings == {} or publishSettings['hash'] == '' or publishSettings['siteURL'] == '' or filename == '' or path == '' then
wpid = 'Internal: Wrong function call of AddNewMedia. Parameter mismatch'
Log('Added Media 1: ', wpid)
Log('path: ', path, 'filename: ', filename, 'hash: ', publishSettings['hash'], 'siteURL: ', publishSettings['siteURL'], 'hash: ',hash)
return wpid, restData
end
-- check reachability of WP-site and Plugin
local result = CheckLogin( publishSettings )
if tableHasKey( result, 'error' ) then
Log('AddNewMedia: ', result['error'])
wpid = result['error']
return wpid, restData
end
if not publishSettings.wpplugin then
Log('AddNewMedia: WP-Plugin not available')
wpid = 'WP-Plugin not available'
return wpid, restData
end
-- get the dimensions of the original image
local dimensions = LrPhotoInfo.fileAttributes( path )
local w = dimensions.width
local h = dimensions.height
Log('WP-Dimensions: ', w, h)
-- reduce Metadata
if reduceMetaData then
local cmd2 = ''
local hasExifTool = false
local pipath = _PLUGIN.path .. "\\exiftool"
if not WIN_ENV then
pipath = '/usr/local/bin/exiftool' -- path according to the description on exiftool.org, but not tested
end
if WIN_ENV then
hasExifTool = LrFileUtils.exists( pipath .. '.exe' )
else
hasExifTool = LrFileUtils.exists( pipath )
end
if hasExifTool then
cmd2 = pipath .. " -P -adobe:all= -photoshop:all= -thumbnailimage= -icc_profile= -software= -serialnumber=0 -lensserialnumber=0 -xmp:all= -tagsFromFile \"" .. path .. "\" -XMP-iptcCore:all -XMP-dc:all -XMP-xmpRights:all \"" .. path .. "\""
Log('exiftool-CMD-1: ', cmd2 )
LrTasks.execute( cmd2 )
cmd2 = pipath .. " -SensitivityType= -RecommendedExposureIndex= -MeteringMode= -LightSource= -Flash= -SubSecTimeOriginal= -SubSecTimeDigitized= -SensingMethod= -FileSource= -SceneType= -CFAPattern= -ExposureMode= -WhiteBalance= -SceneCaptureType= -GainControl= -Contrast= -Saturation= -Sharpness= -SubjectDistanceRange= \"" .. path .. "\""
Log('exiftool-CMD-2: ', cmd2 )
LrTasks.execute( cmd2 )
else
Log('exiftool not found')
end
end
-- create the new file if webp or avif if set
if doConversion and fileFormat == 'WEBP' then
mime = 'image/webp'
local cmd = ''
local newfile = string.gsub( path, 'jpg', 'webp')
-- convert jpg file to webp with imagick. Must be installed
if WIN_ENV then
cmd = "magick \"" .. path .. "\" -quality " .. conversionQuality .. " -define webp:auto-filter=true \"" .. newfile .. "\""
else
cmd = pipath .. "/magick " .. path .. " -quality " .. conversionQuality .. " -define webp:auto-filter=true " .. newfile -- TODO pipath is not defined here
end
Log('Webp-CMD: ', cmd)
LrTasks.execute( cmd )
Log('Webp-Path: ', newfile)
filen = string.gsub( filen, 'jpg', 'webp' )
Log('Webp-file:', filen)
LrTasks.sleep(0.1)
path = newfile
elseif doConversion and fileFormat == 'AVIF' then
mime = 'image/avif'
local cmd = ''
local newfile = string.gsub( path, 'jpg', 'avif')
-- convert jpg file to avif with imagick. Must be installed
if WIN_ENV then
cmd = "magick \"" .. path .. "\" -quality " .. conversionQuality .. " \"" .. newfile .. "\""
else
cmd = pipath .. "/magick " .. path .. " -quality " .. conversionQuality .. " " .. newfile -- TODO pipath is not defined here
end
Log('Avif-CMD: ', cmd)
LrTasks.execute( cmd )
Log('Avif-Path: ', newfile)
filen = string.gsub( filen, 'jpg', 'avif' )
Log('Avif-file:', filen)
LrTasks.sleep(0.1)
path = newfile
end
-- generate and upload sub-sizes if set. For all file types
if generateSubsizes and not defaultcoll then
-- generate the filenames
sizes = getImageSubsizes(publishSettings, hash)
Log('WP-Subsizes: ', sizes)
files = generateFileNames(w,h, filen,sizes)
Log('WP-Files: ', files)
-- generate the sub-sizes in a loop and upload them to wordpress
for key, name in pairs(sizes) do
local newfilen = sizes[key].file
local baseName = newfilen:match("^(.*)%.")
local newpath = string.gsub(path, "([^\\]+)%.([^%.]+)$", baseName .. ".%2")
Log('newpath: ', newpath)
-- resize the image
resizeImage(path, newpath, sizes[key].width, sizes[key].height, sizes[key].crop, conversionQuality, mime)
-- upload the image CASE 1: new file, subsize, special folder
uploadMedia(newpath, -- path to the file
newfilen, -- filename
publishSettings, -- table with settings including siteURL
hash, -- authorization hash
mime, -- mime type of the file
defaultcoll, -- boolean for default collection
folder, -- folder path or empty string
'filetofolder', -- route
0 -- The WP ID of the media
)
end
end
-- upload the image CASE 2: new image to wordpress, original, WPCat and CASE 3: new image to wordpress, original, special folder
local result, headers = uploadMedia(path, filen, publishSettings, hash, mime, defaultcoll, folder, 'addtofolder', 0)
-- Extract data from the Response to the Create-Request
if headers.status == 201 and wpid ~= nil then -- Antwort aus REST bei default-collection mit "/wp-json/wp/v2/media/"
result = JSON:decode(result)
wpid = tonumber(result['id'])
restData = ExtractDataFromREST(result)
elseif headers.status == 200 and wpid ~= nil then -- Antwort auf wp-plugin wpcat_json_rest mit "/wp-json/extmedialib/v1/addtofolder/"
result = JSON:decode(result)
wpid = tonumber(result['id'])
local url = publishSettings['siteURL'] .. "/wp-json/wp/v2/media/" .. tostring(wpid)
Log("Anfrage des neuen Bildes über Standard-REST: ", url)
local httphead = {
{field='Authorization', value=hash}
}
local result, headers = LrHttp.get( url, httphead )
result = JSON:decode(result)
restData = ExtractDataFromREST(result)
else
wpid = 'Upload: Fault during upload to WP: ' .. filen .. '.\nHeader-Status: ' .. tostring(headers.status) .. '\nMessage: ' .. inspect(result)
end
Log('AddNewMedia url: ' .. url .. ' filen ' .. filen)
Log('http: ' .. inspect(headers.status) .. ' ID ' .. inspect(wpid))
Log('result: ' .. inspect(result))
Log('Added Media 3: ', inspect(wpid) )
return wpid, restData
end
-- Update Media File to WP-Media-Catalog via REST-API
function UpdateMedia( publishSettings, filename, path, defaultcoll, folder, wpid )
local hash = 'Basic ' .. publishSettings['hash']
local filen = filename
local restData = {}
local mime = 'image/jpeg'
local doConversion = publishSettings['doConversion']
local conversionQuality = publishSettings['conversionQuality']
local fileFormat = publishSettings['fileFormat']
local reduceMetaData = publishSettings['reduceMetaData']
local generateSubsizes = publishSettings['generateSubsizes']
-- check parameters
if publishSettings == {} or publishSettings['hash'] == '' or publishSettings['siteURL'] == '' or filename == '' or path == '' then
wpid = 'Internal: Wrong function call of AddNewMedia. Parameter mismatch'
Log('Update Media 1: ', wpid)
return wpid, restData
end
-- check reachability of WP-site and Plugin
local result = CheckLogin( publishSettings )
if tableHasKey( result, 'error' ) then
Log('UpdateMedia: ', result['error'])
wpid = result['error']
return wpid, restData
end
if not publishSettings.wpplugin then
Log('UpdateMedia: WP-Plugin not available')
wpid = 'WP-Plugin not available'
return wpid, restData
end
-- get the dimensions of the original image
local dimensions = LrPhotoInfo.fileAttributes( path )
local w = dimensions.width
local h = dimensions.height
Log('WP-Dimensions: ', w, h)
-- reduce Metadata
if reduceMetaData then
local cmd2 = ''
local hasExifTool = false
local pipath = _PLUGIN.path .. "\\exiftool"
if not WIN_ENV then
pipath = '/usr/local/bin/exiftool' -- path according to the description on exiftool.org, but not tested
end
if WIN_ENV then
hasExifTool = LrFileUtils.exists( pipath .. '.exe' )
else
hasExifTool = LrFileUtils.exists( pipath )
end
if hasExifTool then
cmd2 = pipath .. " -P -adobe:all= -photoshop:all= -thumbnailimage= -icc_profile= -software= -serialnumber=0 -lensserialnumber=0 -xmp:all= -tagsFromFile \"" .. path .. "\" -XMP-iptcCore:all -XMP-dc:all -XMP-xmpRights:all \"" .. path .. "\""
Log('exiftool-CMD-1: ', cmd2 )
LrTasks.execute( cmd2 )
cmd2 = pipath .. " -SensitivityType= -RecommendedExposureIndex= -MeteringMode= -LightSource= -Flash= -SubSecTimeOriginal= -SubSecTimeDigitized= -SensingMethod= -FileSource= -SceneType= -CFAPattern= -ExposureMode= -WhiteBalance= -SceneCaptureType= -GainControl= -Contrast= -Saturation= -Sharpness= -SubjectDistanceRange= \"" .. path .. "\""
Log('exiftool-CMD-2: ', cmd2 )
LrTasks.execute( cmd2 )
else
Log('exiftool not found')
end
end
-- create the new file if webp or avif if set
if doConversion and fileFormat == 'WEBP' then
mime = 'image/webp'
local cmd = ''
local newfile = string.gsub( path, 'jpg', 'webp')
-- convert jpg file to webp with imagick. Must be installed
if WIN_ENV then
cmd = "magick \"" .. path .. "\" -quality " .. conversionQuality .. " -define webp:auto-filter=true \"" .. newfile .. "\""
else
cmd = pipath .. "/magick " .. path .. " -quality " .. conversionQuality .. " -define webp:auto-filter=true " .. newfile
end
Log('Webp-CMD: ', cmd)
LrTasks.execute( cmd )
Log('Webp-Path: ', newfile)
filen = string.gsub( filen, 'jpg', 'webp' )
Log('Webp-file:', filen)
LrTasks.sleep(0.1)
path = newfile
elseif doConversion and fileFormat == 'AVIF' then
mime = 'image/avif'
local cmd = ''
local newfile = string.gsub( path, 'jpg', 'avif')
-- convert jpg file to avif with imagick. Must be installed
if WIN_ENV then
cmd = "magick \"" .. path .. "\" -quality " .. conversionQuality .. " \"" .. newfile .. "\""
else
cmd = pipath .. "/magick " .. path .. " -quality " .. conversionQuality .. " " .. newfile
end
Log('Avif-CMD: ', cmd)
LrTasks.execute( cmd )
Log('Avif-Path: ', newfile)
filen = string.gsub( filen, 'jpg', 'avif' )
Log('Avif-file:', filen)
LrTasks.sleep(0.1)
path = newfile
end
-- get the upload folder for the default collection - currently unpublished
--[[
if defaultcoll then
local url = publishSettings['siteURL'] .. "/wp-json/wp/v2/media/" .. tostring(wpid)
Log("Anfrage des zu aktualisierenden Bildes über Standard-REST: ", url)
local httphead = {
{field='Authorization', value=hash}
}
local result, headers = LrHttp.get( url, httphead )
local result = JSON:decode(result)
local restData = ExtractDataFromREST(result)
local guid = restData.origurl
local filename = restData.origfile
local year, month = guid:match("http%S+/(%d%d%d%d)/(%d%d)/[%w_%-%.]+%.[%w]+")
folder = year .. "/" .. month
Log('File: ', filename, ' in Folder: ', folder)
end
--]]
-- generate and upload sub-sizes if set. For all file types
if generateSubsizes and not defaultcoll then
-- generate the filenames
sizes = getImageSubsizes(publishSettings, hash)
Log('WP-Subsizes: ', sizes)
files = generateFileNames(w,h, filen,sizes)
Log('WP-Files: ', files)
-- generate the sub-sizes in a loop and upload them to wordpress
for key, name in pairs(sizes) do
local newfilen = sizes[key].file
local baseName = newfilen:match("^(.*)%.")
local newpath = string.gsub(path, "([^\\]+)%.([^%.]+)$", baseName .. ".%2")
Log('newpath: ', newpath)
-- resize the image
resizeImage(path, newpath, sizes[key].width, sizes[key].height, sizes[key].crop, conversionQuality, mime)
-- upload the image CASE 4: update file, subsize, special folder
uploadMedia(newpath, -- path to the file in local file system
newfilen, -- filename
publishSettings, -- table with settings including siteURL
hash, -- authorization hash
mime, -- mime type of the file
defaultcoll, -- boolean for default collection
folder, -- folder path or empty string
'updatefile', -- route
wpid -- The WP ID of the file to update
)
end
end
-- upload the updated and unscaled image which was generated by Lightroom
-- CASE 5: update image in WordPress, original, special folder and WPCat
local result, headers = uploadMedia(path, filen, publishSettings, hash, mime, defaultcoll, folder, 'updatemedia', wpid)
if headers.status == 200 then
result = JSON:decode(result)
else
wpid = 'Update Media Fault: ' .. tostring(headers.status .. ' : ' .. filen)
end
return wpid, result
end
-- Get all Media Files / one Medie File from WP-Media-Catalog via REST-API. Provide response as JSON
-- param: page : wenn nicht angegeben, dann muss perpage eine wpid sein!
-- TODO use parameter _fields with request : ..../media/<wpid>?_fields=id,gallery,filen,MD5 to shorten the transferred data.
function GetMedia( publishSettings, perpage, page )
local result = nil
if publishSettings == {} or publishSettings == nil then
return result
end
local _hash = publishSettings.hash or publishSettings['hash']
local _siteURL = publishSettings.siteURL or publishSettings['siteURL']
local hash = 'Basic ' .. _hash
local url = ''
local httphead = {
{field='Authorization', value=hash},
}
if tonumber(perpage) ~= nil and tonumber(page) ~= nil then
url = _siteURL .. "/wp-json/wp/v2/media/?per_page=" .. perpage .. '&page=' .. page
Log(url)
elseif tonumber(perpage) > 0 and tonumber(page) == nil then
url = _siteURL .. "/wp-json/wp/v2/media/" .. perpage
elseif tonumber(perpage) == 0 then
return
else
url = _siteURL .. "/wp-json/wp/v2/media/"
end
local result, headers = LrHttp.get( url, httphead )
if headers.status == 200 then
result = JSON:decode(result)
else
result = nil
end
return result
end
-- Delete Media Files from WP-Media-Catalog via REST-API
function DeleteMedia( publishSettings, wpmediaid )
local result = false
local idcheck = type(tonumber(wpmediaid))
if publishSettings == {} or publishSettings.hash == '' or publishSettings.siteURL == '' or idcheck ~= 'number' then
return result
end
-- check reachability of WP-site and Plugin
local result = CheckLogin( publishSettings )
if tableHasKey( result, 'error' ) then
Log('DeleteMedia: ', result['error'])
wpid = result['error']
return wpid, restData
end
if not publishSettings.wpplugin then
Log('DeleteMedia: WP-Plugin not available')
wpid = 'WP-Plugin not available'
return wpid, restData
end
local hash = 'Basic ' .. publishSettings.hash
local httphead = {
{field='Authorization', value=hash},
}
local url = ''
url = publishSettings.siteURL .. "/wp-json/wp/v2/media/" .. tostring(wpmediaid) .. "?force=1"
--http://127.0.0.1/wordpress/wp-json/wp/v2/media/3439?force=1
--http-method: delete
local result, headers = LrHttp.post( url, '', httphead, 'Delete' )
if headers.status == 200 then
result = JSON:decode(result)
result = result['deleted']
elseif headers.status == 404 then -- also successful, ID is not available
result = JSON:decode(result)
result = result['code']
end
return result
end
-- Serch pre-selected Images in LR Database, exclude Copies, marked by "Kopie.."
-- special selection if more then on photo found. Selector: "Rot"
-- This runs as asynchronous Task! Main Task has to wait. No Signalling between Tasks.
-- add found photos to WP-LR-Sync-Collection
function addToWPColl (collection, search, photos, all_collections, all_paths)
LrTasks.startAsyncTask(function ()
--LrMobdebug.on()
local str =inspect(all_paths)
Log('Paths in addToWPColl: ', str)
local catalog = LrApplication.activeCatalog()
local selphoto
local specialsearch = true
local lrid = {}
for i=1, #photos do
local filen = photos[i].filen
local base = ''
local ext = ''
photos[i].lrid = {}
if filen == nil or filen == 'nil' then
local str = inspect(photos[i])
Log('Filename nicht definiert. Nr : ' .. i .. str)
else
base, ext = SplitFilename(filen)
end
if ext == 'gif' or ext == 'GIF' or ext == '' or filen == nil or filen == 'nil' then
-- do nothing : skip
else
---- M I : search virt. Copy --------------------------
lrid = catalog:findPhotos {
searchDesc = {
{
criteria = "copyname",
operation = "any",
value = base,
value2 = "",
},
{
criteria = "filename",
operation = "noneOf",
value = base,
value2 = "",
},
combine = "intersect",
},
}
---- M II : search basename with wildcard --------------------------
if #lrid == 0 then
base = string.gsub( base,"[-_]"," ") -- in LR funktioniert die Suche aber nur mit einem Leerzeichen
--base = string.gsub( base,"_"," ")
lrid = catalog:findPhotos {
searchDesc = {
{
criteria = "filename",
operation = "all",
value = base,
},
{
criteria = "copyname",
operation = "noneOf",
value = base,
},
combine = "intersect",
},
}
if #lrid > 1 then
local newlrid = {}
for k, photo in ipairs(lrid) do
local lrfilename = photo:getFormattedMetadata( 'fileName' )
local base4search = '^' .. string.gsub( base," ","[-_]") .. '%.'
local result = string.match(lrfilename, base4search)
if result ~= nil then
Log(' ' .. inspect(lrfilename) .. ' ' .. inspect(base4search) ..' ' .. inspect(result))
--table.insert(newlrid, photo)
newlrid[ #newlrid +1 ] = photo
end
end
lrid = newlrid
end
end
--------- Auswahl bei mehr als einem gefundenen Foto
if lrid[2] ~= nil and specialsearch then
local label = {}
local sel = 0
local nred = 0
local csel = 0
local ncol = 0
local coll = {}
local pubcoll = {}
for k, ph in ipairs(lrid) do
label[k] = ph:getFormattedMetadata('label')
if label[k] == "Rot" then -- TDODO als Variable setzen, für andere Selektoren
sel = k
nred = nred +1
end
coll[k] = ph:getContainedCollections()
pubcoll[k] = ph:getContainedPublishedCollections()
if ((coll[k] ~= nil) or (pubcoll[k] ~= nil)) then
csel = k
ncol = ncol +1
end
end
if nred == 1 then
selphoto = {lrid[sel]}
lrid = selphoto
elseif ncol == 1 then
selphoto = {lrid[csel]}
lrid = selphoto
end
end
if #lrid > 0 then
photos[i].lrid = lrid -- Speichern der gefundenen Fotos in der Tabelle
end
----------------------------
-- Collection bestimmen
local new_collection
local path = photos[i]['path']
local index = 0
index = findValueInArray(all_paths, path)
if index > 0 then
new_collection = all_collections[index]
else
new_collection = collection
end
local name = new_collection:getCollectionInfoSummary()['name']
--Log(path .. '=' .. name)
Log(photos[i].filen .. '; --> ; ' .. base .. '; N lrid = ;' .. #lrid .. '; Coll ; '.. name)
--[[
if #lrid > 0 then
catalog:withWriteAccessDo( 'AddtoWP', function ()
new_collection:addPhotos(lrid)
end )
end
]]
end
end -- end for photos
end )
end
-- Update image_meta keys of Media File to WP-Media-Catalog via REST-API
-- @param wpid number or integer the Wordpress id as integer
function UpdateKeys( publishSettings, photometa, wpid )
local hash = 'Basic ' .. publishSettings['hash']
if publishSettings == {} or publishSettings['hash'] == '' or publishSettings['siteURL'] == '' then
return
end
-- check reachability of WP-site and Plugin
local result = CheckLogin( publishSettings )
if tableHasKey( result, 'error' ) then
Log('UpdateKeys: ', result['error'])
wpid = result['error']
return wpid, restData
end
if not publishSettings.wpplugin then
Log('UpdateKeys: WP-Plugin not available')
wpid = 'WP-Plugin not available'
return wpid, restData
end
local httphead = {
{field='Authorization', value=hash},
{field='Content-Type', value='application/json'},
}
-- restData['image_meta'] = photometa
local image_meta = JSON:encode(photometa)
Log('WPid: ', wpid)
local url = publishSettings['siteURL'] .. "/wp-json/extmedialib/v1/update_meta/" .. tostring(wpid)
Log('Url for image_meta: ', url)
Log('meta as json:', inspect(image_meta) )
local result, headers = LrHttp.post( url, image_meta, httphead )
Log('UpdateKeys http-status: ', headers.status)
if headers.status == 200 then
result = JSON:decode(result)
--wpid = tonumber(result['id'])
--restData = ExtractDataFromREST(result)
else
wpid = 'Update Key Fault: ' .. tostring(headers.status)
end
return wpid, result
end
-- Reset the Custom Meta-Date of this plugin
function ResetCustomMeta (photo)
local catalog = LrApplication.activeCatalog()
catalog:withWriteAccessDo( 'DeleteCollection', function ()
photo:setPropertyForPlugin( _PLUGIN, 'wpid', '' )
photo:setPropertyForPlugin( _PLUGIN,'upldate', '' )
photo:setPropertyForPlugin( _PLUGIN,'wpwidth', '')
photo:setPropertyForPlugin( _PLUGIN,'wpheight', '')
photo:setPropertyForPlugin( _PLUGIN,'wpimgurl', '')
photo:setPropertyForPlugin( _PLUGIN,'slug', '' )
photo:setPropertyForPlugin( _PLUGIN,'post', '')
photo:setPropertyForPlugin( _PLUGIN,'gallery', '')
--photo:setPropertyForPlugin( _PLUGIN,'order', '' )
end )
end
-- get Metadata from photo and return as json table
function getWebpMetaData ( photo )
local aspect = photo:getRawMetadata( 'aspectRatio' )
local orientation = 0
if aspect > 1.0 then
orientation = 1
else
orientation = 0
end
local time = photo:getRawMetadata( 'dateTimeOriginal' )
if time == nil or time == '' or time == 'nil' then
time = ''
else
time = tostring( 978307200 + time )
end
local WebpPhotoMeta = {
image_meta = {
aperture = tostring( photo:getRawMetadata( 'aperture' ) ),
credit = photo:getFormattedMetadata( 'artist' ),
camera = photo:getFormattedMetadata( 'cameraModel' ),
caption = photo:getFormattedMetadata( 'caption' ),
created_timestamp = time,
copyright = photo:getFormattedMetadata( 'copyright' ),
focal_length = tostring( photo:getRawMetadata( 'focalLength35mm' ) ),
iso = tostring( photo:getRawMetadata( 'isoSpeedRating' ) ),
shutter_speed = string.sub( tostring( photo:getRawMetadata( 'shutterSpeed' ) ), 1, 10),
title = photo:getFormattedMetadata( 'title' ),
orientation = tostring( orientation ),
keywords = strsplit( photo:getFormattedMetadata('keywordTagsForExport'), ', ' ) -- return keys as table
}
}
return WebpPhotoMeta
end
-- Functions for local generation of image subsizes
function getImageSubsizes(publishSettings, hash)
local url = publishSettings['siteURL'] .. "/wp-json/extmedialib/v1/imagesubsizes"
local httphead = {
{field='Authorization', value=hash},