lua: Fix formatting with lua-format

This commit is contained in:
Marty Oehme 2020-11-06 15:03:33 +01:00
parent b57db544b7
commit 0e34af1992
Signed by: Marty
GPG key ID: B7538B8F50A1C800
13 changed files with 3867 additions and 3385 deletions

View file

@ -1,13 +1,15 @@
local accounts = {} local accounts = {}
local status, gmailuser = pipe_from('gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | grep username | cut -d: -f2') local status, gmailuser = pipe_from(
local status, gmailpass = pipe_from('gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | head -n1') 'gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | grep username | cut -d: -f2')
local status, gmailpass = pipe_from(
'gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | head -n1')
-- Setup an imap account called gmail -- Setup an imap account called gmail
accounts.gmail = IMAP { accounts.gmail = IMAP {
server = "imap.gmail.com", server = "imap.gmail.com",
username = gmailuser, username = gmailuser,
password = gmailpass, password = gmailpass,
ssl = "auto" ssl = "auto"
} }
return accounts return accounts

View file

@ -14,70 +14,73 @@ options.timeout = 120
-- whether to enter IDLE mode and conintuously check -- whether to enter IDLE mode and conintuously check
-- for new incoming mail to filter -- for new incoming mail to filter
CONTINUOUS=false CONTINUOUS = false
-- time to wait for next synchronization -- time to wait for next synchronization
-- only used in case server does not support IDLE mode -- only used in case server does not support IDLE mode
UPDATE_TIME=120 UPDATE_TIME = 120
-- implement simple wait function in case server does not support IDLE mode -- implement simple wait function in case server does not support IDLE mode
function sleep(n) function sleep(n) os.execute("sleep " .. tonumber(n)) end
os.execute("sleep " .. tonumber(n))
end
-- will set filters to be grabbed from XDG-compliant filter directory -- will set filters to be grabbed from XDG-compliant filter directory
-- can be overridden with env var IMAPFILTER_FILTERDIR -- can be overridden with env var IMAPFILTER_FILTERDIR
function getConfigDir() function getConfigDir()
-- -- set directory for imapfilter files -- -- set directory for imapfilter files
local configdir local configdir
if os.getenv("IMAPFILTER_CONFIGDIR") then if os.getenv("IMAPFILTER_CONFIGDIR") then
configdir=os.getenv("IMAPFILTER_CONFIGDIR") configdir = os.getenv("IMAPFILTER_CONFIGDIR")
elseif os.getenv("XDG_CONFIG_HOME") then elseif os.getenv("XDG_CONFIG_HOME") then
configdir=os.getenv("XDG_CONFIG_HOME") .. "/imapfilter" configdir = os.getenv("XDG_CONFIG_HOME") .. "/imapfilter"
else else
configdir=os.getenv("HOME") .. "/.config/imapfilter" configdir = os.getenv("HOME") .. "/.config/imapfilter"
end end
return configdir return configdir
end end
-- will set filters to be grabbed from XDG-compliant filter directory -- will set filters to be grabbed from XDG-compliant filter directory
-- can be overridden with env var IMAPFILTER_FILTERDIR -- can be overridden with env var IMAPFILTER_FILTERDIR
function getFilterDir() function getFilterDir()
-- -- set directory for imapfilter files -- -- set directory for imapfilter files
local imapfilterdir local imapfilterdir
if os.getenv("IMAPFILTER_FILTERDIR") then if os.getenv("IMAPFILTER_FILTERDIR") then
imapfilterdir=os.getenv("IMAPFILTER_FILTERDIR") imapfilterdir = os.getenv("IMAPFILTER_FILTERDIR")
else else
imapfilterdir=configDir .. "/filters" imapfilterdir = configDir .. "/filters"
end end
return imapfilterdir return imapfilterdir
end end
-- dirlist, from https://stackoverflow.com/a/25266573 -- dirlist, from https://stackoverflow.com/a/25266573
function applyFilters(dir) function applyFilters(dir)
local p = io.popen('find "'..dir..'" -type f -name "*.lua"') --Open directory look for files, save data in p. By giving '-type f' as parameter, it returns all files. local p = io.popen('find "' .. dir .. '" -type f -name "*.lua"') -- Open directory look for files, save data in p. By giving '-type f' as parameter, it returns all files.
for file in p:lines() do --Loop through all files for file in p:lines() do -- Loop through all files
loadfile(file)() loadfile(file)()
end end
end end
-- create global variable containing the configuration files -- create global variable containing the configuration files
configDir=getConfigDir() configDir = getConfigDir()
assert(configDir, "No configuration directory found. Ensure " .. os.getenv("HOME") .. "/.config/imapfilter exists.") assert(configDir,
"No configuration directory found. Ensure " .. os.getenv("HOME") ..
"/.config/imapfilter exists.")
-- create global variable containing account access -- create global variable containing account access
accounts = loadfile(configDir .. "/accounts.lua")() accounts = loadfile(configDir .. "/accounts.lua")()
assert(accounts, "No accounts configured. Ensure accounts.lua exists and returns a table of accounts.") assert(accounts,
"No accounts configured. Ensure accounts.lua exists and returns a table of accounts.")
-- immediately act on the filters once -- immediately act on the filters once
applyFilters(getFilterDir()) applyFilters(getFilterDir())
-- continuously watch for mail if needed -- continuously watch for mail if needed
while CONTINUOUS==true do while CONTINUOUS == true do
local has_idle=accounts.gmail['Inbox']:enter_idle() local has_idle = accounts.gmail['Inbox']:enter_idle()
applyFilters(getFilterDir()) applyFilters(getFilterDir())
if has_idle == false then if has_idle == false then
print("Server does not support idle, application will be polling again in " .. UPDATE_TIME .. "minutes.") print(
sleep(UPDATE_TIME) "Server does not support idle, application will be polling again in " ..
end UPDATE_TIME .. "minutes.")
sleep(UPDATE_TIME)
end
end end

