Maintenance Tasks Added

This commit is contained in:
shabinder 2021-05-18 20:27:33 +05:30
parent 6fbd933b8f
commit 62e110b8c6
8 changed files with 308 additions and 0 deletions

View File

@ -0,0 +1,18 @@
@file:Suppress("FunctionName")
package analytics_html_img
import utils.byProperty
internal object Common {
const val GITHUB_API = "https://api.github.com"
val GITHUB_TOKEN get() = "GITHUB_TOKEN".byProperty
fun START_SECTION(tagName: String = "HTI") = "<!--START_SECTION:$tagName-->"
fun END_SECTION(tagName: String = "HTI") = "<!--END_SECTION:$tagName-->"
const val USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0"
}
internal data class GithubFileContent(
val decryptedContent: String,
val sha: String
)

View File

@ -0,0 +1,88 @@
package analytics_html_img
import io.ktor.client.HttpClient
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.headers
import io.ktor.client.request.put
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.util.InternalAPI
import io.ktor.util.encodeBase64
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
internal val client = HttpClient {
install(JsonFeature) {
serializer = KotlinxSerializer(
Json {
ignoreUnknownKeys = true
isLenient = true
}
)
}
}
internal object GithubService {
private const val baseURL = Common.GITHUB_API
suspend fun getGithubFileContent(
token: String,
ownerName: String,
repoName: String,
branchName: String,
fileName: String,
): GithubFileContent {
val resp = client.get<JsonObject>("$baseURL/repos/$ownerName/$repoName/contents/$fileName?ref=$branchName") {
headers {
header("Authorization", "token $token")
}
}
// Get Raw Readme File
val decodedString = client.get<String>("https://raw.githubusercontent.com/$ownerName/$repoName/$branchName/$fileName") {
headers {
header("Authorization", "token $token")
}
}
return GithubFileContent(
decryptedContent = decodedString,
sha = resp["sha"]?.jsonPrimitive.toString()
.removeSurrounding("\"")
)
}
@OptIn(InternalAPI::class)
suspend fun updateGithubFileContent(
token: String,
ownerName: String,
repoName: String,
branchName: String,
fileName: String,
commitMessage: String,
rawContent: String,
sha: String
): JsonObject {
return client.put<JsonObject>("$baseURL/repos/$ownerName/$repoName/contents/$fileName") {
body = buildJsonObject {
put("branch", branchName)
put("message", commitMessage)
put("content", rawContent.encodeBase64())
put("sha", sha)
/*put("committer", buildJsonObject {
put("name","Shabinder Singh")
put("email","dev.shabinder@gmail.com")
})*/
}
headers {
header("Authorization", "token $token")
contentType(ContentType.Application.Json)
}
}
}
}

View File

@ -0,0 +1,88 @@
package analytics_html_img
import io.ktor.client.request.header
import io.ktor.client.request.headers
import io.ktor.client.request.post
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.http.userAgent
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import utils.HCTI_URL_RESPONSE_ERROR
internal object HCTIService {
private const val baseURL = "https://htmlcsstoimage.com/demo_run"
/*
* - When Using Either Viewport Width/Height(in Pixels) , Both are required
* */
suspend fun getImageURLFromHtml(
html: String,
css: String = "",
delayInMilliSeconds: Int = 250,
viewPortHeight: String = "",
viewPortWidth: String = "",
deviceScale: Int = 2
) = getImageURL(
mode = "html",
data = html,
css = css,
delayInMilliSeconds = delayInMilliSeconds,
viewPortHeight = viewPortHeight,
viewPortWidth = viewPortWidth,
deviceScale = deviceScale
)
suspend fun getImageURLFromURL(
url: String,
delayInMilliSeconds: Int = 250,
viewPortHeight: String = "",
viewPortWidth: String = "",
deviceScale: Int = 2
) = getImageURL(
mode = "url",
data = url,
delayInMilliSeconds = delayInMilliSeconds,
viewPortHeight = viewPortHeight,
viewPortWidth = viewPortWidth,
deviceScale = deviceScale
)
private suspend fun getImageURL(
mode: String, // html/url
data: String,
css: String = "",
viewPortHeight: String = "",
viewPortWidth: String = "",
delayInMilliSeconds: Int = 250,
deviceScale: Int = 2,
): String {
val resp = client.post<JsonObject>(baseURL) {
body = buildJsonObject {
put(mode, data)
put("console_mode", "")
put("css", css)
put("selector", "")
put("ms_delay", "$delayInMilliSeconds")
put("render_when_ready", "")
put("viewport_width", viewPortWidth)
put("viewport_height", viewPortHeight)
put("google_fonts", "")
put("device_scale", "$deviceScale")
}
headers {
contentType(ContentType.Application.Json)
userAgent(Common.USER_AGENT)
header("Referer", "https://htmlcsstoimage.com/demo")
header("Origin", "https://htmlcsstoimage.com")
header("Host", "htmlcsstoimage.com")
}
}
val url = resp["url"] ?: throw HCTI_URL_RESPONSE_ERROR(response = resp.toString())
// bubble-up exceptions
return url.jsonPrimitive.toString().removeSurrounding("\"")
}
}

