-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlayerGlobalControl.lua
More file actions
1065 lines (901 loc) · 35.5 KB
/
Copy pathPlayerGlobalControl.lua
File metadata and controls
1065 lines (901 loc) · 35.5 KB
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
---
--- Created by muescha.
--- DateTime: 24.08.22 10:00
---
--- Current Apps / Sites
--- -> IINA
--- -> Chrome for Player in:
--- -> Generic HTML Video
--- -> [x] YouTube
--- -> [x] RTL+
--- -> [x] ARD Audiothek
--- -> [x] ARD Mediathek:
--- -> [x] WDR
--- TODO: onlye some Controls working on: https://www1.wdr.de/lokalzeit/fernsehen/koeln/video-studiogespraech-linda-rennings-gruenderin-heimatlos-in-koeln-hik-und-koelsche-linda-100.html
--- -> [x] spotify
--- -> Spiegel
--- -> Netflix
--- -> Facebook https://www.facebook.com/watch/?v=816103793764263
--- -> twitter (Example: https://twitter.com/jnybgr/status/1688423139330469888?s=12&t=UKgH_3wb-W7rBipFV7CKXg)
--- -> Loom https://www.loom.com/share/8771f24615e04735a00de927bb6fde99?t=277
--- -> https://podcasts.google.com/ (TODO)
--- -> https://www.linkedin.com/learning/small-talk-und-netzwerken-2-unterschatzte-karriere-booster/gutes-small-talk-thema-wie-findet-man-das?autoSkip=true&resume=false
--- -> TODO: add qualitiy selector for YT
--- Audio Player:
--- - Soundcloud
---
--- reduce Chromoim like apps to Chrome - and Safari like to WebKit
--- add fullscreen shortcut
fileInfo()
local cache = {}
local bundleIdIINA = "com.colliderli.iina"
local bundleIdChrome = "com.google.Chrome"
local browserGoogleChrome = "Google Chrome"
local browserGoogleDevTools = "Google DevTools"
local browserJavaScriptRunner = browserGoogleChrome
local getGenericVideoActions
local functionMemory = {}
local actions = enumString {
"start",
"pause",
"speedReset",
"speedInc",
"speedDec",
"moveForward",
"moveBackward",
"maxQuality",
"maxSpeed"
}
-- maybe direct solution via javascript is here:
-- https://github.com/igrigorik/videospeed/blob/master/inject.js
-- since i don't know the current speed:
-- just tune down to minimum (7 keyStrokes from max 2x speed)
-- and then up to 1
function actionSpeedReset(count)
local reset = {}
table.insert(reset, actions.pause)
for _=1,count+4 do
table.insert(reset, actions.speedDec)
end
for _=1,count do
table.insert(reset, actions.speedInc)
end
table.insert(reset, actions.pause)
return reset
end
local PlayerActions = {
appActions = {},
browserActions = {}
}
function PlayerActions.setAppActions(bundleId, actions)
PlayerActions.appActions[bundleId] = actions
end
function PlayerActions.setBrowserActions(actions)
PlayerActions.browserActions = actions
end
function PlayerActions.getAppActions(bundleId)
return PlayerActions.appActions[bundleId]
end
function PlayerActions.getBrowserActions(domain)
return PlayerActions.browserActions[domain]
end
function PlayerActions.hasAppActions(bundleId)
return PlayerActions.getAppActions(bundleId) ~= nil
end
function PlayerActions.hasBrowserActions()
return next(PlayerActions.browserActions) ~= nil
end
function PlayerActions.extendDomainActions(targetDomain, sourceDomain, overrides)
PlayerActions.browserActions[targetDomain] = helper.table.assigned(PlayerActions.browserActions[sourceDomain], overrides)
end
local BrowserDriver = {
isBrowser = true,
bundleIds = {
[bundleIdChrome] = true
}
}
function BrowserDriver.detect(bundleId)
if BrowserDriver.bundleIds[bundleId] then
return BrowserDriver
end
return nil
end
function BrowserDriver.supportsActions()
return PlayerActions.hasBrowserActions()
end
function BrowserDriver.getCurrentUrl(_target, callback)
assert(callback, "BrowserDriver.getCurrentUrl requires callback")
callback(getChromeUrl())
end
function BrowserDriver.getDomain(target, callback)
assert(callback, "BrowserDriver.getDomain requires callback")
BrowserDriver.getCurrentUrl(target, function(url)
debugInfo("current url: ", url)
local domain = helper.url.getDomain(url)
debugInfo("current domain: ", domain)
callback(domain)
end)
end
function BrowserDriver.getActions(target, callback)
assert(callback, "BrowserDriver.getActions requires callback")
BrowserDriver.getDomain(target, function(domain)
if domain == nil then
debugInfo("No domain detected for current Chrome tab (likely internal/blank page).")
callback(nil, nil)
return
end
local appActions = PlayerActions.getBrowserActions(domain)
if appActions == nil then
getGenericVideoActions(domain, callback)
return
end
functionMemory['domain'] = domain
callback(appActions, domain)
end)
end
local AppDriver = {
isBrowser = false
}
function AppDriver.supportsActions(bundleId)
return PlayerActions.hasAppActions(bundleId)
end
function AppDriver.getActions(target, callback)
assert(callback, "AppDriver.getActions requires callback")
callback(PlayerActions.getAppActions(target.getBundleId()), nil)
end
local PlayerDriver = {}
function PlayerDriver.detect(bundleId)
return BrowserDriver.detect(bundleId) or AppDriver
end
local PlayerTarget = {
bundleId = bundleIdChrome,
window = nil
}
function PlayerTarget.saveWindow(win)
PlayerTarget.window = win
PlayerTarget.bundleId = win:application():bundleID()
end
function PlayerTarget.getWindow()
return PlayerTarget.window
end
function PlayerTarget.getBundleId()
return PlayerTarget.bundleId
end
function PlayerTarget.getDriver()
return PlayerDriver.detect(PlayerTarget.getBundleId())
end
function PlayerTarget.isBrowser()
return PlayerTarget.getDriver().isBrowser
end
function PlayerTarget.supportsBundleId(bundleId)
return PlayerDriver.detect(bundleId).supportsActions(bundleId)
end
function PlayerTarget.getActions(callback)
assert(callback, "PlayerTarget.getActions requires callback")
PlayerTarget.getDriver().getActions(PlayerTarget, callback)
end
function PlayerTarget.getReceiverApp()
local savedWindow = PlayerTarget.getWindow()
if savedWindow then
-- TODO: activate the window - place over others - but go back to current app
-- TODO: check if savedWindow still exists - otherwise null it or use the current
return savedWindow:application()
end
return hs.application.applicationsForBundleID(PlayerTarget.getBundleId())[1]
end
-- Java Script Actions
local function doCache(cacheKey, f)
debugInfo("Cache Size:", helper.table.count(cache))
--for key, _ in pairs(cache) do
-- print(key)
--end
local code = cache[cacheKey]
if code ~= nil then
debugInfo("Cache: found - reusing javascript")
return code
end
debugInfo("Cache: not found - generate javascript")
code = f()
cache[cacheKey] = code
return code
end
local function getCacheKey(path, params)
return "cache-key-'"..path.."'-params:"..hs.inspect(params, {newline="",indent=""})
end
local function getActionCode(templatePath, action, params)
local templateBaseName = "PlayerGlobalControl-"
local jsPath = templatePath .. templateBaseName..action..".js"
local cacheKey = getCacheKey(jsPath, params)
local generate = function()
debugInfo("Filename: ", jsPath)
debugInfo("params: ", params)
return readFileTemplate(jsPath, params)
end
return doCache(cacheKey, generate)
end
local function runActionCode(code, callback)
local wrapper = path() .. "PlayerGlobalControl-BrowserWrapper.js"
local params = { code = code, application = browserGoogleChrome, path = wrapper, browser = browserJavaScriptRunner, debug = false }
if browserJavaScriptRunner == browserGoogleDevTools then
params.path = nil
end
runJavaScriptInBrowser(params, callback)
end
local function logActionCodeResult(ok, output, message)
debugInfo("runActionCode - ok: ", ok)
debugInfo("runActionCode - Output: ", output)
debugInfo("runActionCode - Message: ", message)
end
local function runActionCodeDebug(code, callback)
assert(callback, "runActionCodeDebug requires callback")
runActionCode(code, function(ok, output, message)
logActionCodeResult(ok, output, message)
callback(ok, output, message)
end)
end
--
function GenericAction(action, defaultParams)
local templatePath = path()
return function(memory, callback)
assert(callback, "GenericAction requires callback")
local params = helper.table.assigned(memory, defaultParams)
debugInfo("Params: ", params)
local code = getActionCode(templatePath, action, params)
local handleResult = function(ok, output, message)
if not ok then
return false, message
end
if params.property == nil then
if output == nil then
return ok, {}
end
return ok, { [(memory.domain or '') .. '-' .. action..'-'.. params.action] = output}
end
local calc = params.calc or function(v) return v end
-- TODO add nil check for output
local result = { [params.property] = calc(output)}
return ok, result
end
runActionCodeDebug(code, function(ok, output, message)
callback(handleResult(ok, output, message))
end)
end
end
function ActionSelect(params)
return GenericAction("ActionSelect", params)
end
function ActionClick(params)
return GenericAction("ActionClick", params)
end
function ActionGetProperty(params)
return GenericAction("ActionGetProperty", params)
end
function ActionGetChildIndex(params)
return GenericAction("ActionGetChildIndex", params)
end
function ActionPatch(params)
return GenericAction("ActionPatch", params)
end
function ActionGenericVideo(command)
local params = (command == nil) and {} or { action = command }
return GenericAction("ActionGenericVideo", params)
end
function MemoryCalc(params)
return function(memory, callback) -- MemoryCalc
assert(callback, "MemoryCalc requires callback")
local allParams = helper.table.assigned(memory, params)
debugInfo("MemoryCalc")
debugInfo("Params: ", allParams)
debugFunction(allParams.calc)
local output = allParams.calc(allParams[allParams.property])
local result = { [allParams.property] = output}
callback(true, result)
end
end
function MemoryCalcCheck(params)
return MemoryCalc({
calc = function(value)
if params.min ~= nil then
value = math.max(params.min, value)
end
if params.max ~= nil then
value = math.min(params.max, value)
end
return value
end,
property = params.property
})
end
---@param modifier table @available modifiers or empty table
---@param key string @key
---@return void
---
local function doKey(modifier, key)
debugInfo("--> doKey(", modifier, ',"', key, '")')
local receiverApp = PlayerTarget.getReceiverApp()
if receiverApp then
hs.eventtap.keyStroke(modifier, key, 0, receiverApp)
end
end
local function Key(modifier, key)
return function(_, callback)
doKey(modifier, key)
callback(true, {})
end
end
local function copyCommandQueue(command)
return type(command) == 'table' and { table.unpack(command) } or { command }
end
local function failCommand(callback, message, details)
debugInfo(message, details)
callback(false, details or message)
end
PlayerActions.setAppActions(bundleIdIINA, {
pause = Key({}, "p"),
speedReset = Key({}, "0"),
-- speedInc = { {}, "=" }, -- +
-- speedDec = { {}, "-" },
speedInc = Key({}, "]"), -- 2,0
speedDec = Key({}, "["), -- 0,5
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
info = "IINA Player"
})
PlayerActions.setBrowserActions({
["generic.video"] = {
selector = "",
start = {
ActionClick({ selector = ".ytp-large-play-button" }),
ActionGenericVideo("play")
},
pause = ActionGenericVideo("doPause"),
speedReset = ActionGenericVideo(),
speedInc = ActionGenericVideo(),
speedDec = ActionGenericVideo(),
moveForward = ActionGenericVideo(),
moveBackward = ActionGenericVideo(),
maxQuality = {},
maxSpeed = ActionGenericVideo(),
info = "Generic Video"
},
["youtube.com"] = {
selector = "",
start = {
ActionClick({ selector = ".ytp-large-play-button" })
},
pause = ActionGenericVideo("doPause"),
speedReset = ActionGenericVideo(),
speedInc = ActionGenericVideo(),
speedDec = ActionGenericVideo(),
moveForward = ActionGenericVideo(),
moveBackward = ActionGenericVideo(),
maxQuality = {},
maxSpeed = ActionGenericVideo(),
info = "Generic YouTube"
},
["youtube.com-old"] = {
selector = "#movie_player",
start = {
ActionClick({ selector = ".ytp-large-play-button" })
},
pause = Key({}, "k"),
-- document.querySelector('.ytp-large-play-button').click()
-- not working:
--pause = {
-- ActionClick({ selector = ".ytp-large-play-button" })
--},
speedReset = actionSpeedReset(3),
speedInc = Key({ "shift" }, "."), -- '>'
speedDec = Key({ "shift" }, ","), -- '<'
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
maxQuality = {
ActionClick({ selector="button.ytp-settings-button"}),
ActionPatch({
selector=".ytp-settings-menu .ytp-panel-menu .ytp-menuitem",
childSelector=".ytp-menuitem-label"
}),
ActionClick({ selector=".ytp-settings-menu .ytp-panel-menu .ytp-menuitem[data-content-inner-text='Qualität']"}),
ActionPatch({
selector=".ytp-quality-menu .ytp-menuitem",
childSelector=".ytp-menuitem-label"
}),
ActionClick({ selector=".ytp-menuitem[data-content-inner-text='1080p HD'"}),
},
info = "YouTube Player"
},
["twitch.tv"] = {
selector = ".persistent-player",
start = {},
pause = Key({}, "k"),
speedReset = actionSpeedReset(3),
speedInc = Key({}, "."), -- '>'
speedDec = Key({}, ","), -- '<'
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
info = "Twitch Player (Speed only on Videos)"
},
["udemy.com"] = {
--selector = "[class*='app--body-container--']",
--selector = "[data-purpose='curriculum-item-viewer-content']",
start = {
ActionClick({ selector = "[data-purpose='go-to-next-button']" })
},
selector = "video.vjs-tech",
pause = Key({}, "SPACE"),
speedReset = actionSpeedReset(2),
speedInc = Key({ "shift" }, "right"),
speedDec = Key({ "shift" }, "left"),
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
info = "Udemy Player"
},
["tvnow.de"] = {
start = {},
pause = Key({}, "SPACE"),
speedReset = {},
speedInc = {},
speedDec = {},
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
info = "TVnow Player (no speed controls)"
},
["spiegel.de-old"] = {
--defaultFunctionParams = {
-- speedItems = { '0.5x', '1x', '1.25x', '1.5x', '2x' },
-- speedItemsDefault = '1x',
--},
start = {},
pause = Key({}, "SPACE"),
speedReset ={
--ActionClick, { selector="div[aria-label='Einstellungen']"},
--ActionClick, { selector="div[name='playbackRates']"},
ActionClick({ selector = "button.jw-settings-content-item[aria-label='1x']" })
--ActionClick, { selector=".jw-settings-close"},
},
speedInc = {
ActionGetChildIndex({
selector=".jw-settings-submenu-playbackRates button.jw-settings-content-item.jw-settings-item-active",
property="child-index",
}),
MemoryCalc({
calc=function(value) return value+1+1 end,
property="child-index",
}),
ActionClick({
selector=".jw-settings-submenu-playbackRates button.jw-settings-content-item:nth-child({{ child-index }})",
}),
ActionGetProperty({
selector=".jw-settings-submenu-playbackRates button.jw-settings-content-item:nth-child({{ child-index }})",
property="aria-label"
}),
},
speedDec = {
ActionGetChildIndex({
selector=".jw-settings-submenu-playbackRates button.jw-settings-content-item.jw-settings-item-active",
property="child-index",
--calc=function(value) return value-1+1 end,
}),
MemoryCalc({
calc=function(value) return value-1+1 end,
property="child-index",
}),
ActionClick({
selector=".jw-settings-submenu-playbackRates button.jw-settings-content-item:nth-child({{ child-index }})",
}),
ActionGetProperty({
selector=".jw-settings-submenu-playbackRates button.jw-settings-content-item:nth-child({{ child-index }})",
property="aria-label"
}),
},
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
info = "Spiegel.de Player"
},
-- https://exporte.wdr.de/player/current/v-6.5.0/ardplayer-wdr.js?t=19569
["wdr.de"] = {
selector = "#videoPlayer",
start = {},
pause = ActionClick({ selector=".ardplayer-button-playpause" }),
speedReset = {
ActionClick({ selector="button.ardplayer-button-settings"}),
ActionClick({ selector=".ardplayer-bottom-sheet-container div[aria-label='Geschwindigkeit'] span.ardplayer-option[data-index='3']"}),
ActionClick({ timeout=500, selector=".ardplayer-bottom-sheet-close-button.ardplayer-icon-close"}),
},
speedInc = {
ActionClick({ selector="button.ardplayer-button-settings"}),
ActionGetProperty({
selector=".ardplayer-bottom-sheet-container div[aria-label='Geschwindigkeit'] span.ardplayer-option.ardplayer-option-active",
property="data-index"
}),
MemoryCalc({
calc=function(value) return value+1 end,
property="data-index"
}),
ActionClick({ selector=".ardplayer-bottom-sheet-container div[aria-label='Geschwindigkeit'] span.ardplayer-option[data-index='{{ data-index }}']"}),
ActionClick({ timeout=500, selector=".ardplayer-bottom-sheet-close-button.ardplayer-icon-close"}),
},
speedDec = {
ActionClick({ selector="button.ardplayer-button-settings"}),
ActionGetProperty({
selector=".ardplayer-bottom-sheet-container div[aria-label='Geschwindigkeit'] span.ardplayer-option.ardplayer-option-active",
property="data-index"
}),
MemoryCalc({
calc=function(value) return value-1 end,
property="data-index"
}),
ActionClick({ selector=".ardplayer-bottom-sheet-container div[aria-label='Geschwindigkeit'] span.ardplayer-option[data-index='{{ data-index }}']"}),
ActionClick({ timeout=500, selector=".ardplayer-bottom-sheet-close-button.ardplayer-icon-close"}),
},
moveForward = Key({}, "l"),
moveBackward = Key({}, "j"),
info = "wdr.de Player"
},
["joyn.de"] = {
start = {},
pause = Key({}, "SPACE"),
speedReset = {},
speedInc = {},
speedDec = {},
moveForward = Key({}, "right"),
moveBackward = Key({}, "left"),
info = "Joyn Player (no speed controls)"
},
["spotify.com"] = {
start = {},
pause = Key({}, "SPACE"),
speedReset = {
ActionClick({
selector = "button[data-testid='control-button-playback-speed']"
}),
ActionPatch({
selector="#context-menu ul div li",
childSelector="button span"
}),
ActionClick({
selector = "#context-menu ul div li[data-content-inner-text='1x'] button"
})
},
speedInc = {
ActionClick({
selector = "button[data-testid='control-button-playback-speed']"
}),
ActionPatch({
selector="#context-menu ul div li",
childSelector="button span"
}),
ActionGetProperty({
selector="#context-menu ul div li:has( button[aria-checked='true'])",
property="data-element-index",
calc=function(value) return value+1 end,
}),
MemoryCalcCheck({
min=0,
max=30,
property="data-element-index"
}),
ActionClick({
selector = "#context-menu ul div li[data-element-index='{{ data-element-index }}'] button"
})
},
speedDec = {
ActionClick({
selector = "button[data-testid='control-button-playback-speed']"
}),
ActionPatch({
selector="#context-menu ul div li",
childSelector="button span"
}),
ActionGetProperty({
selector="#context-menu ul div li:has( button[aria-checked='true'])",
property="data-element-index",
calc=function(value) return value-1 end,
}),
MemoryCalcCheck({
min=0,
max=30,
property="data-element-index"
}),
ActionClick({
selector = "#context-menu ul div li[data-element-index='{{ data-element-index }}'] button"
})
},
moveForward = Key({ "cmd", "shift"}, "right"),
moveBackward = Key({ "cmd", "shift" }, "left"),
info = "Spotify Player"
},
})
-- https://www.ardaudiothek.de/sendung/legion/12015417/
PlayerActions.extendDomainActions("ardaudiothek.de", "wdr.de", {
selector = ".ardplayer-viewport",
info = "ardaudiothek.de Player"
})
-- https://www.ardmediathek.de/video/lokalzeit-aus-koeln/lokalzeit-aus-koeln-oder-25-08-2023/wdr/Y3JpZDovL3dkci5kZS9CZWl0cmFnLWU3NjI3YTM4LTI4YTUtNDlkNi04NGZkLTNhZmYxMWI1ZTY1Ng
PlayerActions.extendDomainActions("ardmediathek.de", "wdr.de", {
selector = ".ardplayer-viewport",
info = "ardmediathek.de Player"
})
-- https://www.arte.tv/de/
-- https://www.zdf.de/dokus
function getChromeUrl()
--local _,url = hs.osascript.applescript('tell application "Google Chrome" to return URL of active tab of front window')
--_, title, _ = hs.osascript.javascript("Application('Google Chrome').windows[0].activeTab().title()")
--_, url, _ = hs.osascript.javascript("Application('Google Chrome').windows[0].activeTab().url()")
local ok, url, err = hs.osascript.javascript("Application('Google Chrome').windows[0].activeTab().url()")
if not ok then
debugInfo("getChromeUrl: AppleScript-JS call failed: ", err)
return nil
end
if type(url) ~= "string" or url == "" then
debugInfo("getChromeUrl: no URL for active tab (window missing or internal page).")
return nil
end
return url
end
---@param actionFunction function @function to be called
---@return void
---
local function doFunction(actionFunction, callback)
assert(callback, "doFunction requires callback")
debugInfo("--> doFunction(", getFunctionSignature(actionFunction), ")")
debugInfo("Memory: ", functionMemory)
debugInfo("debugFunction(actionFunction)")
debugFunction(actionFunction)
local done = function(ok, result)
local win = hs.window.focusedWindow()
hs.alert.show(hs.inspect(result), { atScreenEdge = 1}, win)
if ok then
helper.table.assign(functionMemory, result)
debugInfo("Memory: ", functionMemory)
else
failCommand(callback, "doFunction: action failed: ", result)
return
end
callback(ok, result)
end
actionFunction(functionMemory, done)
end
---@param appActions table @available actions for all apps
---@param actionQueue table @queue of actions
---@return void
---
local function doCommand(appActions, actionQueue, callback)
assert(callback, "doCommand requires callback")
if #actionQueue == 0 then
callback(true)
return
end
debugInfo("--> doCommand(", "appActions", ",", actionQueue, ")")
local command = table.remove(actionQueue, 1)
local function continueQueue(ok, message)
if not ok then
failCommand(callback, "Command queue failed: ", message)
return
end
doCommand(appActions, actionQueue, callback)
end
if type(command) == 'string' then
local actionCommands = appActions[command]
if actionCommands == nil then
failCommand(callback, "No command defined for action: " .. command)
return
end
doCommand(appActions, copyCommandQueue(actionCommands), continueQueue)
elseif type(command) == 'function' then
doFunction(command, continueQueue)
else
failCommand(callback, "Unknown command: " .. tostring(command))
end
end
-- TODO add error message if no javascript is activated
-- TODO inform how to activate javascript in Chrome
-- https://sites.google.com/a/chromium.org/dev/developers/applescript?visit_id=638164618181850548-1888693479&p=applescript&rd=1
local function testforScriptEnabled()
local wasSuccessful, jsout, error = hs.osascript.javascript("Application('Google Chrome').windows[0].activeTab.execute({javascript:'true'})")
debugInfo("wasSuccessful: ",wasSuccessful)
debugInfo("error: ", error)
debugTable(error)
debugInfo("jsout: ", jsout)
end
local function selectPlayer(selector)
if selector==nil or selector=="" then return end
doFunction(ActionSelect({ selector=selector }), function() end)
end
-- TODO: when Chrome is not the current App, then also i need to switch to
-- the right tab to get the keyStrokes send to the right tab
-- fix for Chrome when current app is also Chrome
-- remember current window - activate player window to receive the actionCommands
-- when in same maybe use the current tab ---> first test: not work on Chrome :(
-- savedWindow:focusTab(1)
-- local _,tabIndex = hs.osascript.applescript('tell application "Google Chrome" to return active tab index of front window')
local function checkSwitch()
local win = hs.window.focusedWindow()
if win == nil then debugInfo("checkSwitch: no focused window available") return end
local app = win:application()
if app == nil then debugInfo("checkSwitch: focused window has no application") return end
local bundleId = app:bundleID()
local returnSwitchBacks = { win }
if not PlayerTarget.isBrowser() then debugInfo("checkSwitch: saved window is not browser") return end
local savedWindow = PlayerTarget.getWindow()
if savedWindow==nil then debugInfo("checkSwitch: no window saved") return end
if savedWindow:application()==nil then debugInfo("checkSwitch: savedWindow has no Application") return end
if win == savedWindow then debugInfo("checkSwitch: current app focused is same window as saved") return end
local savedWindowFocused = savedWindow:application():focusedWindow()
if savedWindowFocused == savedWindow then debugInfo("checkSwitch: saved app focused is the same window as saved") return end
debugInfo("checkSwitch: saved app focused is NOT the same window as saved")
if win ~= savedWindowFocused then
debugInfo("checkSwitch: add currentWinFocused to return table")
table.insert(returnSwitchBacks, 1, savedWindowFocused)
end
debugInfo("checkSwitch: switch to ", savedWindow)
savedWindow:focus()
hs.timer.usleep(10000)
--savedWindow:raise()
return returnSwitchBacks
end
local function checkSwitchBack(switchBacks)
if switchBacks then
for _, win in pairs(switchBacks) do
debugInfo("checkSwitch: switch back to", win)
win:focus()
end
end
end
getGenericVideoActions = function(domain, callback)
functionMemory['domain'] = domain
doFunction(ActionGenericVideo("isGeneric"), function(ok)
if ok and functionMemory[domain..'-ActionGenericVideo-isGeneric'] then
local genericDomain = "generic.video"
local appActions = PlayerActions.getBrowserActions(genericDomain)
functionMemory['domain'] = genericDomain
callback(appActions, genericDomain)
else
callback(nil, domain)
end
end)
end
local hotkeyInfo = {}
-- types
---@param sourceKey string
---@param action string
local function createHotkey(sourceKey, action, description)
hotkeyInfo[action] = {
sourceKey = sourceKey,
action = action,
description = description
}
hs.hotkey.bind(hyper, sourceKey, keyInfo(description), function()
functionMemory = {}
debugInfo("")
debugInfo("-----------------------------")
debugInfo("HotKey")
debugInfo("-----------------------------")
debugInfo("hyper: ", hyper)
debugInfo("sourceKey: ", sourceKey)
debugInfo("description: ", keyInfo(description))
debugInfo("Key: ", hyper, " + '", sourceKey, "' => ", keyInfo(description))
debugInfo("Action ", action)
debugInfo("-----------------------------")
debugInfo("step: reset functionMemory")
print("collectgarbage(count)")
print(collectgarbage("count"))
-- collectgarbage("collect")
local switchBackToWindow = checkSwitch()
PlayerTarget.getActions(function(appActions, domain)
if appActions == nil then
debugInfo("exit - no commands found for domain " .. tostring(domain))
checkSwitchBack(switchBackToWindow)
return
end
helper.table.assign(functionMemory, { action = action })
doCommand(appActions, { action }, function(ok, message)
checkSwitchBack(switchBackToWindow)
if not ok then
local msg = "HotKey action failed: " .. action .. "\n" .. tostring(message)
debugInfo(msg)
hs.alert.show(msg)
return
end
print("collectgarbage(count)")
print(collectgarbage("count"))
debugInfo("-----------------------------")
debugInfo("HotKey: End")
debugInfo("-----------------------------")
end)
end)
end)
end
local function toggleBrowserJavaScriptRunner()
if browserJavaScriptRunner == browserGoogleChrome then
browserJavaScriptRunner = browserGoogleDevTools
else
browserJavaScriptRunner = browserGoogleChrome
end
debugInfo("Player browser JavaScript runner: ", browserJavaScriptRunner)
hs.alert.show("Player JS: " .. browserJavaScriptRunner)
end
local function getEnabledInfo(appActions)
local enabledInfo = ""
local icon = ""
local sortedActionsIterator = helper.table.sortByKeyIterator(actions)
local format = "✧%s %s %-12s %s\n"
for k, v in sortedActionsIterator do
if appActions[v] == nil or type(appActions[v]) == 'table' and #appActions[v] == 0 then
icon = "🔴"
else
icon = "🟢"
end
local info = string.format(format, hotkeyInfo[v].sourceKey ,icon ,v, hotkeyInfo[v].description)
enabledInfo = enabledInfo .. info
end
return enabledInfo
end
local function setSavedWindow()
debugInfo("devtoolscheck: Start")
local devtoolscheck = helper.chrome.devtools.debugFrontmostChromeDetection()
debugInfo("devtoolscheck: Result:")
debugTable(devtoolscheck)
debugInfo("devtoolscheck: End")
local win = hs.window.focusedWindow()
if win == nil then
debugInfo("setSavedWindow: no focused window available")
return
end
local app = win:application()
if app == nil then
debugInfo("setSavedWindow: focused window has no application")
return
end
local bundleId = app:bundleID()
local title = app:title()