View file

@ -1,43 +1,40 @@
function sendToFolder(folderFrom, folderTo, senders) function sendToFolder(folderFrom, folderTo, senders)
local messages = folderFrom:select_all() local messages = folderFrom:select_all()
for _, sender in pairs(senders) do for _, sender in pairs(senders) do
local filtered=messages:contain_from(sender) local filtered = messages:contain_from(sender)
filtered:mark_seen() filtered:mark_seen()
filtered:move_messages(folderTo) filtered:move_messages(folderTo)
end end
end end
-- will set filters to be grabbed from XDG-compliant filter directory -- will set filters to be grabbed from XDG-compliant filter directory
-- can be overridden with env var IMAPFILTER_ROLLUPFILE -- can be overridden with env var IMAPFILTER_ROLLUPFILE
function getRollupFile(fname) function getRollupFile(fname)
local f local f
local fname=fname or "rollup.txt" local fname = fname or "rollup.txt"
if os.getenv("IMAPFILTER_ROLLUPFILE") then if os.getenv("IMAPFILTER_ROLLUPFILE") then
f=os.getenv("IMAPFILTER_ROLLUPFILE") f = os.getenv("IMAPFILTER_ROLLUPFILE")
elseif os.getenv("XDG_DATA_HOME") then elseif os.getenv("XDG_DATA_HOME") then
f=os.getenv("XDG_DATA_HOME") .. "/imapfilter/" .. fname f = os.getenv("XDG_DATA_HOME") .. "/imapfilter/" .. fname
else else
f=os.getenv("HOME") .. "/.local/share/imapfilter/" .. fname f = os.getenv("HOME") .. "/.local/share/imapfilter/" .. fname
end end
return f return f
end end
function getSenderList(rollupfile) function getSenderList(rollupfile)
local rollupSenders={} local rollupSenders = {}
local file = io.open(rollupfile) local file = io.open(rollupfile)
if file then if file then
for line in file:lines() do for line in file:lines() do table.insert(rollupSenders, line) end
table.insert(rollupSenders, line) else
print(
"ERROR: rollup did not find rollup.txt file containing mail addresses at " ..
rollupfile or "")
end end
else return rollupSenders
print("ERROR: rollup did not find rollup.txt file containing mail addresses at " .. rollupfile or "" )
end
return rollupSenders
end end
sendToFolder ( sendToFolder(accounts.gmail["Inbox"], accounts.gmail["Dump"],
accounts.gmail["Inbox"], getSenderList(getRollupFile()))
accounts.gmail["Dump"],
getSenderList(getRollupFile())
)

View file

@ -4,24 +4,22 @@ local lqprofile = "lowquality"
local hqprofile = "highquality" local hqprofile = "highquality"
local function powerstate() local function powerstate()
local f =io.open("/sys/class/power_supply/AC/online") local f = io.open("/sys/class/power_supply/AC/online")
if f == nil then if f == nil then return end
return local t = f:read("*n")
end f:close()
local t = f:read("*n") return t
f:close()
return t
end end
local function adjust() local function adjust()
local state = powerstate() local state = powerstate()
-- this actually overrides automatically applied profiles -- this actually overrides automatically applied profiles
-- like 'protocol.http' -- like 'protocol.http'
if state == 0 then if state == 0 then
mp.msg.info("Running on battery, setting low-quality options.") mp.msg.info("Running on battery, setting low-quality options.")
mp.set_property("profile", lqprofile) mp.set_property("profile", lqprofile)
else else
mp.msg.info("Not running on battery, setting high-quality options.") mp.msg.info("Not running on battery, setting high-quality options.")
end end
end end
mp.add_hook("on_load", 1, adjust) mp.add_hook("on_load", 1, adjust)

File diff suppressed because it is too large Load diff

View file