View File

@ -0,0 +1,27 @@
package analytics_html_img
import utils.byOptionalProperty
import utils.byProperty
internal data class Secrets(
val githubToken: String,
val ownerName: String,
val repoName: String,
val branchName: String,
val filePath: String,
val imageDescription: String,
val commitMessage: String,
val tagName: String
)
internal fun initSecrets() = Secrets(
githubToken = "GH_TOKEN".byProperty,
ownerName = "OWNER_NAME".byProperty,
repoName = "REPO_NAME".byProperty,
branchName = "BRANCH_NAME".byOptionalProperty ?: "main",
filePath = "FILE_PATH".byOptionalProperty ?: "README.md",
imageDescription = "IMAGE_DESCRIPTION".byOptionalProperty ?: "IMAGE",
commitMessage = "COMMIT_MESSAGE".byOptionalProperty ?: "HTML-TO-IMAGE Update",
tagName = "TAG_NAME".byOptionalProperty ?: "HTI"
// hctiKey = "HCTI_KEY".analytics_html_img.getByProperty
)

View File

@ -0,0 +1,58 @@
package analytics_html_img
import kotlinx.coroutines.runBlocking
import utils.debug
internal fun updateAnalyticsImage() {
val secrets = initSecrets()
// debug("fun main: secrets -> $secrets")
runBlocking {
val oldGithubFile = GithubService.getGithubFileContent(
token = Common.GITHUB_TOKEN,
ownerName = secrets.ownerName,
repoName = secrets.repoName,
branchName = secrets.branchName,
fileName = "README.md"
)
debug("OLD FILE CONTENT:\n$oldGithubFile")
/*
* Use Any Random useless query param ,
* As HCTI Demo, `caches value for a specific Link`
* */
val randomID = (1..100000).random()
val imageURL = HCTIService.getImageURLFromURL(
url = "https://kind-grasshopper-73.telebit.io/matomo/index.php?module=Widgetize&action=iframe&containerId=VisitOverviewWithGraph&disableLink=0&widget=1&moduleToWidgetize=CoreHome&actionToWidgetize=renderWidgetContainer&idSite=1&period=week&date=today&disableLink=1&widget=$randomID",
delayInMilliSeconds = 5000
)
debug("Updated IMAGE:\n$imageURL")
val replacementText = """
${Common.START_SECTION(secrets.tagName)}
![Today's Analytics]($imageURL)
${Common.END_SECTION(secrets.tagName)}
""".trimIndent()
// debug("Updated Text to be Inserted:\n$replacementText")
val regex = """${Common.START_SECTION(secrets.tagName)}(?s)(.*)${Common.END_SECTION(secrets.tagName)}""".toRegex()
val updatedContent = regex.replace(
oldGithubFile.decryptedContent,
replacementText
)
// debug("Updated File Content:\n$updatedContent")
val updationResponse = GithubService.updateGithubFileContent(
token = Common.GITHUB_TOKEN,
ownerName = secrets.ownerName,
repoName = secrets.repoName,
branchName = secrets.branchName,
fileName = secrets.filePath,
commitMessage = secrets.commitMessage,
rawContent = updatedContent,
sha = oldGithubFile.sha
)
debug("File Updation Response:\n$updationResponse")
}
}

View File

@ -0,0 +1,9 @@
import analytics_html_img.updateAnalyticsImage
import utils.debug
fun main(args: Array<String>) {
debug("fun main: args -> ${args.joinToString(";")}")
// Update Analytics Image in Readme
updateAnalyticsImage()
}

View File

@ -0,0 +1,12 @@
@file:Suppress("ClassName")
package utils
data class ENV_KEY_MISSING(
val keyName: String,
override val message: String? = "$keyName was not found, please check your ENV variables"
) : Exception(message)
data class HCTI_URL_RESPONSE_ERROR(
val response: String,
override val message: String? = "Server Error, We Recieved this Resp: $response"
) : Exception(message)

View File

@ -0,0 +1,8 @@
package utils
val String.byProperty: String get() = System.getenv(this)
?: throw (ENV_KEY_MISSING(this))
val String.byOptionalProperty: String? get() = System.getenv(this)
fun debug(message: String) = println("::debug::$message")