Repository: JakeWharton/dodo Branch: trunk Commit: 0ba2fe7bb2d6 Files: 38 Total size: 56.5 KB Directory structure: gitextract__ur9wtr5/ ├── .dockerignore ├── .editorconfig ├── .github/ │ └── workflows/ │ ├── build.yaml │ └── build_and_publish.yaml ├── .gitignore ├── CHANGELOG.md ├── Dockerfile ├── LICENSE.txt ├── README.md ├── RELEASING.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── renovate.json ├── root/ │ ├── app/ │ │ └── sync.sh │ └── etc/ │ ├── cont-init.d/ │ │ ├── 10-adduser.sh │ │ └── 20-cron.sh │ └── services.d/ │ ├── cron/ │ │ └── run │ └── dodo/ │ └── run ├── settings.gradle └── src/ ├── main/ │ ├── kotlin/ │ │ └── com/ │ │ └── jakewharton/ │ │ └── dodo/ │ │ ├── app.kt │ │ ├── db.kt │ │ ├── html.kt │ │ ├── main.kt │ │ └── twitter4j.kt │ ├── resources/ │ │ ├── logback.xml │ │ └── static/ │ │ └── app.js │ └── sqldelight/ │ ├── com/ │ │ └── jakewharton/ │ │ └── dodo/ │ │ └── db/ │ │ ├── tweet.sq │ │ └── tweetIndex.sq │ └── migrations/ │ ├── 1.sqm │ ├── 2.sqm │ ├── 3.sqm │ ├── 4.sqm │ └── 5.sqm └── test/ └── kotlin/ └── com/ └── jakewharton/ └── dodo/ ├── Twitter4jTest.kt └── twitter4jFakes.kt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ /.git /.gradle /build ================================================ FILE: .editorconfig ================================================ root = true [*] indent_style = tab indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yaml] indent_style = space ================================================ FILE: .github/workflows/build.yaml ================================================ name: build on: pull_request: push: branches: - '**' - '!trunk' env: GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Validate Gradle Wrapper uses: gradle/wrapper-validation-action@v1 - name: Build run: docker build . ================================================ FILE: .github/workflows/build_and_publish.yaml ================================================ name: build and publish on: push: branches: - trunk tags: - '*' env: GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: gradle/wrapper-validation-action@v1 - uses: actions/setup-java@v3 with: distribution: 'zulu' java-version: 8 - run: ./gradlew build - uses: crazy-max/ghaction-docker-meta@v1 id: docker_meta with: images: | jakewharton/dodo ghcr.io/jakewharton/dodo tag-semver: | {{version}} {{major}} {{major}}.{{minor}} - uses: docker/login-action@v2 with: username: jakewharton password: ${{ secrets.DOCKER_HUB_TOKEN }} - run: echo ${{ secrets.GHCR_TOKEN }} | docker login ghcr.io -u $GITHUB_ACTOR --password-stdin - uses: docker/build-push-action@v4 with: push: true tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} - name: Extract release notes id: release_notes if: startsWith(github.ref, 'refs/tags/') uses: ffurrer2/extract-release-notes@v1 - name: Create Release if: startsWith(github.ref, 'refs/tags/') uses: softprops/action-gh-release@v1 with: body: ${{ steps.release_notes.outputs.release_notes }} files: build/distributions/dodo.zip env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Get version id: get_version if: startsWith(github.ref, 'refs/tags/') run: echo ::set-output name=version::${GITHUB_REF/refs\/tags\//} - name: Set SHA id: shasum if: startsWith(github.ref, 'refs/tags/') run: echo ::set-output name=sha::"$(shasum -a 256 build/distributions/dodo.zip | awk '{printf $1}')" - name: Bump Brew if: startsWith(github.ref, 'refs/tags/') env: HOMEBREW_GITHUB_API_TOKEN: ${{ secrets.GH_HOMEBREW_TOKEN }} run: | git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" git config --global user.name "github-actions[bot]" # Update to ensure we have the latest version which supports arbitrary default branches. brew update brew tap JakeWharton/repo brew bump-formula-pr -f --version=${{ steps.get_version.outputs.version }} --no-browse --no-audit \ --sha256=${{ steps.shasum.outputs.sha }} \ --url="https://github.com/JakeWharton/dodo/releases/download/${{ steps.get_version.outputs.version }}/dodo.zip" \ JakeWharton/repo/dodo ================================================ FILE: .gitignore ================================================ # Gradle build .gradle /reports # IntelliJ .idea ================================================ FILE: CHANGELOG.md ================================================ # Changelog ## [Unreleased] ## [1.1.0] Features: * Persist account names at the time of tweet/retweet/quote Fixed: * Display actual tweet timestamp and render with browser timezone and locale ## [1.0.0] - Initial release [Unreleased]: https://github.com/JakeWharton/dodo/compare/1.1.0...HEAD [1.1.0]: https://github.com/JakeWharton/dodo/releases/tag/1.1.0 [1.0.0]: https://github.com/JakeWharton/dodo/releases/tag/1.0.0 ================================================ FILE: Dockerfile ================================================ FROM adoptopenjdk:8-jdk-hotspot AS build ENV GRADLE_OPTS="-Dorg.gradle.daemon=false -Dkotlin.incremental=false" WORKDIR /app COPY gradlew settings.gradle ./ COPY gradle ./gradle RUN ./gradlew --version COPY build.gradle ./ COPY src ./src RUN ./gradlew build FROM koalaman/shellcheck-alpine:stable AS shellcheck WORKDIR /overlay COPY root/ ./ RUN find . -type f | xargs shellcheck -e SC1008 FROM mvdan/shfmt:v3-alpine AS shfmt WORKDIR /overlay COPY root/ ./ COPY .editorconfig / RUN shfmt -d . FROM oznu/s6-alpine:3.11 LABEL maintainer="Jake Wharton " RUN apk add --no-cache \ curl \ openjdk8-jre \ && rm -rf /var/cache/* \ && mkdir /var/cache/apk ENV \ # Fail if cont-init scripts exit with non-zero code. S6_BEHAVIOUR_IF_STAGE2_FAILS=2 \ CRON="" \ ACCESS_TOKEN="" \ ACCESS_SECRET="" \ API_KEY="" \ API_SECRET="" \ HEALTHCHECK_ID="" \ HEALTHCHECK_HOST="https://hc-ping.com" \ PUID="" \ PGID="" COPY root/ / WORKDIR /app COPY --from=build /app/build/install/dodo ./ ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Dodo Synchronize your Twitter timeline to a local database for archival and search. ![Screenshot of web interface](screenshot.png) Available as a binary and Docker container. ## Usage Dodo consumes data from Twitter and requires you register your own Twitter application for keys: https://developer.twitter.com/en/apply-for-access You will need an OAuth access token and access secret as well as an API key and secret. From there, you can run Dodo in one of two ways: * [Command line](#command-line) * [Docker](#docker) ### Command-line Install on Mac OS with: ``` $ brew install JakeWharton/repo/dodo ``` For other platforms, download ZIP from [latest release](https://github.com/JakeWharton/dodo/releases/latest) and run `bin/dodo` or `bin/dodo.bat`. Dodo can run in two modes: - One-off syncs via `sync` subcommand, or - Long-running web-server with manual syncs ``` $ dodo --help Usage: dodo [OPTIONS] COMMAND [ARGS]... Options: -h, --help Show this message and exit Commands: sync Perform a one-time sync of the latest tweets run Start an HTTP server for displaying tweets and performing syncs ``` The `sync` subcommand will perform a one-off sync to the specified Sqlite database file. You can run it on a cron and use `sqlite3` or any Sqlite-capable tool to consume the data. ``` $ dodo sync --help Usage: dodo sync [OPTIONS] Perform a one-time sync of the latest tweets Options: --db FILE Sqlite database file --access-token KEY OAuth access token --access-secret KEY OAuth access token secret --api-key KEY OAuth consumer API key --api-secret KEY OAuth consumer API secret -h, --help Show this message and exit ``` The `run` subcommand will start a webserver with a search and manual sync interface. You can also POST the `/sync` endpoint to trigger a sync, such as on a cron. ``` $ dodo run --help Usage: dodo run [OPTIONS] Start an HTTP server for displaying tweets and performing syncs Options: --db FILE Sqlite database file --access-token KEY OAuth access token --access-secret KEY OAuth access token secret --api-key KEY OAuth consumer API key --api-secret KEY OAuth consumer API secret --port PORT Port for the HTTP server (default 8098) -h, --help Show this message and exit ``` ## Docker The container starts the webserver on port 8098 and automatically triggers sync using cron. [![Docker Image Version](https://img.shields.io/docker/v/jakewharton/dodo?sort=semver)][hub] [![Docker Image Size](https://img.shields.io/docker/image-size/jakewharton/dodo)][layers] [hub]: https://hub.docker.com/r/jakewharton/dodo/ [layers]: https://microbadger.com/images/jakewharton/dodo ``` $ docker run -it --rm \ -v /path/to/data:/data \ -e "CRON=*/3 * * * *" \ -e "ACCESS_TOKEN=..." \ -e "ACCESS_SECRET=..." \ -e "API_KEY=..." \ -e "API_SECRET=..." \ jakewharton/dodo:trunk ``` To be notified when sync is failing visit https://healthchecks.io, create a check, and specify the ID to the container using the `HEALTHCHECK_ID` environment variable. ### Docker Compose ```yaml version: '2' services: dodo: image: jakewharton/dodo:trunk restart: unless-stopped volumes: - /path/to/data:/data environment: - "CRON=*/3 * * * *" - "ACCESS_TOKEN=..." - "ACCESS_SECRET=..." - "API_KEY=..." - "API_SECRET=..." #Optional: - "HEALTHCHECK_ID=..." - "PUID=..." - "PGID=..." ``` ## Development To run the latest code build with `./gradlew installDist`. This will put the application into `build/install/dodo/`. From there you can use the [command-line instructions](#command-line) instructions to run. The Docker containers can be built with `docker build .`, which also runs the full set of checks as CI would. # License Copyright 2020 Jake Wharton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: RELEASING.md ================================================ # Releasing 1. Update the `CHANGELOG.md`: 1. Change the `Unreleased` header to the release version. 2. Add a link URL to ensure the header link works. 3. Add a new `Unreleased` section to the top. 2. Commit ``` $ git commit -am "Prepare version X.Y.X" ``` 3. Tag ``` $ git tag -am "Version X.Y.Z" X.Y.Z ``` 4. Push! ``` $ git push && git push --tags ``` This will trigger a GitHub Action workflow which will create a GitHub release, upload the zip, deploy the Docker container, and send a PR to the Homebrew repo. 5. Find [the Homebrew PR](https://github.com/JakeWharton/homebrew-repo/pulls) and merge it! ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() } dependencies { classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20' classpath 'com.squareup.sqldelight:gradle-plugin:1.5.4' } } apply plugin: 'org.jetbrains.kotlin.jvm' apply plugin: 'com.squareup.sqldelight' sqldelight { Database { packageName = 'com.jakewharton.dodo.db' schemaOutputDirectory = file('src/main/sqldelight/databases') verifyMigrations = true } } apply plugin: 'application' mainClassName = 'com.jakewharton.dodo.Main' dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4' implementation 'com.github.ajalt.clikt:clikt:3.5.2' implementation 'com.squareup.sqldelight:sqlite-driver:1.5.4' implementation 'org.xerial:sqlite-jdbc:3.41.2.1' implementation 'org.twitter4j:twitter4j-core:4.1.2' implementation 'ch.qos.logback:logback-classic:1.4.6' def ktorVersion = '1.6.8' implementation "io.ktor:ktor-server-core:${ktorVersion}" implementation "io.ktor:ktor-server-netty:${ktorVersion}" implementation "io.ktor:ktor-html-builder:${ktorVersion}" testImplementation 'junit:junit:4.13.2' testImplementation 'com.google.truth:truth:1.1.3' } repositories { mavenCentral() // https://github.com/Kotlin/kotlinx.html/issues/81 jcenter { content { includeModule('org.jetbrains.kotlinx', 'kotlinx-html-jvm') } } } tasks.named("distTar").configure { task -> task.enabled = false } tasks.named("assemble").configure { task -> task.dependsOn(tasks.getByName("installDist")) } tasks.withType(org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile).configureEach { task -> task.kotlinOptions { jvmTarget = '1.8' freeCompilerArgs += [ '-progressive', ] } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command; # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in # double quotes to make sure that they get re-expanded; and # * put everything else in single quotes, so that it's not re-expanded. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: renovate.json ================================================ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:base" ] } ================================================ FILE: root/app/sync.sh ================================================ #!/usr/bin/with-contenv sh if [ -n "$HEALTHCHECK_ID" ]; then curl -sS -X POST -o /dev/null "$HEALTHCHECK_HOST/$HEALTHCHECK_ID/start" fi # If the sync fails we want to avoid triggering the health check. set -e curl -sS -X POST --fail http://localhost/sync if [ -n "$HEALTHCHECK_ID" ]; then curl -sS -X POST -o /dev/null --fail "$HEALTHCHECK_HOST/$HEALTHCHECK_ID" fi ================================================ FILE: root/etc/cont-init.d/10-adduser.sh ================================================ #!/usr/bin/with-contenv sh # # Copyright (c) 2017 Joshua Avalon # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. PUID=${PUID:-1001} PGID=${PGID:-1001} groupmod -o -g "$PGID" abc usermod -o -u "$PUID" abc echo " Initializing container User uid: $(id -u abc) User gid: $(id -g abc) " chown abc:abc /app ================================================ FILE: root/etc/cont-init.d/20-cron.sh ================================================ #!/usr/bin/with-contenv sh if [ -z "$CRON" ]; then echo " Not running in cron mode " exit 0 fi if [ ! -d /data ]; then echo " ERROR: '/data' directory must be mounted " exit 1 fi if [ -z "$HEALTHCHECK_ID" ]; then echo " NOTE: Define HEALTHCHECK_ID with https://healthchecks.io to monitor sync job" fi if [ -z "$ACCESS_TOKEN" ]; then echo " ERROR: 'ACCESS_TOKEN' environment variable not set" exit 1 fi if [ -z "$ACCESS_SECRET" ]; then echo " ERROR: 'ACCESS_SECRET' environment variable not set" exit 1 fi if [ -z "$API_KEY" ]; then echo " ERROR: 'API_KEY' environment variable not set" exit 1 fi if [ -z "$API_SECRET" ]; then echo " ERROR: 'API_SECRET' environment variable not set" exit 1 fi # Set up the cron schedule. echo " Initializing cron $CRON " crontab -u abc -d # Delete any existing crontab. echo "$CRON /usr/bin/flock -n /app/sync.lock /app/sync.sh" >/tmp/crontab.tmp crontab -u abc /tmp/crontab.tmp rm /tmp/crontab.tmp ================================================ FILE: root/etc/services.d/cron/run ================================================ #!/usr/bin/with-contenv sh # Log level 5 (and below) is noisy during periodic wakeup where nothing happens. /usr/sbin/crond -f -l 6 ================================================ FILE: root/etc/services.d/dodo/run ================================================ #!/usr/bin/with-contenv sh /app/bin/dodo run \ --port 80 \ --db /data/dodo.db \ --access-token "$ACCESS_TOKEN" \ --access-secret "$ACCESS_SECRET" \ --api-key "$API_KEY" \ --api-secret "$API_SECRET" ================================================ FILE: settings.gradle ================================================ rootProject.name = 'dodo' ================================================ FILE: src/main/kotlin/com/jakewharton/dodo/app.kt ================================================ package com.jakewharton.dodo import com.jakewharton.dodo.db.Search import com.jakewharton.dodo.db.TweetIndexQueries import com.jakewharton.dodo.db.TweetQueries import java.time.ZoneOffset.UTC import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory import twitter4j.Twitter import twitter4j.TwitterObjectFactory import twitter4j.v1.Paging import twitter4j.v1.Status class Dodo( private val twitter: Twitter, private val tweetQueries: TweetQueries, private val searchQueries: TweetIndexQueries, ) { fun sync() { val newestStatusId = tweetQueries.newest().executeAsOne().status_id ?: 1L val tweets = twitter.v1().timelines().getHomeTimeline(Paging.ofSinceId(newestStatusId)) logger.info("Retrieved ${tweets.size} new tweets") for (tweet in tweets) { val text: String val quotedStatus: Status? if (tweet.isRetweet) { text = tweet.retweetedStatus.displayText quotedStatus = tweet.retweetedStatus.quotedStatus } else { text = tweet.text quotedStatus = tweet.quotedStatus } tweetQueries.insert( status_id = tweet.id, status_user_id = tweet.user.id, status_user_handle = tweet.user.screenName, status_user_name = tweet.user.name, status_text = text, status_unix_time = tweet.createdAt.toEpochSecond(UTC), retweeted_id = tweet.retweetedStatus?.id, retweeted_user_id = tweet.retweetedStatus?.user?.id, retweeted_user_handle = tweet.retweetedStatus?.user?.screenName, retweeted_user_name = tweet.retweetedStatus?.user?.name, retweeted_unix_time = tweet.retweetedStatus?.createdAt?.toEpochSecond(UTC), quoted_id = quotedStatus?.id, quoted_user_id = quotedStatus?.user?.id, quoted_user_handle = quotedStatus?.user?.screenName, quoted_user_name = quotedStatus?.user?.name, quoted_text = quotedStatus?.displayText, quoted_unix_time = quotedStatus?.createdAt?.toEpochSecond(UTC), json = TwitterObjectFactory.getRawJSON(tweet), // LMAO WTF thread local cache?!? ) } } suspend fun totalCount(): Long { return withContext(IO) { tweetQueries.totalCount().executeAsOne() } } suspend fun search(query: String): List = withContext(IO) { searchQueries.search(query).executeAsList() } private companion object { private val logger = LoggerFactory.getLogger(Dodo::class.java) } } ================================================ FILE: src/main/kotlin/com/jakewharton/dodo/db.kt ================================================ package com.jakewharton.dodo import com.jakewharton.dodo.db.Database import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver inline fun withDatabase(path: String, crossinline block: (db: Database) -> Unit) { JdbcSqliteDriver("jdbc:sqlite:$path").use { driver -> migrateIfNeeded(driver) block(Database(driver)) } } private const val versionPragma = "user_version" fun migrateIfNeeded(driver: JdbcSqliteDriver) { val oldVersion = driver.executeQuery(null, "PRAGMA $versionPragma", 0).use { cursor -> if (cursor.next()) { cursor.getLong(0)?.toInt() } else { null } } ?: 0 val newVersion = Database.Schema.version if (oldVersion == 0) { println("Creating DB version $newVersion!") Database.Schema.create(driver) driver.execute(null, "PRAGMA $versionPragma=$newVersion", 0) } else if (oldVersion < newVersion) { println("Migrating DB from version $oldVersion to $newVersion!") Database.Schema.migrate(driver, oldVersion, newVersion) driver.execute(null, "PRAGMA $versionPragma=$newVersion", 0) } } ================================================ FILE: src/main/kotlin/com/jakewharton/dodo/html.kt ================================================ package com.jakewharton.dodo import com.jakewharton.dodo.db.Search import kotlinx.html.FlowContent import kotlinx.html.FormMethod.get import kotlinx.html.HTML import kotlinx.html.InputType.submit import kotlinx.html.InputType.text import kotlinx.html.a import kotlinx.html.blockQuote import kotlinx.html.body import kotlinx.html.div import kotlinx.html.form import kotlinx.html.head import kotlinx.html.input import kotlinx.html.link import kotlinx.html.meta import kotlinx.html.nav import kotlinx.html.p import kotlinx.html.script import kotlinx.html.time import kotlinx.html.title import java.time.Instant import java.time.LocalDateTime import java.time.ZoneOffset.UTC import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME fun HTML.renderIndex(query: String?, totalCount: Long, tweets: List) { head { meta(charset = "utf-8") meta(name = "viewport", content = "width=device-width, initial-scale=1.0") title("Dodo Tweet Archive") link(rel = "stylesheet", href = "/static/chota.min.css") meta(name = "twitter:dnt", content = "on") script(src = "https://platform.twitter.com/widgets.js") { async = true charset = "utf-8" } } body { nav(classes = "nav") { div(classes = "nav-center") { a(href = "/", classes = "brand") { +"Dodo 🐦" } } } div(classes = "container") { div(classes = "row") { div(classes = "col") { form(action = "/", method = get, classes = "is-center") { div(classes = "grouped") { input(name = "q", type = text) { placeholder = "Search term" autoFocus = true if (query != null) { value = query } } input(type = submit) { value = "Search $totalCount tweets" } } } } } div(classes = "row") { div(classes = "col") { for (tweet in tweets) { tweet(tweet) } } } } script(src = "/static/app.js") { async = true charset = "utf-8" } } } private fun FlowContent.tweet(tweet: Search) { blockQuote("twitter-tweet tw-align-center") { attributes["data-cards"] = "hidden" attributes["data-conversation"] = "none" p { +tweet.status_text if (tweet.quoted_text != null) { blockQuote { p { +tweet.quoted_text } p { +"— " twitterHandleLink(tweet.quoted_user_handle!!) } } } } p { +"— " if (tweet.retweeted_user_handle != null) { twitterHandleLink(tweet.retweeted_user_handle) +" retweeted by " } twitterHandleLink(tweet.status_user_handle) } p { a(href = "https://twitter.com/${tweet.status_user_handle}/status/${tweet.status_id}") { renderUnixTime(tweet.status_unix_time) } } } } private fun FlowContent.twitterHandleLink(handle: String) { a(href = "https://twitter.com/$handle") { rel = "noreferrer noopener" +"@$handle" } } private fun FlowContent.renderUnixTime(unixTime: Long) { time { val ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), UTC) val formatted = ISO_LOCAL_DATE_TIME.format(ldt) + "Z" dateTime = formatted +formatted } } ================================================ FILE: src/main/kotlin/com/jakewharton/dodo/main.kt ================================================ @file:JvmName("Main") package com.jakewharton.dodo import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.NoOpCliktCommand import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.help import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import com.github.ajalt.clikt.parameters.types.int import io.ktor.application.call import io.ktor.html.respondHtml import io.ktor.http.content.resources import io.ktor.http.content.static import io.ktor.response.respondBytes import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.routing import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import twitter4j.Twitter fun main(vararg args: String) { NoOpCliktCommand(name = "dodo") .subcommands(SyncCommand(), RunCommand()) .main(args) } private abstract class DodoCommand( name: String, help: String, ) : CliktCommand( name = name, help = help ) { private val dbPath by option("--db", metavar = "FILE") .required() .help("Sqlite database file") private val accessToken by option(metavar = "KEY") .required() .help("OAuth access token") private val accessSecret by option(metavar = "KEY") .required() .help("OAuth access token secret") private val apiKey by option(metavar = "KEY") .required() .help("OAuth consumer API key") private val apiSecret by option(metavar = "KEY") .required() .help("OAuth consumer API secret") override fun run() { val twitter = Twitter.newBuilder() .oAuthAccessToken(accessToken, accessSecret) .oAuthConsumer(apiKey, apiSecret) .jsonStoreEnabled(true) .build() withDatabase(dbPath) { db -> val dodo = Dodo(twitter, db.tweetQueries, db.tweetIndexQueries) run(dodo) } } abstract fun run(dodo: Dodo) } private class SyncCommand : DodoCommand( name = "sync", help = "Perform a one-time sync of the latest tweets", ) { override fun run(dodo: Dodo) { dodo.sync() } } private class RunCommand : DodoCommand( name = "run", help = "Start an HTTP server for displaying tweets and performing syncs", ) { private val port by option(metavar = "PORT").int() .default(defaultPort) .help("Port for the HTTP server (default $defaultPort)") override fun run(dodo: Dodo) { embeddedServer(Netty, port) { routing { static("/static") { resources("static") } get("/") { val query = call.request.queryParameters["q"] val totalCount = dodo.totalCount() val tweets = if (query != null) dodo.search(query) else emptyList() call.respondHtml { renderIndex(query, totalCount, tweets) } } post("/sync") { dodo.sync() call.respondBytes(byteArrayOf()) } } }.start(wait = true) } companion object { private const val defaultPort = 8098 } } ================================================ FILE: src/main/kotlin/com/jakewharton/dodo/twitter4j.kt ================================================ package com.jakewharton.dodo import twitter4j.v1.Status val Status.displayText: String get() { return buildString { var lastIndex = 0 for (urlEntity in urlEntities.sortedBy { it.start }) { append(text, lastIndex, urlEntity.start) append(urlEntity.expandedURL) lastIndex = urlEntity.end } append(text, lastIndex, text.length) } } ================================================ FILE: src/main/resources/logback.xml ================================================ %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n ================================================ FILE: src/main/resources/static/app.js ================================================ let elements = document.getElementsByTagName("time") for (let i = 0; i < elements.length; i++) { let node = elements[i]; node.innerHTML = new Date(Date.parse(node.getAttribute("datetime"))).toLocaleString() } ================================================ FILE: src/main/sqldelight/com/jakewharton/dodo/db/tweet.sq ================================================ CREATE TABLE tweet( status_id INTEGER NOT NULL PRIMARY KEY, status_user_id INTEGER NOT NULL, status_user_handle TEXT NOT NULL, status_user_name TEXT NOT NULL, status_text TEXT NOT NULL, status_unix_time INTEGER NOT NULL, -- Retweet: If one is non-null, all are non-null. retweeted_id INTEGER, retweeted_user_id INTEGER, retweeted_user_handle TEXT, retweeted_user_name TEXT, retweeted_unix_time INTEGER, -- Quote tweet: If one is non-null, all are non-null. quoted_id INTEGER, quoted_user_id INTEGER, quoted_user_handle TEXT, quoted_user_name TEXT, quoted_text TEXT, quoted_unix_time INTEGER, json TEXT NOT NULL ); CREATE UNIQUE INDEX tweet_status_id ON tweet(status_id); newest: SELECT MAX(status_id) AS status_id FROM tweet ; insert: INSERT INTO tweet VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ; totalCount: SELECT COUNT(status_id) AS count FROM tweet ; ================================================ FILE: src/main/sqldelight/com/jakewharton/dodo/db/tweetIndex.sq ================================================ CREATE VIRTUAL TABLE tweet_index USING fts5( status_id INTEGER UNINDEXED, status_text TEXT, status_user_name TEXT, status_user_handle TEXT, retweeted_user_handle TEXT, retweeted_user_name TEXT, quoted_user_handle TEXT, quoted_user_name TEXT, quoted_text TEXT ); CREATE TRIGGER tweet_after_insert AFTER INSERT ON tweet BEGIN INSERT INTO tweet_index( status_id, status_text, status_user_name, status_user_handle, retweeted_user_handle, retweeted_user_name, quoted_user_handle, quoted_user_name, quoted_text ) VALUES ( new.status_id, new.status_text, new.status_user_name, new.status_user_handle, new.retweeted_user_handle, new.retweeted_user_name, new.quoted_user_handle, new.quoted_user_name, new.quoted_text ); END; search: SELECT tweet.status_id, tweet.status_user_handle, tweet.status_text, tweet.status_unix_time, tweet.retweeted_user_handle, tweet.retweeted_unix_time, tweet.quoted_user_handle, tweet.quoted_text, tweet.quoted_unix_time FROM tweet INNER JOIN tweet_index ON tweet.status_id=tweet_index.status_id WHERE tweet_index MATCH ?1 ORDER BY bm25(tweet_index); ================================================ FILE: src/main/sqldelight/migrations/1.sqm ================================================ DROP TABLE tweet; CREATE TABLE tweet( status_id INTEGER NOT NULL PRIMARY KEY, status_user_id INTEGER NOT NULL, status_user_name TEXT NOT NULL, status_text TEXT NOT NULL, retweet_id INTEGER, retweet_user_id INTEGER, retweet_user_name TEXT, quoted_id INTEGER, quoted_user_id INTEGER, quoted_user_name TEXT, quoted_text TEXT, json TEXT NOT NULL ); ================================================ FILE: src/main/sqldelight/migrations/2.sqm ================================================ CREATE TABLE tweet2( status_id INTEGER NOT NULL PRIMARY KEY, status_user_id INTEGER NOT NULL, status_user_name TEXT NOT NULL, status_text TEXT NOT NULL, status_unix_time INTEGER NOT NULL, retweeted_id INTEGER, retweeted_user_id INTEGER, retweeted_user_name TEXT, retweeted_unix_time INTEGER, quoted_id INTEGER, quoted_user_id INTEGER, quoted_user_name TEXT, quoted_text TEXT, quoted_unix_time INTEGER, json TEXT NOT NULL ); INSERT INTO tweet2 SELECT status_id , status_user_id , status_user_name , status_text , 0 -- status_unix_time , retweet_id , retweet_user_id , retweet_user_name , 0 -- retweeted_unix_time , quoted_id , quoted_user_id , quoted_user_name , quoted_text , 0 -- quoted_unix_time , json FROM tweet ; DROP TABLE tweet; ALTER TABLE tweet2 RENAME TO tweet; ================================================ FILE: src/main/sqldelight/migrations/3.sqm ================================================ CREATE TABLE tweet2( status_id INTEGER NOT NULL PRIMARY KEY, status_user_id INTEGER NOT NULL, status_user_handle TEXT NOT NULL, status_user_name TEXT NOT NULL, status_text TEXT NOT NULL, status_unix_time INTEGER NOT NULL, -- Retweet: If one is non-null, all are non-null. retweeted_id INTEGER, retweeted_user_id INTEGER, retweeted_user_handle TEXT, retweeted_user_name TEXT, retweeted_unix_time INTEGER, -- Quote tweet: If one is non-null, all are non-null. quoted_id INTEGER, quoted_user_id INTEGER, quoted_user_handle TEXT, quoted_user_name TEXT, quoted_text TEXT, quoted_unix_time INTEGER, json TEXT NOT NULL ); INSERT INTO tweet2 SELECT status_id , status_user_id , status_user_name , status_user_name -- repurpose name (which was the handle) as display name , status_text , status_unix_time , retweeted_id , retweeted_user_id , retweeted_user_name , retweeted_user_name -- repurpose name (which was the handle) as display name , retweeted_unix_time , quoted_id , quoted_user_id , quoted_user_name , quoted_user_name -- repurpose name (which was the handle) as display name , quoted_text , quoted_unix_time , json FROM tweet ; DROP TABLE tweet; ALTER TABLE tweet2 RENAME TO tweet; ================================================ FILE: src/main/sqldelight/migrations/4.sqm ================================================ CREATE VIRTUAL TABLE tweet_index USING fts5( status_id INTEGER UNINDEXED, status_text TEXT, status_user_name TEXT, status_user_handle TEXT, retweeted_user_handle TEXT, retweeted_user_name TEXT, quoted_user_handle TEXT, quoted_user_name TEXT, quoted_text TEXT ); INSERT INTO tweet_index SELECT status_id, status_text, status_user_name, status_user_handle, retweeted_user_handle, retweeted_user_name, quoted_user_handle, quoted_user_name, quoted_text FROM tweet; CREATE TRIGGER tweet_after_insert AFTER INSERT ON tweet BEGIN INSERT INTO tweet_index( status_id, status_text, status_user_name, status_user_handle, retweeted_user_handle, retweeted_user_name, quoted_user_handle, quoted_user_name, quoted_text ) VALUES ( new.status_id, new.status_text, new.status_user_name, new.status_user_handle, new.retweeted_user_handle, new.retweeted_user_name, new.quoted_user_handle, new.quoted_user_name, new.quoted_text ); END; ================================================ FILE: src/main/sqldelight/migrations/5.sqm ================================================ CREATE UNIQUE INDEX tweet_status_id ON tweet(status_id); ================================================ FILE: src/test/kotlin/com/jakewharton/dodo/Twitter4jTest.kt ================================================ package com.jakewharton.dodo import com.google.common.truth.Truth.assertThat import org.junit.Test class Twitter4jTest { @Test fun displayTextNoUrlEntitiesReturnsOriginal() { val status = TestStatus( "This is some text", emptyList(), ) assertThat(status.displayText).isEqualTo("This is some text") } @Test fun displayTextUrlFirst() { val status = TestStatus( "This is some text", listOf(TestURLEntity("Expanded", 0, 4)) ) assertThat(status.displayText).isEqualTo("Expanded is some text") } @Test fun displayTextUrlLast() { val status = TestStatus( "This is some text", listOf(TestURLEntity("expanded", 13, 17)) ) assertThat(status.displayText).isEqualTo("This is some expanded") } @Test fun displayTextUrlOutOfOrder() { val status = TestStatus( "This is some text", listOf( TestURLEntity("expanded", 13, 17), TestURLEntity("Expanded", 0, 4), ) ) assertThat(status.displayText).isEqualTo("Expanded is some expanded") } } ================================================ FILE: src/test/kotlin/com/jakewharton/dodo/twitter4jFakes.kt ================================================ package com.jakewharton.dodo import twitter4j.v1.Status import twitter4j.v1.URLEntity /** A minimal working subset of [Status] for testing purposes only. */ data class TestStatus( private val text: String, private val urlEntities: List ) : Status { override fun getText() = text override fun getURLEntities() = urlEntities.toTypedArray() override fun getId() = TODO("Not yet implemented") override fun getRateLimitStatus() = TODO("Not yet implemented") override fun getAccessLevel() = TODO("Not yet implemented") override fun getUserMentionEntities() = TODO("Not yet implemented") override fun getHashtagEntities() = TODO("Not yet implemented") override fun getMediaEntities() = TODO("Not yet implemented") override fun getSymbolEntities() = TODO("Not yet implemented") override fun getCreatedAt() = TODO("Not yet implemented") override fun getDisplayTextRangeStart() = TODO("Not yet implemented") override fun getDisplayTextRangeEnd() = TODO("Not yet implemented") override fun getSource() = TODO("Not yet implemented") override fun isTruncated() = TODO("Not yet implemented") override fun getInReplyToStatusId() = TODO("Not yet implemented") override fun getInReplyToUserId() = TODO("Not yet implemented") override fun getInReplyToScreenName() = TODO("Not yet implemented") override fun getGeoLocation() = TODO("Not yet implemented") override fun getPlace() = TODO("Not yet implemented") override fun isFavorited() = TODO("Not yet implemented") override fun isRetweeted() = TODO("Not yet implemented") override fun getFavoriteCount() = TODO("Not yet implemented") override fun getUser() = TODO("Not yet implemented") override fun isRetweet() = TODO("Not yet implemented") override fun getRetweetedStatus() = TODO("Not yet implemented") override fun getContributors() = TODO("Not yet implemented") override fun getRetweetCount() = TODO("Not yet implemented") override fun isRetweetedByMe() = TODO("Not yet implemented") override fun getCurrentUserRetweetId() = TODO("Not yet implemented") override fun isPossiblySensitive() = TODO("Not yet implemented") override fun getLang() = TODO("Not yet implemented") override fun getScopes() = TODO("Not yet implemented") override fun getWithheldInCountries() = TODO("Not yet implemented") override fun getQuotedStatusId() = TODO("Not yet implemented") override fun getQuotedStatus() = TODO("Not yet implemented") override fun getQuotedStatusPermalink() = TODO("Not yet implemented") override fun compareTo(other: Status?) = TODO("Not yet implemented") } data class TestURLEntity( private val expandedUrl: String, private val start: Int, private val end: Int, ) : URLEntity { override fun getStart() = start override fun getEnd() = end override fun getExpandedURL() = expandedUrl override fun getText() = TODO("Not yet implemented") override fun getURL() = TODO("Not yet implemented") override fun getDisplayURL() = TODO("Not yet implemented") }