@ -2,8 +2,7 @@
-- --
-- This script skips sponsored segments of YouTube videos -- This script skips sponsored segments of YouTube videos
-- using data from https://github.com/ajayyy/SponsorBlock -- using data from https://github.com/ajayyy/SponsorBlock
local ON_WINDOWS = package.config:sub(1, 1) ~= '/'
local ON_WINDOWS = package.config:sub(1,1) ~= '/'
local options = { local options = {
server_address = "https://sponsor.ajay.app", server_address = "https://sponsor.ajay.app",
@ -71,9 +70,7 @@ mp.options = require "mp.options"
mp.options.read_options(options, "sponsorblock") mp.options.read_options(options, "sponsorblock")
local legacy = mp.command_native_async == nil local legacy = mp.command_native_async == nil
if legacy then if legacy then options.local_database = false end
options.local_database = false
end
local utils = require "mp.utils" local utils = require "mp.utils"
if mp.get_script_directory == nil then if mp.get_script_directory == nil then
@ -83,7 +80,9 @@ else
end end
local sponsorblock = utils.join_path(scripts_dir, "shared/sponsorblock.py") local sponsorblock = utils.join_path(scripts_dir, "shared/sponsorblock.py")
local uid_path = utils.join_path(scripts_dir, "shared/sponsorblock.txt") local uid_path = utils.join_path(scripts_dir, "shared/sponsorblock.txt")
local database_file = options.local_database and utils.join_path(scripts_dir, "shared/sponsorblock.db") or "" local database_file = options.local_database and
utils.join_path(scripts_dir, "shared/sponsorblock.db") or
""
local youtube_id = nil local youtube_id = nil
local ranges = {} local ranges = {}
local init = false local init = false
@ -96,8 +95,13 @@ local fade_dir = nil
local volume_before = mp.get_property_number("volume") local volume_before = mp.get_property_number("volume")
function file_exists(name) function file_exists(name)
local f = io.open(name,"r") local f = io.open(name, "r")
if f ~= nil then io.close(f) return true else return false end if f ~= nil then
io.close(f)
return true
else
return false
end
end end
function t_count(t) function t_count(t)
@ -106,15 +110,14 @@ function t_count(t)
return count return count
end end
function time_sort(a, b) function time_sort(a, b) return a.time < b.time end
return a.time < b.time
end
function clean_chapters() function clean_chapters()
local chapters = mp.get_property_native("chapter-list") local chapters = mp.get_property_native("chapter-list")
local new_chapters = {} local new_chapters = {}
for _, chapter in pairs(chapters) do for _, chapter in pairs(chapters) do
if chapter.title ~= "Preview segment start" and chapter.title ~= "Preview segment end" then if chapter.title ~= "Preview segment start" and chapter.title ~=
"Preview segment end" then
table.insert(new_chapters, chapter) table.insert(new_chapters, chapter)
end end
end end
@ -124,7 +127,11 @@ end
function create_chapter(chapter_title, chapter_time) function create_chapter(chapter_title, chapter_time)
local chapters = mp.get_property_native("chapter-list") local chapters = mp.get_property_native("chapter-list")
local duration = mp.get_property_native("duration") local duration = mp.get_property_native("duration")
table.insert(chapters, {title=chapter_title, time=(duration == nil or duration > chapter_time) and chapter_time or duration - .001}) table.insert(chapters, {
title = chapter_title,
time = (duration == nil or duration > chapter_time) and chapter_time or
duration - .001
})
table.sort(chapters, time_sort) table.sort(chapters, time_sort)
mp.set_property_native("chapter-list", chapters) mp.set_property_native("chapter-list", chapters)
end end
@ -134,7 +141,8 @@ function getranges(_, exists, db, more)
if options.server_fallback then if options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end) mp.add_timeout(0, function() getranges(true, true, "") end)
else else
return mp.osd_message("[sponsorblock] database update failed, gave up") return mp.osd_message(
"[sponsorblock] database update failed, gave up")
end end
end end
if db ~= "" and db ~= database_file then db = database_file end if db ~= "" and db ~= database_file then db = database_file end
@ -151,20 +159,23 @@ function getranges(_, exists, db, more)
end end
local sponsors local sponsors
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "ranges", db, options.server_address,
sponsorblock,
"ranges",
db,
options.server_address,
youtube_id youtube_id
} }
if not legacy then if not legacy then
sponsors = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args}) sponsors = mp.command_native({
name = "subprocess",
capture_stdout = true,
playback_only = false,
args = args
})
else else
sponsors = utils.subprocess({args = args}) sponsors = utils.subprocess({args = args})
end end
if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end
if string.match(sponsors.stdout, "error") then return getranges(true, true) end if string.match(sponsors.stdout, "error") then
return getranges(true, true)
end
local new_ranges = {} local new_ranges = {}
local r_count = 0 local r_count = 0
if more then r_count = -1 end if more then r_count = -1 end
@ -176,7 +187,8 @@ function getranges(_, exists, db, more)
start_time = tonumber(string.match(t, '[^,]+')) start_time = tonumber(string.match(t, '[^,]+'))
end_time = tonumber(string.sub(string.match(t, ',[^,]+'), 2)) end_time = tonumber(string.sub(string.match(t, ',[^,]+'), 2))
for o_uuid, o_t in pairs(ranges) do for o_uuid, o_t in pairs(ranges) do
if (start_time >= o_t.start_time and start_time <= o_t.end_time) or (o_t.start_time >= start_time and o_t.start_time <= end_time) then if (start_time >= o_t.start_time and start_time <= o_t.end_time) or
(o_t.start_time >= start_time and o_t.start_time <= end_time) then
new_ranges[o_uuid] = o_t new_ranges[o_uuid] = o_t
goto continue goto continue
end end
@ -189,29 +201,31 @@ function getranges(_, exists, db, more)
} }
end end
if options.make_chapters then if options.make_chapters then
create_chapter("Sponsor start (" .. string.sub(uuid, 1, 6) .. ")", start_time) create_chapter("Sponsor start (" .. string.sub(uuid, 1, 6) ..
create_chapter("Sponsor end (" .. string.sub(uuid, 1, 6) .. ")", end_time) ")", start_time)
create_chapter("Sponsor end (" .. string.sub(uuid, 1, 6) .. ")",
end_time)
end end
end end
::continue:: ::continue::
r_count = r_count + 1 r_count = r_count + 1
end end
local c_count = t_count(ranges) local c_count = t_count(ranges)
if c_count == 0 or r_count >= c_count then if c_count == 0 or r_count >= c_count then ranges = new_ranges end
ranges = new_ranges
end
end end
function fast_forward() function fast_forward()
local last_speed = mp.get_property_number("speed") local last_speed = mp.get_property_number("speed")
local new_speed = math.min(last_speed + options.fast_forward_increase, options.fast_forward_cap) local new_speed = math.min(last_speed + options.fast_forward_increase,
options.fast_forward_cap)
if new_speed <= last_speed then return end if new_speed <= last_speed then return end
mp.set_property("speed", new_speed) mp.set_property("speed", new_speed)
end end
function fade_audio(step) function fade_audio(step)
local last_volume = mp.get_property_number("volume") local last_volume = mp.get_property_number("volume")
local new_volume = math.max(options.audio_fade_cap, math.min(last_volume + step, volume_before)) local new_volume = math.max(options.audio_fade_cap,
math.min(last_volume + step, volume_before))
if new_volume == last_volume then if new_volume == last_volume then
if step >= 0 then fade_dir = nil end if step >= 0 then fade_dir = nil end
if fade_timer ~= nil then fade_timer:kill() end if fade_timer ~= nil then fade_timer:kill() end
@ -225,7 +239,8 @@ function skip_ads(name, pos)
if pos == nil then return end if pos == nil then return end
local sponsor_ahead = false local sponsor_ahead = false
for uuid, t in pairs(ranges) do for uuid, t in pairs(ranges) do
if (options.fast_forward == uuid or not options.skip_once or not t.skipped) and t.start_time <= pos and t.end_time > pos then if (options.fast_forward == uuid or not options.skip_once or
not t.skipped) and t.start_time <= pos and t.end_time > pos then
if options.fast_forward == uuid then return end if options.fast_forward == uuid then return end
if options.fast_forward == false then if options.fast_forward == false then
mp.osd_message("[sponsorblock] sponsor skipped") mp.osd_message("[sponsorblock] sponsor skipped")
@ -237,20 +252,18 @@ function skip_ads(name, pos)
last_skip = {uuid = uuid, dir = nil} last_skip = {uuid = uuid, dir = nil}
if options.report_views or options.auto_upvote then if options.report_views or options.auto_upvote then
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "stats", database_file,
sponsorblock, options.server_address, youtube_id, uuid,
"stats", options.report_views and "1" or "", uid_path,
database_file, options.user_id, options.auto_upvote and "1" or ""
options.server_address,
youtube_id,
uuid,
options.report_views and "1" or "",
uid_path,
options.user_id,
options.auto_upvote and "1" or ""
} }
if not legacy then if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end) mp.command_native_async(
{
name = "subprocess",
playback_only = false,
args = args
}, function() end)
else else
utils.subprocess_detached({args = args}) utils.subprocess_detached({args = args})
end end
@ -260,22 +273,29 @@ function skip_ads(name, pos)
speed_timer = mp.add_periodic_timer(1, fast_forward) speed_timer = mp.add_periodic_timer(1, fast_forward)
end end
return return
elseif (not options.skip_once or not t.skipped) and t.start_time <= pos + 1 and t.end_time > pos + 1 then elseif (not options.skip_once or not t.skipped) and t.start_time <= pos +
1 and t.end_time > pos + 1 then
sponsor_ahead = true sponsor_ahead = true
end end
end end
if options.audio_fade then if options.audio_fade then
if sponsor_ahead then if sponsor_ahead then
if fade_dir ~= false then if fade_dir ~= false then
if fade_dir == nil then volume_before = mp.get_property_number("volume") end if fade_dir == nil then
volume_before = mp.get_property_number("volume")
end
if fade_timer ~= nil then fade_timer:kill() end if fade_timer ~= nil then fade_timer:kill() end
fade_dir = false fade_dir = false
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(-options.audio_fade_step) end) fade_timer = mp.add_periodic_timer(.1, function()
fade_audio(-options.audio_fade_step)
end)
end end
elseif fade_dir == false then elseif fade_dir == false then
fade_dir = true fade_dir = true
if fade_timer ~= nil then fade_timer:kill() end if fade_timer ~= nil then fade_timer:kill() end
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(options.audio_fade_step) end) fade_timer = mp.add_periodic_timer(.1, function()
fade_audio(options.audio_fade_step)
end)
end end
end end
if options.fast_forward and options.fast_forward ~= true then if options.fast_forward and options.fast_forward ~= true then
@ -286,25 +306,27 @@ function skip_ads(name, pos)
end end
function vote(dir) function vote(dir)
if last_skip.uuid == "" then return mp.osd_message("[sponsorblock] no sponsors skipped, can't submit vote") end if last_skip.uuid == "" then
return mp.osd_message(
"[sponsorblock] no sponsors skipped, can't submit vote")
end
local updown = dir == "1" and "up" or "down" local updown = dir == "1" and "up" or "down"
if last_skip.dir == dir then return mp.osd_message("[sponsorblock] " .. updown .. "vote already submitted") end if last_skip.dir == dir then
return mp.osd_message("[sponsorblock] " .. updown ..
"vote already submitted")
end
last_skip.dir = dir last_skip.dir = dir
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "stats", database_file,
sponsorblock, options.server_address, youtube_id, last_skip.uuid, "", uid_path,
"stats", options.user_id, dir
database_file,
options.server_address,
youtube_id,
last_skip.uuid,
"",
uid_path,
options.user_id,
dir
} }
if not legacy then if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end) mp.command_native_async({
name = "subprocess",
playback_only = false,
args = args
}, function() end)
else else
utils.subprocess({args = args}) utils.subprocess({args = args})
end end
@ -312,13 +334,14 @@ function vote(dir)
end end
function update() function update()
mp.command_native_async({name = "subprocess", playback_only = false, args = { mp.command_native_async({
options.python_path, name = "subprocess",
sponsorblock, playback_only = false,
"update", args = {
database_file, options.python_path, sponsorblock, "update", database_file,
options.server_address options.server_address
}}, getranges) }
}, getranges)
end end
function file_loaded() function file_loaded()
@ -327,15 +350,18 @@ function file_loaded()
segment = {a = 0, b = 0, progress = 0, first = true} segment = {a = 0, b = 0, progress = 0, first = true}
last_skip = {uuid = "", dir = nil} last_skip = {uuid = "", dir = nil}
local video_path = mp.get_property("path") local video_path = mp.get_property("path")
local youtube_id1 = string.match(video_path, "https?://youtu%.be/([%a%d%-_]+).*") local youtube_id1 = string.match(video_path,
local youtube_id2 = string.match(video_path, "https?://w?w?w?%.?youtube%.com/v/([%a%d%-_]+).*") "https?://youtu%.be/([%a%d%-_]+).*")
local youtube_id2 = string.match(video_path,
"https?://w?w?w?%.?youtube%.com/v/([%a%d%-_]+).*")
local youtube_id3 = string.match(video_path, "/watch%?v=([%a%d%-_]+).*") local youtube_id3 = string.match(video_path, "/watch%?v=([%a%d%-_]+).*")
local youtube_id4 = string.match(video_path, "/embed/([%a%d%-_]+).*") local youtube_id4 = string.match(video_path, "/embed/([%a%d%-_]+).*")
local local_pattern = nil local local_pattern = nil
if options.local_pattern ~= "" then if options.local_pattern ~= "" then
local_pattern = string.match(video_path, options.local_pattern) local_pattern = string.match(video_path, options.local_pattern)
end end
youtube_id = youtube_id1 or youtube_id2 or youtube_id3 or youtube_id4 or local_pattern youtube_id = youtube_id1 or youtube_id2 or youtube_id3 or youtube_id4 or
local_pattern
if not youtube_id then return end if not youtube_id then return end
init = true init = true
if not options.local_database then if not options.local_database then
@ -344,7 +370,9 @@ function file_loaded()
local exists = file_exists(database_file) local exists = file_exists(database_file)
if exists and options.server_fallback then if exists and options.server_fallback then
getranges(true, true) getranges(true, true)
mp.add_timeout(0, function() getranges(true, true, "", true) end) mp.add_timeout(0, function()
getranges(true, true, "", true)
end)
elseif exists then elseif exists then
getranges(true, true) getranges(true, true)
elseif options.server_fallback then elseif options.server_fallback then
@ -352,30 +380,25 @@ function file_loaded()
end end
end end
if initialized then return end if initialized then return end
if options.skip then if options.skip then mp.observe_property("time-pos", "native", skip_ads) end
mp.observe_property("time-pos", "native", skip_ads)
end
if options.display_name ~= "" then if options.display_name ~= "" then
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "username", database_file,
sponsorblock, options.server_address, youtube_id, "", "", uid_path,
"username", options.user_id, options.display_name
database_file,
options.server_address,
youtube_id,
"",
"",
uid_path,
options.user_id,
options.display_name
} }
if not legacy then if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end) mp.command_native_async({
name = "subprocess",
playback_only = false,
args = args
}, function() end)
else else
utils.subprocess_detached({args = args}) utils.subprocess_detached({args = args})
end end
end end
if not options.local_database or (not options.auto_update and file_exists(database_file)) then return end if not options.local_database or
(not options.auto_update and file_exists(database_file)) then return end
update() update()
end end
@ -383,17 +406,19 @@ function set_segment()
if not youtube_id then return end if not youtube_id then return end
local pos = mp.get_property_number("time-pos") local pos = mp.get_property_number("time-pos")
if pos == nil then return end if pos == nil then return end
if segment.progress > 1 then if segment.progress > 1 then segment.progress = segment.progress - 2 end
segment.progress = segment.progress - 2
end
if segment.progress == 1 then if segment.progress == 1 then
segment.progress = 0 segment.progress = 0
segment.b = pos segment.b = pos
mp.osd_message("[sponsorblock] segment boundary B set, press again for boundary A", 3) mp.osd_message(
"[sponsorblock] segment boundary B set, press again for boundary A",
3)
else else
segment.progress = 1 segment.progress = 1
segment.a = pos segment.a = pos
mp.osd_message("[sponsorblock] segment boundary A set, press again for boundary B", 3) mp.osd_message(
"[sponsorblock] segment boundary A set, press again for boundary B",
3)
end end
if options.make_chapters and not segment.first then if options.make_chapters and not segment.first then
local start_time = math.min(segment.a, segment.b) local start_time = math.min(segment.a, segment.b)
@ -414,25 +439,30 @@ function submit_segment()
if end_time - start_time == 0 or end_time == 0 then if end_time - start_time == 0 or end_time == 0 then
mp.osd_message("[sponsorblock] empty segment, not submitting") mp.osd_message("[sponsorblock] empty segment, not submitting")
elseif segment.progress <= 1 then elseif segment.progress <= 1 then
mp.osd_message(string.format("[sponsorblock] press Shift+G again to confirm: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d", math.floor(start_time/(60*60)), math.floor(start_time/60%60), math.floor(start_time%60), math.floor(end_time/(60*60)), math.floor(end_time/60%60), math.floor(end_time%60)), 5) mp.osd_message(string.format(
"[sponsorblock] press Shift+G again to confirm: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d",
math.floor(start_time / (60 * 60)),
math.floor(start_time / 60 % 60),
math.floor(start_time % 60),
math.floor(end_time / (60 * 60)),
math.floor(end_time / 60 % 60),
math.floor(end_time % 60)), 5)
segment.progress = segment.progress + 2 segment.progress = segment.progress + 2
else else
mp.osd_message("[sponsorblock] submitting segment...", 30) mp.osd_message("[sponsorblock] submitting segment...", 30)
local submit local submit
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "submit", database_file,
sponsorblock, options.server_address, youtube_id, tostring(start_time),
"submit", tostring(end_time), uid_path, options.user_id
database_file,
options.server_address,
youtube_id,
tostring(start_time),
tostring(end_time),
uid_path,
options.user_id
} }
if not legacy then if not legacy then
submit = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args}) submit = mp.command_native({
name = "subprocess",
capture_stdout = true,
playback_only = false,
args = args
})
else else
submit = utils.subprocess({args = args}) submit = utils.subprocess({args = args})
end end
@ -445,14 +475,21 @@ function submit_segment()
create_chapter("Submitted segment end", end_time) create_chapter("Submitted segment end", end_time)
end end
elseif string.match(submit.stdout, "error") then elseif string.match(submit.stdout, "error") then
mp.osd_message("[sponsorblock] segment submission failed, server may be down. try again", 5) mp.osd_message(
"[sponsorblock] segment submission failed, server may be down. try again",
5)
elseif string.match(submit.stdout, "502") then elseif string.match(submit.stdout, "502") then
mp.osd_message("[sponsorblock] segment submission failed, server is down. try again", 5) mp.osd_message(
"[sponsorblock] segment submission failed, server is down. try again",
5)
elseif string.match(submit.stdout, "400") then elseif string.match(submit.stdout, "400") then
mp.osd_message("[sponsorblock] segment submission failed, impossible inputs", 5) mp.osd_message(
"[sponsorblock] segment submission failed, impossible inputs", 5)
segment = {a = 0, b = 0, progress = 0, first = true} segment = {a = 0, b = 0, progress = 0, first = true}
elseif string.match(submit.stdout, "429") then elseif string.match(submit.stdout, "429") then
mp.osd_message("[sponsorblock] segment submission failed, rate limited. try again", 5) mp.osd_message(
"[sponsorblock] segment submission failed, rate limited. try again",
5)
elseif string.match(submit.stdout, "409") then elseif string.match(submit.stdout, "409") then
mp.osd_message("[sponsorblock] segment already submitted", 3) mp.osd_message("[sponsorblock] segment already submitted", 3)
segment = {a = 0, b = 0, progress = 0, first = true} segment = {a = 0, b = 0, progress = 0, first = true}

