Commit d20de946 authored by David's avatar David

Making the build work

parent 91692093
Pipeline #12 failed with stage
in 1 minute and 8 seconds
......@@ -83,6 +83,9 @@ dependencies {
implementation 'com.github.Hopding:JRPiCam:1.1.1'
//Going to do much simpler oauth2
//compile 'org.pac4j:pac4j-oauth:3.6.1'
//Some extra java time classes that are potentially useful
implementation 'org.threeten:threeten-extra:1.5.0'
//Gonna use the DarkSky forecast info
......@@ -154,7 +157,11 @@ task runDesktop(type: JavaExec) {
environment += [
"JIRA_BASEURL": jiraBaseUrl,
"USERNAME": username,
"PASSWORD": password
"PASSWORD": password,
"REDDIT_USERNAME": redditUsername,
"REDDIT_PASSWORD": redditPassword,
"REDDIT_CLIENT_ID": redditClientId,
"REDDIT_SECRET": redditSecret
]
main = "is.kow.deskscreen.DesktopScreen"
}
......
deviceIp = 10.10.220.66
jiraBaseUrl = https://www.example.com
username = nope
password = nope
\ No newline at end of file
password = nope
redditUsername = nope
redditPassword = lol
redditClientId = huehuehueh
redditSecret = hahahaha
\ No newline at end of file
package `is`.kow.deskscreen.cat
import `is`.kow.deskscreen.MainController
import com.github.thomasnield.rxkotlinfx.doOnNextFx
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.Priority
import mu.KotlinLogging
import tornadofx.*
import java.util.concurrent.TimeUnit
class CatViewState {
val imageProperty = SimpleObjectProperty<Image>(this, "image", null)
var image by imageProperty
val urlProperty = SimpleStringProperty(this, "url", "")
val url by urlProperty
}
class CatViewStateModel : ItemViewModel<CatViewState>() {
val image = bind(CatViewState::imageProperty)
val url = bind(CatViewState::urlProperty)
}
class CatView : View() {
private val logger = KotlinLogging.logger {}
private val catViewStateModel: CatViewStateModel by inject()
private val mainController: MainController by inject()
private val redditCatService = RedditCatService(mainController.appConfig)
private val centerPane = borderpane {
vgrow = Priority.ALWAYS
hgrow = Priority.ALWAYS
}
override val root = borderpane {
vgrow = Priority.ALWAYS
hgrow = Priority.ALWAYS
center = centerPane
centerPane.center = imagePane
}
private val imagePane: ImageView = imageview {
imageProperty().bind(catViewStateModel.image)
this.fitHeightProperty().bind(root.heightProperty())
this.fitWidthProperty().bind(root.widthProperty())
this.isPreserveRatio = true
this.isSmooth = true
}
// we'll go ahead and get random cat pictures from my multi on reddit
override fun onDock() {
Observable.interval(0, 30, TimeUnit.SECONDS)
.observeOn(Schedulers.io())
.map {
redditCatService.catPictureUrl()
}
.doOnNext {
logger.debug("URL for image: $it")
}
.map {
Image(it)
}
.doOnNextFx {
catViewStateModel.image.value = it
}
.doOnError {
logger.error("Unable to load image: ${it.message}")
}
.retry()
.subscribe()
}
}
\ No newline at end of file
package `is`.kow.deskscreen.cat
import com.fasterxml.jackson.annotation.JsonProperty
import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.LoadingCache
import com.typesafe.config.Config
import mu.KotlinLogging
import org.apache.http.client.config.RequestConfig
import org.apache.http.impl.client.HttpClients
import org.http4k.client.ApacheClient
import org.http4k.core.Body
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.body.form
import org.http4k.core.then
import org.http4k.filter.ClientFilters
import org.http4k.filter.DebuggingFilters
import org.http4k.format.Jackson.auto
import org.http4k.format.Jackson.json
import java.util.concurrent.TimeUnit
class RedditCatService(config: Config) {
private val logger = KotlinLogging.logger {}
private final val TOKEN = "THISISTHETOKEN"
private val SUBREDDITS = "SUBREDDITS"
private val client = ApacheClient(
client = HttpClients.custom()
.setUserAgent("CatService 1.0")
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(5000) //5 seconds?
.setConnectionRequestTimeout(5000) //5 seconds?
.setSocketTimeout(5000) //5 seconds?
.build())
.build()
)
val debugHandler = DebuggingFilters.PrintRequestAndResponse().then(client)
private data class RedditTokenResponse(
@JsonProperty("access_token") val accessToken: String,
val scope: String,
@JsonProperty("expires_in") val expiresIn: Number,
@JsonProperty("token_type") val tokenType: String)
private val tokenCache: LoadingCache<String, String> = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build { key ->
//request a token from reddit
//application/x-www-form-urlencoded post a form
//reddit@reddit-VirtualBox:~$ curl -X POST -d 'grant_type=password&username=reddit_bot&password=snoo' --user 'p-jcoLKBynTLew:gko_LXELoV07ZBNUXrvWZfzE3aI' https://www.reddit.com/api/v1/access_token
val username = config.getString("reddit.username")
val password = config.getString("reddit.password")
val clientId = config.getString("reddit.client_id")
val secret = config.getString("reddit.secret")
logger.debug("me: $username $password")
logger.debug("reddit: $clientId $secret")
val authedHandler = ClientFilters.BasicAuth(clientId, secret).then(debugHandler)
val request = Request(Method.POST, "https://www.reddit.com/api/v1/access_token")
.form("grant_type", "password")
.form("username", username)
.form("password", password)
val result = authedHandler(request)
val tokenResponseLens = Body.auto<RedditTokenResponse>().toLens()
val json = tokenResponseLens(result)
json.accessToken
}
private val subredditCache: LoadingCache<String, List<String>> = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.DAYS)
.build { _ ->
val token = tokenCache.get(TOKEN)
//Lets get my multi
val request = Request(Method.GET, "https://oauth.reddit.com/api/multi/user/beep_dog/m/cats/")
.header("Authorization", "bearer $token")
val lens = Body.json().toLens()
// Multi info, including a list of subreddits
// https://oauth.reddit.com/api/multi/user/beep_dog/m/cats/
val thing = lens.extract(debugHandler(request)).at("/data/subreddits") //Then extract all the names
thing.map {
it.get("name").asText()
}.toList()
}
private fun randomSubreddit(): String {
return subredditCache.get(SUBREDDITS)!!.random()
}
private data class RedditListing(
val data: RedditListingData
)
private data class RedditListingData(
val dist: Number,
val children: List<RedditT3Data>
)
private data class RedditT3Data(
val kind: String,
val data: RedditPostData
)
private data class RedditPostData(
@JsonProperty("is_reddit_media_domain") val isRedditMediaDomain: Boolean,
@JsonProperty("over_18") val over18: Boolean,
val url: String
)
/**
* Return a url to a cat picture image!
*/
fun catPictureUrl(): String {
//Pick a random subreddit, and then do https://www.reddit.com/dev/api#GET_top /r/<subreddit>/top
val subreddit = randomSubreddit()
val request = Request(Method.GET, "https://oauth.reddit.com/r/$subreddit/top")
.query("t", "day")
.header("Authorization", "bearer ${tokenCache[TOKEN]}")
val result = debugHandler(request)
val redditListingLens = Body.auto<RedditListing>().toLens()
val redditListing = redditListingLens.extract(result)
val redditPostDatas = redditListing.data.children.map {
it.data
}.filter {
!it.over18 && it.isRedditMediaDomain
}
val rando = redditPostDatas.random().url
logger.debug("Rando url: $rando")
// /user/beep_dog/m/cats/
return rando
}
}
\ No newline at end of file
......@@ -2,6 +2,7 @@ package `is`.kow.deskscreen.views
import `is`.kow.deskscreen.DisplayController
import `is`.kow.deskscreen.TransitionsController
import `is`.kow.deskscreen.cat.CatView
import `is`.kow.deskscreen.jira.JiraView
import `is`.kow.deskscreen.temperature.TemperatureView
import `is`.kow.deskscreen.ticker.TickerView
......@@ -18,6 +19,7 @@ class DefaultView : View() {
private val tickerView: TickerView by inject()
private val namePlateView: NamePlateView by inject()
private val jiraView: JiraView by inject()
private val catView: CatView by inject()
private val temperatureView: TemperatureView by inject()
private val displayController: DisplayController by inject()
private val transitionsController: TransitionsController by inject()
......@@ -30,6 +32,7 @@ class DefaultView : View() {
center = vbox {
//TODO: cat view
//this.add(jiraView.root)
this.add(catView.root)
}
bottom = tickerView.root
......
......@@ -32,4 +32,15 @@ jira {
logging {
level = DEBUG
level = ${?LOG_LEVEL}
}
reddit {
username = "nope"
username = ${?REDDIT_USERNAME}
password = "nope"
password = ${?REDDIT_PASSWORD}
client_id = "nope"
client_id = ${?REDDIT_CLIENT_ID}
secret = "nope"
secret = ${?REDDIT_SECRET}
}
\ No newline at end of file
This diff is collapsed.
{
"kind": "LabeledMulti",
"data": {
"can_edit": true,
"display_name": "cats",
"name": "cats",
"description_html": "&lt;!-- SC_OFF --&gt;&lt;div class=\"md\"&gt;&lt;p&gt;copied from &lt;a href=\"/user/_regrettably/m/cats/\"&gt;/user/_regrettably/m/cats/&lt;/a&gt;&lt;/p&gt;\n&lt;/div&gt;&lt;!-- SC_ON --&gt;",
"num_subscribers": 0,
"copied_from": "/user/_regrettably/m/cats/",
"icon_url": "https://www.redditstatic.com/custom_feeds/custom_feed_default_0.png",
"subreddits": [
{
"name": "catsinboxes"
},
{
"name": "StartledCats"
},
{
"name": "TheCatTrapIsWorking"
},
{
"name": "catsonglass"
},
{
"name": "KneadyCats"
},
{
"name": "Thisismylifemeow"
},
{
"name": "stolendogbeds"
},
{
"name": "Catloaf"
},
{
"name": "Kitting"
},
{
"name": "SupermodelCats"
},
{
"name": "thecatdimension"
},
{
"name": "CatsISUOTTATFO"
},
{
"name": "StuffOnCats"
},
{
"name": "teefies"
},
{
"name": "TuxedoCats"
},
{
"name": "sploot"
},
{
"name": "CatsInBusinessAttire"
},
{
"name": "CatsInSinks"
},
{
"name": "boopablenosies"
},
{
"name": "SneakyPaws"
},
{
"name": "kittengifs"
},
{
"name": "CatTaps"
},
{
"name": "Blep"
},
{
"name": "blackcats"
},
{
"name": "toebeans"
},
{
"name": "IfIFitsISits"
},
{
"name": "CatsOnPizza"
},
{
"name": "CatSlaps"
},
{
"name": "jellybeantoes"
},
{
"name": "catbellies"
},
{
"name": "mlem"
},
{
"name": "curledfeetsies"
}
],
"created_utc": 1509048038.0,
"visibility": "private",
"created": 1509076838.0,
"over_18": false,
"path": "/user/beep_dog/m/cats/",
"owner": "beep_dog",
"key_color": "#cee3f8",
"is_subscriber": false,
"owner_id": "t2_68qeq",
"description_md": "copied from [/user/_regrettably/m/cats/](/user/_regrettably/m/cats/)",
"is_favorited": false
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment