Coder Social home page Coder Social logo

koonsplash's Introduction

CircleCI codecov.io

Koonsplash

Unofficial client side Kotlin wrapper for Unsplash API.

Usage

runBlocking {
    val api = Koonsplash.builder("my-access-key-client-id")
                .openLinksStrategy {
                    //if _openLinksStrategy_ is not set. Koonsplash will try to open browser 
                    //or photo links using os terminal.
                    Desptop.browse(it)
                    Result.success(Unit)
                }
                .build()
                .authenticated(
                    Koonsplash.AuthenticatedBuilder("secret-key".toCharArray())
                        .scopes(AuthScope.PUBLIC + AuthScope.READ_USER + AuthScope.WRITE_USER)
                )   
                .api
    val me = api.endpoint("/me").call()
    val myLikesLink: Link.Api = me["links"]["likes"]()
    val firstLikedPhoto = myLikesLink.call()[0]
    val link: Link.Download = firstLikedPhoto["links"]["download_location"]()
    val photo: Link.Browser = link.download(File("<path>"), id)
    // or with progress
    link
        .downloadWithProgress(File("<path>"), id)
        .collect { status ->
            when (status) {
                is ApiCall.Status.Canceled -> status.err.printStackTrace()
                is ApiCall.Status.Current  -> println("Progress: ${status.value}%")
                is ApiCall.Status.Done     -> status.resource.open()
                is ApiCall.Status.Starting -> println("Starting")
            }
        }
}        

DSL Support for image resizing

val photo: Link.Photo = firstLikedPhoto["urls"]["raw"]
val resizedPhoto = photo.resize{
    500u.w
    500u.h
    fit(Fit.CROP)
    crop(Crop.TOP, Crop.LEFT)
    100.q
    fm(Fm.PNG)
}.toDownloadLink()
val saved: Link.Browser = resizedPhoto.download(File("<path>"), "my-resized-photo")
saved.open()

Cancelling a request

val cancelButton = MutableSharedFlow<Unit>()
launch {
   val photo = api.call("/photos/random").cancelable(cancelFlow)
   if(photo != null){
     val link: Link.Download = photo["links"]["download_location"]()
     //...
   }else{
     //request was manually canceled
     showMessage("Canceled")
   }
}
launch {
   api.call("/photos/random")
        .cancelableExecute(cancelFlow)
        .collect{ status ->
            when (status) {
                is ApiCall.Status.Starting -> showProgressBar()
                is ApiCall.Status.Current -> updateProgressBar(status.value)
                is ApiCall.Status.Done -> {
                    hideProgressBar()
                    val photo = status.resource()
                    //....
                }
                is ApiCall.Status.Canceled -> {
                    hideProgressBar()
                    showMessage("Canceled")
                }           
            }
        }
}
//pressing the supposed button will cancel the request.
launch {
    delay(1000)
    cancelButton.emit(Unit)
}

Work in progress...

koonsplash's People

Contributors

criske avatar

Watchers

 avatar  avatar

koonsplash's Issues

Make Koonsplash/KoonsplashAuth singleton.

After init / auth, clients should be able to call Koonsplash/KoonsplashAuth from anywhere using this extension Koonsplash.instance. This extension will return Koonsplash or KoonsplashAuth depending on context.

All api calls should be done in background by default.

It assumes that for example apu.raw()() is running on IO CoroutineDisptacher, no need for client to explicit launch a coroutine with IO dispatcher.

Might let client customize it by passing their own Dispatcher for api calls in Koonsplash builder.

Link entity for ApiJson.

Any url string values from ApiJson should be converted to a Link object.
There would these types of links:

  • JsonLink (if link points to api resource). Json link should use the api.call("url")
  • PhotoLink (if link points to a photo). Photo links can be "opened" or "downloaded"
  • BrowserLink (if link can be opened in a browser).

Abstraction for api call result.

Right now the api call result is just json as string.
Client should be able to traverse this json and also should be able find links from json. This links can be opened or downloaded if the case,

Create AccessContext.

This context should encapsultate the access key and the auth token, because these two are used across the lib.
authToken must check on call if client is signed out (returning null will be suffice).

Create a raw api call feature available for 0.1 release

Design thought:

launch {
 val api  = Koonsplash.build()...api
 val randomPhoto = api.raw("/photos/random")()
 val preparedPhoto = api.raw("/photos/{id}")
 val photo1 = preparedPhoto ("id1")
 val photo2 = preparedPhoto ("id2")
// assuming api is authenticated
 api.raw("/me", verb = PUT("username" to "john_doe"))()
}

Start first draft for authenticated Koonsplash

The root class will be Koonsplash that has the api keys.
Koonsplash#authenticated supendable will return AuthKoonsplash. Internally this method will use Authorizer#authorize for OAuth2 flow and get the AuthToken.

AuthKoonsplash then should have methods.

  • signOut
  • api (api should access all methods that require AuthToken, access will be async using coroutines)

Make `AuthScope` composable.

Also add AuthScope.ALL for all scopes.
AuthScope should support adding and subtraction.
So instead of passing a list o auth scopes on auth, clients should pass a composition of scopes.
When adding it should ignore if the scope was already added.
When subtracting if scope was not presesnt then should ignore (subtraction usually should be applied on ALL)
Use cases:

  • AuthScope.PUBLIC + AuthScope.READ_USER
  • AuthScope.ALL
  • AuthScope.ALL - AuthScope.READ_USER (excludes read_user scope from all)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.