View file

@ -1,3 +1,3 @@
if mp.get_script_directory == nil then if mp.get_script_directory == nil then
dofile(mp.find_config_file("scripts/sponsorblock/main.lua")) dofile(mp.find_config_file("scripts/sponsorblock/main.lua"))
end end

File diff suppressed because it is too large Load diff

View file

@ -3,40 +3,42 @@ local api = vim.api
function M.blameVirtText() function M.blameVirtText()
-- get the current file extension -- get the current file extension
local ft = vim.fn.expand('%:h:t') local ft = vim.fn.expand('%:h:t')
if ft == '' or ft == 'bin' then -- if we are in a scratch buffer, unknown filetype, or nvim's terminal window if ft == '' or ft == 'bin' then -- if we are in a scratch buffer, unknown filetype, or nvim's terminal window
return return
end
M.clearBlameVirtText()
local currFile = vim.fn.expand('%')
local line = api.nvim_win_get_cursor(0)
local blame = vim.fn.system(string.format('git blame -c -L %d,%d %s', line[1], line[1], currFile))
local hash = vim.split(blame, '%s')[1]
local cmd = string.format("git show %s ", hash).."--format='%an | %ar | %s'"
if hash == '00000000' then
text = 'Not Committed Yet'
else
text = vim.fn.system(cmd)
text = vim.split(text, '\n')[1]
if text:find("fatal") then -- if the call to git show fails
text = 'Not Committed Yet'
end end
end
-- set virtual text for namespace 2 with the content from git and assign it to the higlight group 'GitLens' M.clearBlameVirtText()
api.nvim_buf_set_virtual_text(0, 2, line[1] - 1, {{ text,'GitLens' }}, {})
local currFile = vim.fn.expand('%')
local line = api.nvim_win_get_cursor(0)
local blame = vim.fn.system(string.format('git blame -c -L %d,%d %s',
line[1], line[1], currFile))
local hash = vim.split(blame, '%s')[1]
local cmd = string.format("git show %s ", hash) ..
"--format='%an | %ar | %s'"
if hash == '00000000' then
text = 'Not Committed Yet'
else
text = vim.fn.system(cmd)
text = vim.split(text, '\n')[1]
if text:find("fatal") then -- if the call to git show fails
text = 'Not Committed Yet'
end
end
-- set virtual text for namespace 2 with the content from git and assign it to the higlight group 'GitLens'
api.nvim_buf_set_virtual_text(0, 2, line[1] - 1, {{text, 'GitLens'}}, {})
end end
-- important for clearing out the text when our cursor moves -- important for clearing out the text when our cursor moves
function M.clearBlameVirtText() function M.clearBlameVirtText()
-- clear out virtual text from namespace 2 (the namespace we will set later) -- clear out virtual text from namespace 2 (the namespace we will set later)
api.nvim_buf_clear_namespace(0, 2, 0, -1) api.nvim_buf_clear_namespace(0, 2, 0, -1)
end end
return M return M

