LBRYVideoUpload:
LBRYAudioUpload:
;------------------------------------------------

if(LBRYUploadType = "Video"){
	CurrentSite := "LBRY Video"
	IniRead, LBRYPermanentURL, %VideoLinksIniFile%, Misc, LBRYVideoPermanentURL, %A_Space%

}
if(LBRYUploadType = "Audio"){
	CurrentSite := "LBRY Audio"
	IniRead, LBRYPermanentURL, %VideoLinksIniFile%, Misc, LBRYAudioPermanentURL, %A_Space%
}

; if LBRY permanent URL was already grabbed before, exit
if(LBRYPermanentURL != "")
Return

CheckLBRYProcess() ; double check lbry process


SaveOrPostProgress(Message:="Starting Upload",PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

TooltipThis("Uploading Video through API")
; Variables of items that need to be replaced before argument is passed to API
Apostrophe = '
LBRYTags =  ; Create empty variable
SingleQuotationmark = " 
EscapedQuotationMark = \"

; Replace all items to make text passable to API
LBRYVideoTitle :=  StrReplace(VideoTitle, SingleQuotationmark, EscapedQuotationMark) ; replace all spaces with dashes 
LBRYVideoDescription := StrReplace(VideoDescription, SingleQuotationmark, EscapedQuotationMark)

if(StrLen(LBRYVideoDescription) >= 5000){
	LBRYVideoDescription := SubStr(LBRYVideoDescription, 1, 4990)
	LBRYVideoDescription .= "...."
}

if(LBRYUploadType = "Video"){
	Message = Uploading through API with URL Slug: %LBRYURLSlug%
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

	FilePathForLBRYAPI := VideoFilepath

}

if(LBRYUploadType = "Audio"){
	; Replace all items to make text passable to API
	LBRYVideoTitle .= " (Audio)"
	LBRYURLSlug .= "_Audio"
	Message = Uploading through API with URL Slug: %LBRYURLSlug%
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

	FilePathForLBRYAPI := WavAudioFilepath
}

; if no lbry slug, then error out
if(LBRYURLSlug = "" OR LBRYURLSlug = "_Audio"){
	Message = Upload Failed because no URL Slug was provided.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}



; loops through array and creates a string of: --tags="tag1" --tags="tag2" --tags="tag3" so that it can be passed to lbrynet
Loop % KeywordsArray.Length(){ 
	LBRYTags .= "--tags=" . SingleQuotationmark ArrayOfVideoTags[A_Index] . SingleQuotationmark . " "
}

; Msgbox % "FilePathForLBRYAPI: " FilePathForLBRYAPI

SplitPath, VideoThumbFilepath, ThumbnailFileNameWExt, OutDir, OutExtension, OutNameNoExt, OutDrive

FDRThumbnailURL = https://cdn.freedomainradio.com/%ThumbnailFileNameWExt%
message = FDRThumbnailURL: %FDRThumbnailURL%
SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile,DiscordErrorLogging")


; Msgbox % "FDRThumbnailURL: " FDRThumbnailURL
; Create API Command and save it to variable
LBRYAPICommand = "%LBRYNetFilepath%" publish --name="%LBRYURLSlug%" --bid="%LBRYNewVideoStakeAmount%" --file_path="%FilePathForLBRYAPI%" --title="%LBRYVideoTitle%" --description="%LBRYVideoDescription%" %LBRYTags% --thumbnail_url="%FDRThumbnailURL%" --channel_id="%LBRYChannelID%"


; LogErrorToTextFile(LBRYAPICommand) ; Log to file
LogErrorToTextFile("LBRYAPICommand: " LBRYAPICommand)

; Parse returned API json for success status
UploadResult := StdOutToVar(LBRYAPICommand)






if(InStr(UploadResult, "Could not connect")){
	Message = Upload Failed. Reason: %UploadResult%
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}

if(UploadResult = ""){
	Message = LBRYNet did not return anything. LBRY not running?
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}

; Msgbox % "UploadResult: " UploadResult
try parsed := JSON.Load(UploadResult)
try UploadStatus := parsed.height

; Msgbox % "UploadStatus: " UploadStatus

; -2 is returned if upload was successful
if(UploadStatus != "-2"){
	; msgbox, error
	ErrorCode := parsed.message
	ErrorCode := parsed.message
	ErrorCode := StrSplit(ErrorCode, "code")
	ErrorCode := ErrorCode[1]

	Message = LBRY Upload Failed`nReason: %ErrorCode%
	; Msgbox % "Message: " Message
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}



; Clipboard := UploadResult
; Msgbox % "UploadResult: " UploadResult


LogErrorToTextFile("UploadResult: " UploadResult)

if(InStr(UploadResult, "Could not connect to daemon")){
	if(LBRYAttemptNumber = 2){

		Message = Upload Error (E#4081)`nVideo Upload Failed due to daemon not running.`nPlease start it manually and re-run the upload.		
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

		try run, %LBRYKillerPath% "Kill"
		catch e {
			; Message = Unable to Kill LBRYKiller.ahk
			; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")  
		}
		Return
	}
	else, { ; if attempt number 1
		Process, Close, LBRY.exe ; terminate LBRY if it's running
		LBRYAttemptNumber := 2
		Message = Upload Failed (E#1980)`nDue to daemon not running.`nTrying to restart LBRY.exe and try the upload again. 
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
		Goto, LBRYVideoUpload
	}
}

; Clipboard := UploadResult
; Msgbox % "UploadResult: " UploadResult

/*if(DevMode){
	Clipboard := UploadResult
	Msgbox % "UploadResult: " UploadResult
}
*/
; Create an object out of the API Return
LBRYJSONResult := JSON.Load(UploadResult)

if(!InStr(UploadResult, "permanent_url")){ ; if no permanent_url is generated then API issue
	LBRYAPIError := LBRYJSONResult.message
	; LBRYAPIError := GetLBRYAPIErrorFromString(UploadResult)
	; if the returned string does not have "permanent_url" in it, then upload failed
	Message = Upload Error (E#6930)`nVideo Upload Failed due to API Issue. Please send errorlog to Yuriy.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}


; Transform the Upload Result json into the LBRY.tv link
; PermanentURL := GetPermanentLBRYURL(UploadResult) ; get permanentURL from the upload result json
LBRYPermanentURL := LBRYJSONResult.outputs[1].permanent_url
if(LBRYPermanentURL = ""){
	Message = Failed to grab permanent_url with json.ahk. Please send errorlog to Yuriy.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
	Return
}


Message = Claim Was Successfully Submitted to lbrynet with: %LBRYPermanentURL%
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

; Message = LBRYPermanentURL: %LBRYPermanentURL%
; SaveOrPostProgress(Message:=Message,PostType:=",ErrorLoggingTextFile")

if(CurrentSite = "LBRY Video"){
	IniWrite, %LBRYPermanentURL%, %VideoLinksIniFile%, Misc, LBRYVideoPermanentURL
}

if(CurrentSite = "LBRY Audio"){
	IniWrite, %LBRYPermanentURL%, %VideoLinksIniFile%, Misc, LBRYAudioPermanentURL
}
Return




LBRYGetURL:
;------------------------------------------------
if(LBRYUploadType = "Video"){

	CurrentSite := "LBRY Video"
	; IniWrite, %PermanentURL%, %VideoLinksIniFile%, URLs, LBRYVideoPermanentURL
	IniRead, LBRYPermanentURL, %VideoLinksIniFile%, Misc, LBRYVideoPermanentURL, %A_Space%
}
if(LBRYUploadType = "Audio"){

	CurrentSite := "LBRY Audio"
	IniRead, LBRYPermanentURL, %VideoLinksIniFile%, Misc, LBRYAudioPermanentURL, %A_Space%

}

if(LBRYPermanentURL = ""){
	Message = Upload Skipped. LBRYPermanentURL is blank (Upload Failed due to some API issue)
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}

; Message := "Waiting a couple of minutes for lbrynet blockchain to generate blockchain metadata for newest video"
Message = Waiting for LBRYNet to Generate LBRY URL
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
; sleep, 60000 ; 1 minute
; sleep, 300000 ; sleep for 5 minutes so LBRYNet blockchain has a chance to register the new video ; as recomended by LBRY Devs
; sleep, 360000 ; sleep for 6 minutes so LBRYNet blockchain has a chance to register the new video ; LBRY devs recommend 5 mins


LBRYResolveAPICommand = "%LBRYNetFilepath%" resolve %LBRYPermanentURL% ; create variable with the text that's needed for the API command
Message := "LBRYResolveAPICommand: " . LBRYResolveAPICommand ; Save the result to the errorlogging file
SaveOrPostProgress(Message:=Message,PostType:=",ErrorLoggingTextFile")

; msgbox

loop, 15 {
	LBRYResolveResult := StdOutToVar(LBRYResolveAPICommand) ; Save API call to a variable 

	if(A_index = 1 OR a_index = 10){
		Message := "LBRYResolveResult: " . LBRYResolveResult ; Save result to the errorlogging file
		SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile")
	}

	if(InStr(LBRYResolveResult, "could not find claim") AND A_Index < 10) ; try 4 times to get the resolveURL, sometimes the blockchain is quite slow
	{
		; @todo: Make it check every 2 minutes?
		; TooltipThis("Not Able to Grab URL from API. `nWaiting another 5 for blockchain to sync claim before trying again")
		; MessageNumber := A_index + 5

		if(A_index < 5)
		Message = Waiting for LBRYNet to Generate LBRY URL`nChecking Every 2 Minutes
		if(A_index > 5)
		Message = Still Waiting for LBRYNet to Generate LBRY URL`nLBRY Network is most likely congested.`nChecking Every 2 Minutes

		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
		; sleep, 300000 ; 5 minutes
		sleep, 120000 ; 2 minute

		Continue
	}

	if(InStr(LBRYResolveResult, "could not find claim") AND A_index = 15){
		Message = Failed to Grab URL from LBRY after 30 minutes. Either LBRY IS REALLY congested or there is a bug and the API commands were passed incorrectly.
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		Return
	}

	if(InStr(LBRYResolveResult, "canonical_url"))
	Break
}


if(LBRYUploadType = "Video"){
	LBRYVideoURL := GetLBRYCanonicalURL(LBRYResolveResult)  ; Transform the API resulting json into the LBRY.tv link
	if(LBRYVideoURL = ""){
		Message = Failed to Grab LBRY URL from LBRYNet
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		Return
	}

	; DevModeMsgBox(LBRYVideoURL)

	Message = LBRYVideoURL from GetLBRYCanonicalURL: %LBRYVideoURL%
	SaveOrPostProgress(Message, PostType:=",ErrorLoggingTextFile")

	OpenLBRYVideoURL := StrReplace(LBRYVideoURL, "https://lbry.tv", "https://open.lbry.com")
	OpenLBRYVideoURL := StrReplace(OpenLBRYVideoURL, "#", ":")


	OdyseeVideoURL := StrReplace(LBRYVideoURL, "https://lbry.tv", "https://odysee.com")
	OdyseeVideoURL := StrReplace(OdyseeVideoURL, "#", ":")

	Message = Upload Complete: <%OpenLBRYVideoURL%> + <%OdyseeVideoURL%>
	SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile,DiscordErrorLogging")

	IniWrite, %OpenLBRYVideoURL%, %VideoLinksIniFile%, URLs, LBRYVideoURL
	IniWrite, %OdyseeVideoURL%, %VideoLinksIniFile%, URLs, OdyseeVideoURL

}
if(LBRYUploadType = "Audio"){
	LBRYAudioURL := GetLBRYCanonicalURL(LBRYResolveResult)  ; Transform the API resulting json into the LBRY.tv link
	if(LBRYAudioURL = ""){
		Message = Failed to Grab LBRY URL from LBRYNet
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		Return
	}

	Message = LBRYAudioURL from GetLBRYCanonicalURL: %LBRYAudioURL%
	SaveOrPostProgress(Message, PostType:=",ErrorLoggingTextFile")

	OpenLBRYAudioURL := StrReplace(LBRYAudioURL, "https://lbry.tv", "https://open.lbry.com")
	OpenLBRYAudioURL := StrReplace(OpenLBRYAudioURL, "#", ":")

	OdyseeAudioURL := StrReplace(LBRYAudioURL, "https://lbry.tv", "https://odysee.com")
	OdyseeAudioURL := StrReplace(OdyseeAudioURL, "#", ":")

	Message = Upload Complete: <%OpenLBRYAudioURL%> + <%OdyseeAudioURL%>
	SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile,DiscordErrorLogging")

	IniWrite, %OpenLBRYAudioURL%, %VideoLinksIniFile%, URLs, LBRYAudioURL
	IniWrite, %OdyseeAudioURL%, %VideoLinksIniFile%, URLs, OdyseeAudioURL
}

if(!LBRYKillerStarted){

	; If LBRY Killer not found, then download it
	; @todo: Add LBRY kill download functionality from gitea
	LBRYKillerPath := LibFolder . "\LBRY Process Killer.exe" 
	if(!FileExist(LBRYKillerPath)){

		; Msgbox % "LBRYKillerPath: " LBRYKillerPath
		; Msgbox % "LBRYProcessKillerURL: " LBRYProcessKillerURL
		LBRYKillerPath = %A_ScriptDir%\Lib\LBRY Process Killer.exe
		LBRYKillerUpdateURL = https://freedomain.dev/yuriy/video-uploader/raw/branch/main/Modules/LBRY-Process-Killer.exe

		Message = LBRY Process Killer Not Found. Automatically Downloading.
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

		UrlDownloadToFile, %LBRYKillerUpdateURL%, %LBRYKillerPath%
		if(ErrorLevel){
			Message = Failed to download the the LBRY-Killer.exe from %LBRYKillerUpdateURL%
			SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
			Return
		}

	}

	if(KillLBRYAfterUpload){
		try run, %LBRYKillerPath%
		catch e {
			Message = LBRYKiller not found. Unable to find File.
			SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		}
		LBRYKillerStarted := 1
	}

}
; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
; SaveDriverURL()
AddToTotalVideosUploadedCount()
Return