├── .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 ├── settings.gradle └── src └── main └── kotlin └── com └── jakewharton └── singularsolution └── main.kt /.dockerignore: -------------------------------------------------------------------------------- 1 | /.git 2 | /.gradle 3 | /build 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [*.yaml] 12 | indent_style = space 13 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - '**' 8 | - '!trunk' 9 | 10 | env: 11 | GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v4 20 | 21 | - name: Validate Gradle Wrapper 22 | uses: gradle/actions/wrapper-validation@v4 23 | 24 | - name: Build 25 | run: docker build . 26 | -------------------------------------------------------------------------------- /.github/workflows/build_and_publish.yaml: -------------------------------------------------------------------------------- 1 | name: build and publish 2 | 3 | on: 4 | push: 5 | branches: 6 | - trunk 7 | tags: 8 | - '*' 9 | 10 | env: 11 | GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | 20 | - uses: gradle/actions/wrapper-validation@v4 21 | 22 | - uses: actions/setup-java@v4 23 | with: 24 | distribution: 'zulu' 25 | java-version: 19 26 | 27 | - run: ./gradlew build 28 | 29 | - uses: crazy-max/ghaction-docker-meta@v1 30 | id: docker_meta 31 | with: 32 | images: | 33 | jakewharton/singular-solution 34 | ghcr.io/jakewharton/singular-solution 35 | tag-semver: | 36 | {{version}} 37 | {{major}} 38 | {{major}}.{{minor}} 39 | 40 | - uses: docker/login-action@v3 41 | with: 42 | username: jakewharton 43 | password: ${{ secrets.DOCKER_HUB_TOKEN }} 44 | 45 | - run: echo ${{ secrets.GHCR_TOKEN }} | docker login ghcr.io -u $GITHUB_ACTOR --password-stdin 46 | 47 | - uses: docker/build-push-action@v6 48 | with: 49 | push: true 50 | tags: ${{ steps.docker_meta.outputs.tags }} 51 | labels: ${{ steps.docker_meta.outputs.labels }} 52 | 53 | - name: Extract release notes 54 | id: release_notes 55 | if: startsWith(github.ref, 'refs/tags/') 56 | uses: ffurrer2/extract-release-notes@v2 57 | 58 | - name: Create Release 59 | if: startsWith(github.ref, 'refs/tags/') 60 | uses: softprops/action-gh-release@v2 61 | with: 62 | body: ${{ steps.release_notes.outputs.release_notes }} 63 | files: build/distributions/singular-solution.zip 64 | env: 65 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 66 | 67 | - name: Get version 68 | id: get_version 69 | if: startsWith(github.ref, 'refs/tags/') 70 | run: echo ::set-output name=version::${GITHUB_REF/refs\/tags\//} 71 | 72 | - name: Set SHA 73 | id: shasum 74 | if: startsWith(github.ref, 'refs/tags/') 75 | run: echo ::set-output name=sha::"$(shasum -a 256 build/distributions/singular-solution.zip | awk '{printf $1}')" 76 | 77 | - name: Bump Brew 78 | if: startsWith(github.ref, 'refs/tags/') 79 | env: 80 | HOMEBREW_GITHUB_API_TOKEN: ${{ secrets.GH_HOMEBREW_TOKEN }} 81 | run: | 82 | git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" 83 | git config --global user.name "github-actions[bot]" 84 | 85 | # Update to ensure we have the latest version which supports arbitrary default branches. 86 | brew update 87 | 88 | brew tap JakeWharton/repo 89 | brew bump-formula-pr -f --version=${{ steps.get_version.outputs.version }} --no-browse --no-audit \ 90 | --sha256=${{ steps.shasum.outputs.sha }} \ 91 | --url="https://github.com/JakeWharton/singular-solution/releases/download/${{ steps.get_version.outputs.version }}/singular-solution.zip" \ 92 | JakeWharton/repo/singular-solution 93 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | build 3 | .gradle 4 | /reports 5 | 6 | # IntelliJ 7 | .idea 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [Unreleased] 4 | 5 | ## [2.0.0] 6 | 7 | - **Breaking change**: The old CLI behavior is now under the `run` subcommand. 8 | 9 | Before: 10 | ``` 11 | $ singular-solution --api-key=... etc. 12 | ``` 13 | 14 | After: 15 | ``` 16 | $ singular-solution run --api-key=... etc. 17 | ``` 18 | 19 | Usage as a Docker container is unaffected by this change. 20 | 21 | - **New**: `auth` subcommand can provide an access token and access secret given only an API key 22 | and API secret. Don't have an API key and API secret? Google around and you can find the official 23 | ones used for the first-party clients which have full access to the API endpoints needed. 24 | 25 | Example usage: 26 | ``` 27 | $ singular-solution auth --api-key --api-secret 28 | Visit the following URL in your browser to authorize the app: 29 | 30 | https://api.twitter.com/oauth/authorize?oauth_token= 31 | 32 | Once completed, you should see a PIN. Paste that below: 33 | 34 | PIN: 123456 35 | 36 | SUCCESS! 37 | 38 | Consumer API key: 39 | Consumer API secret: 40 | Access token: 41 | Access token secret: 42 | ``` 43 | 44 | 45 | ## [1.0.1] 46 | 47 | - Fix rate limiting logic 48 | - Print a big, greppable message ("MANUAL INTERVENTION NEEDED!!") if unblocking fails 49 | 50 | 51 | ## [1.0.0] 52 | 53 | - Initial release 54 | 55 | 56 | [Unreleased]: https://github.com/JakeWharton/singular-solution/compare/2.0.0...HEAD 57 | [2.0.0]: https://github.com/JakeWharton/singular-solution/releases/tag/2.0.0 58 | [1.0.1]: https://github.com/JakeWharton/singular-solution/releases/tag/1.0.1 59 | [1.0.0]: https://github.com/JakeWharton/singular-solution/releases/tag/1.0.0 60 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM adoptopenjdk:8-jdk-hotspot AS build 2 | ENV GRADLE_OPTS="-Dorg.gradle.daemon=false -Dkotlin.incremental=false" 3 | WORKDIR /app 4 | 5 | COPY gradlew settings.gradle ./ 6 | COPY gradle ./gradle 7 | RUN ./gradlew --version 8 | 9 | COPY build.gradle ./ 10 | COPY src ./src 11 | RUN ./gradlew build 12 | 13 | 14 | FROM koalaman/shellcheck-alpine:stable AS shellcheck 15 | WORKDIR /overlay 16 | COPY root/ ./ 17 | RUN find . -type f | xargs shellcheck -e SC1008 18 | 19 | 20 | FROM mvdan/shfmt:v3-alpine AS shfmt 21 | WORKDIR /overlay 22 | COPY root/ ./ 23 | COPY .editorconfig / 24 | RUN shfmt -d . 25 | 26 | 27 | 28 | 29 | FROM oznu/s6-alpine:3.13 30 | LABEL maintainer="Jake Wharton " 31 | 32 | RUN apk add --no-cache \ 33 | curl \ 34 | openjdk8-jre \ 35 | && rm -rf /var/cache/* \ 36 | && mkdir /var/cache/apk 37 | 38 | ENV \ 39 | # Fail if cont-init scripts exit with non-zero code. 40 | S6_BEHAVIOUR_IF_STAGE2_FAILS=2 \ 41 | CRON="" \ 42 | ACCESS_TOKEN="" \ 43 | ACCESS_SECRET="" \ 44 | API_KEY="" \ 45 | API_SECRET="" \ 46 | HEALTHCHECK_ID="" \ 47 | HEALTHCHECK_HOST="https://hc-ping.com" \ 48 | PUID="" \ 49 | PGID="" 50 | COPY root/ / 51 | WORKDIR /app 52 | COPY --from=build /app/build/install/singular-solution ./ 53 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Singular Solution 2 | 3 | Keep your Twitter follower count at zero by blocking and then quickly unblocking any new followers. 4 | 5 | Available as a binary and Docker container. 6 | 7 | 8 | ## Usage 9 | 10 | Singular Solution needs an API key and secret as well as an OAuth access token and access secret. 11 | 12 | If you only have an API key and secret and need an access token and secret the `auth` subcommand 13 | (documented below) can help you obtain one. 14 | 15 | If you need an API key and secret then Google around and you should be able to find those which 16 | are used by the official Twitter clients. It is no longer feasible to register your own application 17 | since the API endpoints needed cost a ridiculous amount of money. 18 | 19 | From there, you can run Singular Solution in one of two ways: 20 | 21 | * [Command line](#command-line) 22 | * [Docker](#docker) 23 | 24 | ### Command-line 25 | 26 | Install on Mac OS with: 27 | ``` 28 | $ brew install JakeWharton/repo/singular-solution 29 | ``` 30 | 31 | For other platforms, download ZIP from 32 | [latest release](https://github.com/JakeWharton/singular-solution/releases/latest) 33 | and run `bin/singular-solution` or `bin/singular-solution.bat`. 34 | 35 | ``` 36 | $ singular-solution --help 37 | Usage: singular-solution [] []... 38 | 39 | Options: 40 | -h, --help Show this message and exit 41 | 42 | Commands: 43 | auth Perform interactive authentication to get an access token and secret 44 | run Block and quickly unblock all followers to keep count at zero 45 | ``` 46 | ``` 47 | $ singular-solution auth -h 48 | Usage: singular-solution auth [] 49 | 50 | Perform interactive authentication to get an access token and secret 51 | 52 | Options: 53 | --api-key= OAuth consumer API key 54 | --api-secret= OAuth consumer API secret 55 | -h, --help Show this message and exit 56 | ``` 57 | ``` 58 | $ singular-solution run -h 59 | Usage: singular-solution run [] 60 | 61 | Block and quickly unblock all followers to keep count at zero 62 | 63 | Options: 64 | --access-token= OAuth access token 65 | --access-secret= OAuth access token secret 66 | --api-key= OAuth consumer API key 67 | --api-secret= OAuth consumer API secret 68 | --dry-run Print destructive actions instead of performing them 69 | -h, --help Show this message and exit 70 | ``` 71 | 72 | ## Docker 73 | 74 | A container with the binary is available from Docker Hub and GitHub Container Registry. 75 | 76 | * `jakewharton/singular-solution` 77 | * `ghcr.io/jakewharton/singular-solution` 78 | 79 | The `trunk` branch pushes to the `trunk` tag on both registries, or you can use a tagged version. 80 | 81 | [![Docker Image Version](https://img.shields.io/docker/v/jakewharton/singular-solution?sort=semver)][hub] 82 | [![Docker Image Size](https://img.shields.io/docker/image-size/jakewharton/singular-solution)][hub] 83 | 84 | [hub]: https://hub.docker.com/r/jakewharton/singular-solution/ 85 | 86 | The container automatically triggers the binary using cron. 87 | 88 | ``` 89 | $ docker run -it --rm 90 | -e "CRON=*/3 * * * *" \ 91 | -e "ACCESS_TOKEN=..." \ 92 | -e "ACCESS_SECRET=..." \ 93 | -e "API_KEY=..." \ 94 | -e "API_SECRET=..." \ 95 | jakewharton/singular-solution:trunk 96 | ``` 97 | 98 | To be notified when the binary is failing visit https://healthchecks.io, create a check, and specify 99 | the ID to the container using the `HEALTHCHECK_ID` environment variable. 100 | 101 | ### Docker Compose 102 | 103 | ```yaml 104 | version: '2' 105 | services: 106 | singular-solution: 107 | image: jakewharton/singular-solution:trunk 108 | restart: unless-stopped 109 | environment: 110 | - "CRON=*/3 * * * *" 111 | - "ACCESS_TOKEN=..." 112 | - "ACCESS_SECRET=..." 113 | - "API_KEY=..." 114 | - "API_SECRET=..." 115 | #Optional: 116 | - "HEALTHCHECK_ID=..." 117 | ``` 118 | 119 | 120 | ## Development 121 | 122 | To run the latest code build with `./gradlew installDist`. This will put the application into 123 | `build/install/singular-solution/`. From there you can use the 124 | [command-line instructions](#command-line) instructions to run. 125 | 126 | The Docker containers can be built with `docker build .`, which also runs the full set of checks 127 | as CI would. 128 | 129 | 130 | # License 131 | 132 | Copyright 2022 Jake Wharton 133 | 134 | Licensed under the Apache License, Version 2.0 (the "License"); 135 | you may not use this file except in compliance with the License. 136 | You may obtain a copy of the License at 137 | 138 | http://www.apache.org/licenses/LICENSE-2.0 139 | 140 | Unless required by applicable law or agreed to in writing, software 141 | distributed under the License is distributed on an "AS IS" BASIS, 142 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 143 | See the License for the specific language governing permissions and 144 | limitations under the License. 145 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | 1. Update the `CHANGELOG.md`: 4 | 1. Change the `Unreleased` header to the release version. 5 | 2. Add a link URL to ensure the header link works. 6 | 3. Add a new `Unreleased` section to the top. 7 | 8 | 2. Commit 9 | 10 | ``` 11 | $ git commit -am "Prepare version X.Y.X" 12 | ``` 13 | 14 | 3. Tag 15 | 16 | ``` 17 | $ git tag -am "Version X.Y.Z" X.Y.Z 18 | ``` 19 | 20 | 4. Push! 21 | 22 | ``` 23 | $ git push && git push --tags 24 | ``` 25 | 26 | This will trigger a GitHub Action workflow which will create a GitHub release, upload the 27 | zip, deploy the Docker container, and send a PR to the Homebrew repo. 28 | 29 | 5. Find [the Homebrew PR](https://github.com/JakeWharton/homebrew-repo/pulls) and merge it! 30 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | dependencies { 6 | classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.21' 7 | } 8 | } 9 | 10 | apply plugin: 'org.jetbrains.kotlin.jvm' 11 | 12 | apply plugin: 'application' 13 | application { 14 | mainClass = 'com.jakewharton.singularsolution.Main' 15 | } 16 | 17 | dependencies { 18 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2' 19 | implementation 'com.github.ajalt.clikt:clikt:5.0.3' 20 | implementation 'org.twitter4j:twitter4j-core:4.1.2' 21 | implementation 'com.github.scribejava:scribejava-apis:8.3.3' 22 | } 23 | 24 | repositories { 25 | mavenCentral() 26 | } 27 | 28 | tasks.named("distTar").configure { task -> 29 | task.enabled = false 30 | } 31 | tasks.named("assemble").configure { task -> 32 | task.dependsOn(tasks.named("installDist")) 33 | } 34 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JakeWharton/singular-solution/78f1ca69337af9a9f356469a4d77b142c7d38344/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH="\\\"\\\"" 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /root/app/sync.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv sh 2 | 3 | if [ -n "$HEALTHCHECK_ID" ]; then 4 | curl -sS -X POST -o /dev/null "$HEALTHCHECK_HOST/$HEALTHCHECK_ID/start" 5 | fi 6 | 7 | # If the sync fails we want to avoid triggering the health check. 8 | set -e 9 | 10 | /app/bin/singular-solution run \ 11 | --access-token "$ACCESS_TOKEN" \ 12 | --access-secret "$ACCESS_SECRET" \ 13 | --api-key "$API_KEY" \ 14 | --api-secret "$API_SECRET" 15 | 16 | if [ -n "$HEALTHCHECK_ID" ]; then 17 | curl -sS -X POST -o /dev/null --fail "$HEALTHCHECK_HOST/$HEALTHCHECK_ID" 18 | fi 19 | -------------------------------------------------------------------------------- /root/etc/cont-init.d/10-adduser.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv sh 2 | # 3 | # Copyright (c) 2017 Joshua Avalon 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | PUID=${PUID:-1001} 24 | PGID=${PGID:-1001} 25 | 26 | groupmod -o -g "$PGID" abc 27 | usermod -o -u "$PUID" abc 28 | 29 | echo " 30 | Initializing container 31 | 32 | User uid: $(id -u abc) 33 | User gid: $(id -g abc) 34 | " 35 | 36 | chown abc:abc /app 37 | -------------------------------------------------------------------------------- /root/etc/cont-init.d/20-cron.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv sh 2 | 3 | if [ -z "$CRON" ]; then 4 | echo " 5 | Not running in cron mode 6 | " 7 | exit 0 8 | fi 9 | 10 | if [ -z "$HEALTHCHECK_ID" ]; then 11 | echo " 12 | NOTE: Define HEALTHCHECK_ID with https://healthchecks.io to monitor sync job" 13 | fi 14 | 15 | if [ -z "$ACCESS_TOKEN" ]; then 16 | echo " 17 | ERROR: 'ACCESS_TOKEN' environment variable not set" 18 | exit 1 19 | fi 20 | if [ -z "$ACCESS_SECRET" ]; then 21 | echo " 22 | ERROR: 'ACCESS_SECRET' environment variable not set" 23 | exit 1 24 | fi 25 | if [ -z "$API_KEY" ]; then 26 | echo " 27 | ERROR: 'API_KEY' environment variable not set" 28 | exit 1 29 | fi 30 | if [ -z "$API_SECRET" ]; then 31 | echo " 32 | ERROR: 'API_SECRET' environment variable not set" 33 | exit 1 34 | fi 35 | 36 | # Set up the cron schedule. 37 | echo " 38 | Initializing cron 39 | 40 | $CRON 41 | " 42 | crontab -u abc -d # Delete any existing crontab. 43 | echo "$CRON /usr/bin/flock -n /app/sync.lock /app/sync.sh" >/tmp/crontab.tmp 44 | crontab -u abc /tmp/crontab.tmp 45 | rm /tmp/crontab.tmp 46 | -------------------------------------------------------------------------------- /root/etc/services.d/cron/run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv sh 2 | 3 | # Log level 5 (and below) is noisy during periodic wakeup where nothing happens. 4 | /usr/sbin/crond -f -l 6 5 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'singular-solution' 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/jakewharton/singularsolution/main.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("Main") 2 | 3 | package com.jakewharton.singularsolution 4 | 5 | import com.github.ajalt.clikt.core.CliktCommand 6 | import com.github.ajalt.clikt.core.Context 7 | import com.github.ajalt.clikt.core.NoOpCliktCommand 8 | import com.github.ajalt.clikt.core.main 9 | import com.github.ajalt.clikt.core.subcommands 10 | import com.github.ajalt.clikt.parameters.options.flag 11 | import com.github.ajalt.clikt.parameters.options.help 12 | import com.github.ajalt.clikt.parameters.options.option 13 | import com.github.ajalt.clikt.parameters.options.required 14 | import com.github.scribejava.apis.TwitterApi 15 | import com.github.scribejava.core.builder.ServiceBuilder 16 | import java.util.Scanner 17 | import kotlin.time.Duration.Companion.seconds 18 | import kotlinx.coroutines.delay 19 | import kotlinx.coroutines.runBlocking 20 | import twitter4j.Twitter 21 | import twitter4j.TwitterException 22 | import twitter4j.v1.RateLimitStatus 23 | 24 | fun main(vararg args: String) { 25 | NoOpCliktCommand(name = "singular-solution") 26 | .subcommands( 27 | AuthCommand(), 28 | RunCommand(), 29 | ) 30 | .main(args) 31 | } 32 | 33 | private class AuthCommand : CliktCommand("auth") { 34 | override fun help(context: Context) = 35 | "Perform interactive authentication to get an access token and secret" 36 | 37 | private val apiKey by option(metavar = "KEY") 38 | .required() 39 | .help("OAuth consumer API key") 40 | private val apiSecret by option(metavar = "KEY") 41 | .required() 42 | .help("OAuth consumer API secret") 43 | 44 | override fun run() { 45 | val service = ServiceBuilder(apiKey) 46 | .apiSecret(apiSecret) 47 | .build(TwitterApi.instance()) 48 | 49 | val requestToken = service.requestToken 50 | val authorizationUrl = service.getAuthorizationUrl(requestToken) 51 | println("Visit the following URL in your browser to authorize the app:") 52 | println() 53 | println(" $authorizationUrl") 54 | println() 55 | println("Once completed, you should see a PIN. Paste that below:") 56 | println() 57 | print("PIN: ") 58 | val code = Scanner(System.`in`).nextLine() 59 | val accessToken = service.getAccessToken(requestToken, code); 60 | println() 61 | println("SUCCESS!") 62 | println() 63 | println("Consumer API key: $apiKey") 64 | println("Consumer API secret: $apiSecret") 65 | println("Access token: ${accessToken.token}") 66 | println("Access token secret: ${accessToken.tokenSecret}") 67 | } 68 | } 69 | 70 | private class RunCommand : CliktCommand("run") { 71 | override fun help(context: Context) = 72 | "Block and quickly unblock all followers to keep count at zero" 73 | 74 | private val accessToken by option(metavar = "KEY") 75 | .required() 76 | .help("OAuth access token") 77 | private val accessSecret by option(metavar = "KEY") 78 | .required() 79 | .help("OAuth access token secret") 80 | private val apiKey by option(metavar = "KEY") 81 | .required() 82 | .help("OAuth consumer API key") 83 | private val apiSecret by option(metavar = "KEY") 84 | .required() 85 | .help("OAuth consumer API secret") 86 | private val dryRun by option() 87 | .flag() 88 | .help("Print destructive actions instead of performing them") 89 | 90 | override fun run() = runBlocking { 91 | val twitter = Twitter.newBuilder() 92 | .oAuthAccessToken(accessToken, accessSecret) 93 | .oAuthConsumer(apiKey, apiSecret) 94 | .build() 95 | val twitterV1 = twitter.v1() 96 | 97 | val users = twitterV1.users() 98 | val friendsFollowers = twitterV1.friendsFollowers() 99 | 100 | if (dryRun) { 101 | println("!!! DRY RUN !!!\n") 102 | } 103 | 104 | var rateLimitStatus: RateLimitStatus = RateLimit.Unlimited 105 | var cursor = -1L 106 | while (cursor != 0L) { 107 | rateLimitStatus.sleepIfNeeded() 108 | 109 | print("Fetching followers…") 110 | val ids = try { 111 | friendsFollowers.getFollowersIDs(cursor) 112 | } catch (e: TwitterException) { 113 | if (e.exceededRateLimitation()) { 114 | println(" failed.") 115 | rateLimitStatus = e.rateLimitStatus ?: RateLimit.FiveMinutes 116 | continue 117 | } else if (e.statusCode == 503) { 118 | println(" service unavailable!") 119 | rateLimitStatus = RateLimit.FiveMinutes 120 | continue 121 | } else { 122 | throw e 123 | } 124 | } 125 | cursor = ids.nextCursor 126 | rateLimitStatus = ids.rateLimitStatus ?: RateLimit.Unlimited 127 | println(" done. (count=${ids.iDs.size}, hasMore=${cursor != 0L})\n") 128 | 129 | rateLimitStatus.sleepIfNeeded(callCount = 2) 130 | 131 | for (id in ids.iDs) { 132 | print("$id: blocking…") 133 | if (!dryRun) { 134 | try { 135 | users.createBlock(id) 136 | } catch (e: Throwable) { 137 | if (e is TwitterException && e.statusCode == 404) { 138 | when (e.statusCode) { 139 | 404 -> { 140 | println(" user not found!") 141 | rateLimitStatus = e.rateLimitStatus ?: RateLimit.Unlimited 142 | continue 143 | } 144 | 503 -> { 145 | println(" service unavailable!") 146 | rateLimitStatus = RateLimit.FiveMinutes 147 | continue 148 | } 149 | } 150 | } 151 | println(" failed!") 152 | throw e 153 | } 154 | } 155 | print(" unblocking…") 156 | if (!dryRun) { 157 | val result = try { 158 | users.destroyBlock(id) 159 | } catch (e: Throwable) { 160 | println(" failed! MANUAL INTERVENTION NEEDED!!") 161 | throw e 162 | } 163 | rateLimitStatus = result.rateLimitStatus ?: RateLimit.Unlimited 164 | } 165 | println(" done.") 166 | } 167 | } 168 | 169 | println("\nAll done!") 170 | if (dryRun) { 171 | println("!!! DRY RUN !!!") 172 | } 173 | } 174 | 175 | private suspend fun RateLimitStatus.sleepIfNeeded(callCount: Int = 1) { 176 | if (remaining > callCount) return 177 | 178 | println() 179 | var lastLength = 0 180 | for (i in secondsUntilReset downTo 1) { 181 | val message = "\rRate limited! Cooling off ${i.seconds}…" 182 | if (message.length < lastLength) { 183 | print("\r" + " ".repeat(lastLength - 1)) 184 | } 185 | lastLength = message.length 186 | print(message) 187 | delay(1.seconds) 188 | } 189 | delay(secondsUntilReset.seconds) 190 | println("\rRate limited! Cooling off… done") 191 | } 192 | } 193 | 194 | private data class RateLimit( 195 | private val remaining: Int, 196 | private val secondsUntilReset: Int, 197 | ) : RateLimitStatus { 198 | override fun getRemaining() = remaining 199 | override fun getLimit() = throw AssertionError() 200 | override fun getResetTimeInSeconds() = throw AssertionError() 201 | override fun getSecondsUntilReset() = secondsUntilReset 202 | 203 | companion object { 204 | val Unlimited = RateLimit(remaining = Int.MAX_VALUE, secondsUntilReset = 0) 205 | val FiveMinutes = RateLimit(remaining = 0, secondsUntilReset = 5 * 60) 206 | } 207 | } 208 | --------------------------------------------------------------------------------