View file

@ -1,31 +1,43 @@
local on_attach = function(client, bufnr) local on_attach = function(client, bufnr)
-- Keybindings for LSPs -- Keybindings for LSPs
-- Note these are in on_attach so that they don't override bindings in a non-LSP setting -- Note these are in on_attach so that they don't override bindings in a non-LSP setting
vim.fn.nvim_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>",
vim.fn.nvim_set_keymap("n", "gD", "<cmd>lua vim.lsp.buf.implementation()<CR>", {noremap = true, silent = true}) {noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "gD",
vim.fn.nvim_set_keymap("n", "gK", "<cmd>lua vim.lsp.buf.signature_help()<CR>", {noremap = true, silent = true}) "<cmd>lua vim.lsp.buf.implementation()<CR>",
vim.fn.nvim_set_keymap("n", "1gD", "<cmd>lua vim.lsp.buf.type_definition()<CR>", {noremap = true, silent = true}) {noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>",
vim.fn.nvim_set_keymap("n", "g0", "<cmd>lua vim.lsp.buf.document_symbol()<CR>", {noremap = true, silent = true}) {noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gW", "<cmd>lua vim.lsp.buf.workspace_symbol()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "gK",
"<cmd>lua vim.lsp.buf.signature_help()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "1gD",
"<cmd>lua vim.lsp.buf.type_definition()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "g0",
"<cmd>lua vim.lsp.buf.document_symbol()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gW",
"<cmd>lua vim.lsp.buf.workspace_symbol()<CR>",
{noremap = true, silent = true})
end end
require'nvim_lsp'.pyls.setup{on_attach=on_attach} require'nvim_lsp'.pyls.setup {on_attach = on_attach}
require'nvim_lsp'.vimls.setup{on_attach=on_attach} require'nvim_lsp'.vimls.setup {on_attach = on_attach}
require'nvim_lsp'.bashls.setup{on_attach=on_attach} require'nvim_lsp'.bashls.setup {on_attach = on_attach}
require'nvim_lsp'.gopls.setup{on_attach=on_attach} require'nvim_lsp'.gopls.setup {on_attach = on_attach}
require'nvim_lsp'.texlab.setup{on_attach=on_attach} require'nvim_lsp'.texlab.setup {on_attach = on_attach}
-- To get builtin LSP running, do something like: -- To get builtin LSP running, do something like:
-- NOTE: This replaces the calls where you would have before done `require('nvim_lsp').sumneko_lua.setup()` -- NOTE: This replaces the calls where you would have before done `require('nvim_lsp').sumneko_lua.setup()`
require('nlua.lsp.nvim').setup(require('nvim_lsp'), { require('nlua.lsp.nvim').setup(require('nvim_lsp'), {
on_attach = on_attach, on_attach = on_attach,
-- Include globals you want to tell the LSP are real :) -- Include globals you want to tell the LSP are real :)
globals = { globals = {
-- Colorbuddy -- Colorbuddy
"Color", "c", "Group", "g", "s", "Color", "c", "Group", "g", "s"
} }
}) })

View file

@ -1,13 +1,12 @@
local M = {} local M = {}
function M.getCompletionItems(prefix) function M.getCompletionItems(prefix)
-- define your total completion items -- define your total completion items
local items = vim.api.nvim_call_function('pandoc#completion#Complete',{0, prefix}) local items = vim.api.nvim_call_function('pandoc#completion#Complete',
return items {0, prefix})
return items
end end
M.complete_item = { M.complete_item = {item = M.getCompletionItems}
item = M.getCompletionItems
}
return M return M

View file

@ -9,32 +9,34 @@ window, otherwise opens a new split.
The buffer, by default is set to the pandoc filetype. The buffer, by default is set to the pandoc filetype.
This can be changed by setting the `g:scratchpad_ft` variable or the `b:scratchpad_ft` This can be changed by setting the `g:scratchpad_ft` variable or the `b:scratchpad_ft`
variable to the intended filetype. variable to the intended filetype.
]]-- ]] --
local api = vim.api local api = vim.api
local M= {} local M = {}
local function isempty(s) local function isempty(s) return s == nil or s == '' end
return s == nil or s == ''
end
function M.create(split, ft) function M.create(split, ft)
-- should we create a new split or switch out the current buffer? -- should we create a new split or switch out the current buffer?
if isempty(split) then split = false else split = true end if isempty(split) then
-- which filetype to set for the scratchpad, defaults to pandoc split = false
if isempty(ft) then ft = vim.b["scratchpad_ft"] or vim.g["scratchpad_ft"] or "pandoc" end else
split = true
end
-- which filetype to set for the scratchpad, defaults to pandoc
if isempty(ft) then
ft = vim.b["scratchpad_ft"] or vim.g["scratchpad_ft"] or "pandoc"
end
local buf = api.nvim_create_buf(false, true) local buf = api.nvim_create_buf(false, true)
if buf == 0 then if buf == 0 then print("Error opening scratch buffer.") end
print("Error opening scratch buffer.") api.nvim_buf_set_option(buf, "bufhidden", "hide")
end api.nvim_buf_set_option(buf, "buftype", "nofile")
api.nvim_buf_set_option(buf, "bufhidden", "hide") api.nvim_buf_set_option(buf, "swapfile", false)
api.nvim_buf_set_option(buf, "buftype", "nofile") api.nvim_buf_set_option(buf, "filetype", ft)
api.nvim_buf_set_option(buf, "swapfile",false)
api.nvim_buf_set_option(buf, "filetype",ft)
if split then api.nvim_command('vsplit new') end -- i think this is the only way to interact with the buffers creating a new split if split then api.nvim_command('vsplit new') end -- i think this is the only way to interact with the buffers creating a new split
-- switch to scratchpad -- switch to scratchpad
api.nvim_win_set_buf(0, buf) api.nvim_win_set_buf(0, buf)
end end
return M return M

View file

@ -1,17 +1,15 @@
local w = vim.loop.new_fs_event() local w = vim.loop.new_fs_event()
local function on_change(err, fname, status) local function on_change(err, fname, status)
-- Do work... -- Do work...
vim.api.nvim_command('checktime') vim.api.nvim_command('checktime')
-- Debounce: stop/start. -- Debounce: stop/start.
w:stop() w:stop()
watch_file(fname) watch_file(fname)
end end
function watch_file(fname) function watch_file(fname)
local fullpath = vim.api.nvim_call_function( local fullpath = vim.api.nvim_call_function('fnamemodify', {fname, ':p'})
'fnamemodify', {fname, ':p'}) w:start(fullpath, {}, vim.schedule_wrap(function(...) on_change(...) end))
w:start(fullpath, {}, vim.schedule_wrap(function(...)
on_change(...) end))
end end
vim.api.nvim_command( vim.api.nvim_command(
"command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))") "command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")