├── .github ├── FUNDING.yml └── workflows │ ├── build_ubuntu.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── Dockerfile ├── Dockerfile.development ├── LICENSE ├── Package.resolved ├── Package.swift ├── README.md ├── Sources ├── App │ ├── AlternateNames.swift │ ├── GeocodingDatabase.swift │ ├── GeocodingapiController.swift │ ├── Geoname.swift │ ├── PointerExtensions.swift │ ├── PostalCodes.swift │ ├── Protobuf+Vapor.swift │ ├── QuadTree.swift │ ├── Structures.swift │ ├── api.pb.swift │ ├── api.proto │ ├── configure.swift │ ├── database.pb.swift │ └── database.proto └── Run │ └── main.swift ├── Tests └── AppTests │ ├── QuadTreeTests.swift │ └── geocoding_apiTests.swift ├── build ├── geocoding-api.env ├── geocoding-api.service └── geocoding-before-install.sh └── docker-compose.yml /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: open-meteo # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.github/workflows/build_ubuntu.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | 4 | name: Build ubuntu package as artifact 5 | 6 | env: 7 | swift_package_resolve: swift package resolve 8 | swift_build: swift build -c release -Xswiftc -g -Xswiftc -static-stdlib 9 | swift_test: swift test 10 | cache_version: 1 11 | 12 | jobs: 13 | linux: 14 | runs-on: ubuntu-22.04 15 | container: swift:6.1.0-jammy 16 | name: Linux 17 | steps: 18 | - name: Get Swift Version 19 | id: get-swift-version 20 | run: echo "version=$(swift -version | head -n 1 | sed s/,// )" >> $GITHUB_OUTPUT 21 | shell: bash 22 | - uses: actions/checkout@v4 23 | - name: Copy Swift Backtrace 24 | run: cp /usr/libexec/swift/linux/swift-backtrace-static ./swift-backtrace 25 | - name: Cache resolved dependencies 26 | id: cache-resolved-dependencies 27 | uses: actions/cache@v4 28 | with: 29 | path: | 30 | .build 31 | Package.resolved 32 | key: ${{ runner.os }}-${{ steps.get-swift-version.outputs.version }}-${{ env.cache_version }}-spm-deps-${{ hashFiles('Package.swift', 'Package.resolved') }} 33 | restore-keys: | 34 | ${{ runner.os }}-${{ steps.get-swift-version.outputs.version }}-${{ env.cache_version }}-spm-deps- 35 | - name: Resolve dependencies 36 | if: steps.cache-resolved-dependencies.outputs.cache-hit != 'true' 37 | run: ${{ env.swift_package_resolve }} 38 | - name: Build 39 | run: | 40 | ${{ env.swift_build }} 41 | mv .build/release/Run geocoding-api 42 | - name: Package 43 | uses: gravitl/github-action-fpm@master 44 | with: 45 | fpm_args: './build' 46 | fpm_opts: '-s dir -t deb -n geocoding-api -v ${{github.ref_name}} --deb-user geoocoding-api --deb-group geoocoding-api --deb-systemd build/geocoding-api.service --deb-default build/geocoding-api.env --before-install build/geocoding-before-install.sh --before-upgrade build/geocoding-before-install.sh geocoding-api=/usr/local/bin/ swift-backtrace=/usr/local/bin/' 47 | - name: Rename deb file 48 | run: mv geocoding-api_${{github.ref_name}}_amd64.deb geocoding-api_${{github.ref_name}}_jammy_amd64.deb 49 | - name: Release 50 | uses: ncipollo/release-action@v1 51 | with: 52 | generateReleaseNotes: true 53 | artifacts: 'geocoding-api_${{github.ref_name}}_jammy_amd64.deb' 54 | draft: true -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | tags: 4 | - '*.*.*' 5 | 6 | name: Upload Release Asset 7 | 8 | env: 9 | swift_package_resolve: swift package resolve 10 | swift_build: swift build -c release -Xswiftc -g -Xswiftc -static-stdlib 11 | swift_test: swift test 12 | cache_version: 1 13 | 14 | jobs: 15 | linux: 16 | runs-on: ubuntu-22.04 17 | container: swift:6.1.0-jammy 18 | name: Linux 19 | steps: 20 | - name: Get Swift Version 21 | id: get-swift-version 22 | run: | 23 | echo "::set-output name=version::$(swift -version | head -n 1 | sed s/,// )" 24 | shell: bash 25 | - uses: actions/checkout@v4 26 | - name: Copy Swift Backtrace 27 | run: cp /usr/libexec/swift/linux/swift-backtrace-static ./swift-backtrace 28 | - name: Cache resolved dependencies 29 | id: cache-resolved-dependencies 30 | uses: actions/cache@v4 31 | with: 32 | path: | 33 | .build 34 | Package.resolved 35 | key: ${{ runner.os }}-${{ steps.get-swift-version.outputs.version }}-${{ env.cache_version }}-spm-deps-${{ hashFiles('Package.swift', 'Package.resolved') }} 36 | restore-keys: | 37 | ${{ runner.os }}-${{ steps.get-swift-version.outputs.version }}-${{ env.cache_version }}-spm-deps- 38 | - name: Resolve dependencies 39 | if: steps.cache-resolved-dependencies.outputs.cache-hit != 'true' 40 | run: ${{ env.swift_package_resolve }} 41 | - name: Build 42 | run: | 43 | ${{ env.swift_build }} 44 | mv .build/release/Run geocoding-api 45 | - name: Package 46 | uses: gravitl/github-action-fpm@master 47 | with: 48 | fpm_args: './build' 49 | fpm_opts: '-s dir -t deb -n geocoding-api -v ${{github.ref_name}} --deb-user geoocoding-api --deb-group geoocoding-api --deb-systemd build/geocoding-api.service --deb-default build/geocoding-api.env --before-install build/geocoding-before-install.sh --before-upgrade build/geocoding-before-install.sh geocoding-api=/usr/local/bin/ swift-backtrace=/usr/local/bin/' 50 | - name: Rename deb file 51 | run: mv geocoding-api_${{github.ref_name}}_amd64.deb geocoding-api_${{github.ref_name}}_jammy_amd64.deb 52 | - name: Release 53 | uses: ncipollo/release-action@v1 54 | with: 55 | generateReleaseNotes: true 56 | artifacts: 'geocoding-api_${{github.ref_name}}_jammy_amd64.deb' 57 | draft: true -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # see https://github.com/peripheryapp/periphery/blob/master/.github/workflows/test.yml 2 | 3 | name: Test 4 | 5 | on: 6 | push: 7 | branches: [ main ] 8 | pull_request: 9 | branches: [ main ] 10 | 11 | env: 12 | swift_package_resolve: swift package resolve 13 | swift_build: swift build --build-tests 14 | swift_test: swift test 15 | cache_version: 1 16 | 17 | jobs: 18 | linux: 19 | runs-on: ubuntu-22.04 20 | container: swift:6.1.0-jammy 21 | name: Linux 22 | steps: 23 | - name: Get Swift Version 24 | id: get-swift-version 25 | run: | 26 | echo "::set-output name=version::$(swift -version | head -n 1 | sed s/,// )" 27 | shell: bash 28 | - uses: actions/checkout@v4 29 | - name: Cache resolved dependencies 30 | id: cache-resolved-dependencies 31 | uses: actions/cache@v4 32 | with: 33 | path: | 34 | .build 35 | Package.resolved 36 | key: ${{ runner.os }}-${{ steps.get-swift-version.outputs.version }}-${{ env.cache_version }}-spm-deps-${{ hashFiles('Package.swift', 'Package.resolved') }} 37 | restore-keys: | 38 | ${{ runner.os }}-${{ steps.get-swift-version.outputs.version }}-${{ env.cache_version }}-spm-deps- 39 | - name: Resolve dependencies 40 | if: steps.cache-resolved-dependencies.outputs.cache-hit != 'true' 41 | run: ${{ env.swift_package_resolve }} 42 | - name: Build 43 | run: ${{ env.swift_build }} 44 | - name: Test 45 | run: ${{ env.swift_test }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | xcuserdata/ 6 | DerivedData/ 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | /data/ 9 | .swiftpm/xcode/xcshareddata/xcschemes/GeocodingApi.xcscheme 10 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # ================================ 2 | # Build image 3 | # ================================ 4 | FROM swift:5.7.1-jammy as build 5 | WORKDIR /build 6 | 7 | # First just resolve dependencies. 8 | # This creates a cached layer that can be reused 9 | # as long as your Package.swift/Package.resolved 10 | # files do not change. 11 | COPY ./Package.* ./ 12 | RUN swift package resolve 13 | 14 | # Copy entire repo into container 15 | COPY . . 16 | 17 | # Compile with optimizations 18 | RUN swift build --enable-test-discovery -c release 19 | 20 | # ================================ 21 | # Run image 22 | # ================================ 23 | FROM swift:5.7.1-jammy-slim 24 | 25 | # Create a vapor user and group with /app as its home directory 26 | RUN useradd --user-group --create-home --system --skel /dev/null --home-dir /app vapor 27 | 28 | # Switch to the new home directory 29 | WORKDIR /app 30 | 31 | # Copy build artifacts 32 | COPY --from=build --chown=vapor:vapor /build/.build/release /app 33 | COPY --from=build --chown=vapor:vapor /build/Resources /app/Resources 34 | COPY --from=build --chown=vapor:vapor /build/.build/release/*.resources /app/Resources/ 35 | COPY --from=build --chown=vapor:vapor /build/Public /app/Public 36 | 37 | # Ensure all further commands run as the vapor user 38 | USER vapor:vapor 39 | 40 | # Start the Vapor service when the image is run, default to listening on 8080 in production environment 41 | ENTRYPOINT ["./app"] 42 | CMD ["serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"] 43 | -------------------------------------------------------------------------------- /Dockerfile.development: -------------------------------------------------------------------------------- 1 | # ================================ 2 | # Build image 3 | # ================================ 4 | FROM swift:5.7.1-jammy as build 5 | EXPOSE 8080 6 | USER root 7 | 8 | RUN mkdir /app 9 | RUN cd /app 10 | WORKDIR /app 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "async-http-client", 6 | "repositoryURL": "https://github.com/swift-server/async-http-client.git", 7 | "state": { 8 | "branch": null, 9 | "revision": "333f51104b75d1a5b94cb3b99e4c58a3b442c9f7", 10 | "version": "1.25.2" 11 | } 12 | }, 13 | { 14 | "package": "async-kit", 15 | "repositoryURL": "https://github.com/vapor/async-kit.git", 16 | "state": { 17 | "branch": null, 18 | "revision": "e048c8ee94967e8d8a1c2ec0e1156d6f7fa34d31", 19 | "version": "1.20.0" 20 | } 21 | }, 22 | { 23 | "package": "console-kit", 24 | "repositoryURL": "https://github.com/vapor/console-kit.git", 25 | "state": { 26 | "branch": null, 27 | "revision": "742f624a998cba2a9e653d9b1e91ad3f3a5dff6b", 28 | "version": "4.15.2" 29 | } 30 | }, 31 | { 32 | "package": "multipart-kit", 33 | "repositoryURL": "https://github.com/vapor/multipart-kit.git", 34 | "state": { 35 | "branch": null, 36 | "revision": "3498e60218e6003894ff95192d756e238c01f44e", 37 | "version": "4.7.1" 38 | } 39 | }, 40 | { 41 | "package": "routing-kit", 42 | "repositoryURL": "https://github.com/vapor/routing-kit.git", 43 | "state": { 44 | "branch": null, 45 | "revision": "93f7222c8e195cbad39fafb5a0e4cc85a8def7ea", 46 | "version": "4.9.2" 47 | } 48 | }, 49 | { 50 | "package": "swift-algorithms", 51 | "repositoryURL": "https://github.com/apple/swift-algorithms.git", 52 | "state": { 53 | "branch": null, 54 | "revision": "87e50f483c54e6efd60e885f7f5aa946cee68023", 55 | "version": "1.2.1" 56 | } 57 | }, 58 | { 59 | "package": "swift-asn1", 60 | "repositoryURL": "https://github.com/apple/swift-asn1.git", 61 | "state": { 62 | "branch": null, 63 | "revision": "a54383ada6cecde007d374f58f864e29370ba5c3", 64 | "version": "1.3.2" 65 | } 66 | }, 67 | { 68 | "package": "swift-atomics", 69 | "repositoryURL": "https://github.com/apple/swift-atomics.git", 70 | "state": { 71 | "branch": null, 72 | "revision": "cd142fd2f64be2100422d658e7411e39489da985", 73 | "version": "1.2.0" 74 | } 75 | }, 76 | { 77 | "package": "swift-collections", 78 | "repositoryURL": "https://github.com/apple/swift-collections.git", 79 | "state": { 80 | "branch": null, 81 | "revision": "671108c96644956dddcd89dd59c203dcdb36cec7", 82 | "version": "1.1.4" 83 | } 84 | }, 85 | { 86 | "package": "swift-crypto", 87 | "repositoryURL": "https://github.com/apple/swift-crypto.git", 88 | "state": { 89 | "branch": null, 90 | "revision": "e8d6eba1fef23ae5b359c46b03f7d94be2f41fed", 91 | "version": "3.12.3" 92 | } 93 | }, 94 | { 95 | "package": "swift-distributed-tracing", 96 | "repositoryURL": "https://github.com/apple/swift-distributed-tracing.git", 97 | "state": { 98 | "branch": null, 99 | "revision": "a64a0abc2530f767af15dd88dda7f64d5f1ff9de", 100 | "version": "1.2.0" 101 | } 102 | }, 103 | { 104 | "package": "swift-http-structured-headers", 105 | "repositoryURL": "https://github.com/apple/swift-http-structured-headers.git", 106 | "state": { 107 | "branch": null, 108 | "revision": "f280fc7676b9940ff2c6598642751ea333c6544f", 109 | "version": "1.2.2" 110 | } 111 | }, 112 | { 113 | "package": "swift-http-types", 114 | "repositoryURL": "https://github.com/apple/swift-http-types.git", 115 | "state": { 116 | "branch": null, 117 | "revision": "a0a57e949a8903563aba4615869310c0ebf14c03", 118 | "version": "1.4.0" 119 | } 120 | }, 121 | { 122 | "package": "swift-log", 123 | "repositoryURL": "https://github.com/apple/swift-log.git", 124 | "state": { 125 | "branch": null, 126 | "revision": "3d8596ed08bd13520157f0355e35caed215ffbfa", 127 | "version": "1.6.3" 128 | } 129 | }, 130 | { 131 | "package": "swift-metrics", 132 | "repositoryURL": "https://github.com/apple/swift-metrics.git", 133 | "state": { 134 | "branch": null, 135 | "revision": "4c83e1cdf4ba538ef6e43a9bbd0bcc33a0ca46e3", 136 | "version": "2.7.0" 137 | } 138 | }, 139 | { 140 | "package": "swift-nio", 141 | "repositoryURL": "https://github.com/apple/swift-nio.git", 142 | "state": { 143 | "branch": null, 144 | "revision": "0f54d58bb5db9e064f332e8524150de379d1e51c", 145 | "version": "2.82.1" 146 | } 147 | }, 148 | { 149 | "package": "swift-nio-extras", 150 | "repositoryURL": "https://github.com/apple/swift-nio-extras.git", 151 | "state": { 152 | "branch": null, 153 | "revision": "f1f6f772198bee35d99dd145f1513d8581a54f2c", 154 | "version": "1.26.0" 155 | } 156 | }, 157 | { 158 | "package": "swift-nio-http2", 159 | "repositoryURL": "https://github.com/apple/swift-nio-http2.git", 160 | "state": { 161 | "branch": null, 162 | "revision": "4281466512f63d1bd530e33f4aa6993ee7864be0", 163 | "version": "1.36.0" 164 | } 165 | }, 166 | { 167 | "package": "swift-nio-ssl", 168 | "repositoryURL": "https://github.com/apple/swift-nio-ssl.git", 169 | "state": { 170 | "branch": null, 171 | "revision": "6df102a39c8da5fdc2eae29a0f63546d660866fc", 172 | "version": "2.30.0" 173 | } 174 | }, 175 | { 176 | "package": "swift-nio-transport-services", 177 | "repositoryURL": "https://github.com/apple/swift-nio-transport-services.git", 178 | "state": { 179 | "branch": null, 180 | "revision": "cd1e89816d345d2523b11c55654570acd5cd4c56", 181 | "version": "1.24.0" 182 | } 183 | }, 184 | { 185 | "package": "swift-numerics", 186 | "repositoryURL": "https://github.com/apple/swift-numerics.git", 187 | "state": { 188 | "branch": null, 189 | "revision": "e0ec0f5f3af6f3e4d5e7a19d2af26b481acb6ba8", 190 | "version": "1.0.3" 191 | } 192 | }, 193 | { 194 | "package": "SwiftProtobuf", 195 | "repositoryURL": "https://github.com/apple/swift-protobuf.git", 196 | "state": { 197 | "branch": null, 198 | "revision": "d72aed98f8253ec1aa9ea1141e28150f408cf17f", 199 | "version": "1.29.0" 200 | } 201 | }, 202 | { 203 | "package": "swift-service-context", 204 | "repositoryURL": "https://github.com/apple/swift-service-context.git", 205 | "state": { 206 | "branch": null, 207 | "revision": "8946c930cae601452149e45d31d8ddfac973c3c7", 208 | "version": "1.2.0" 209 | } 210 | }, 211 | { 212 | "package": "swift-system", 213 | "repositoryURL": "https://github.com/apple/swift-system.git", 214 | "state": { 215 | "branch": null, 216 | "revision": "a34201439c74b53f0fd71ef11741af7e7caf01e1", 217 | "version": "1.4.2" 218 | } 219 | }, 220 | { 221 | "package": "vapor", 222 | "repositoryURL": "https://github.com/vapor/vapor.git", 223 | "state": { 224 | "branch": null, 225 | "revision": "87b0edd2633c35de543cb7573efe5fbf456181bc", 226 | "version": "4.114.1" 227 | } 228 | }, 229 | { 230 | "package": "websocket-kit", 231 | "repositoryURL": "https://github.com/vapor/websocket-kit.git", 232 | "state": { 233 | "branch": null, 234 | "revision": "014ccd52891b8c098d7e1033d5e72ed76fef7a86", 235 | "version": "2.16.0" 236 | } 237 | } 238 | ] 239 | }, 240 | "version": 1 241 | } 242 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.3 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "GeocodingApi", 8 | platforms: [ 9 | .macOS(.v10_15) 10 | ], 11 | dependencies: [ 12 | .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"), 13 | .package(name: "SwiftProtobuf", url: "https://github.com/apple/swift-protobuf.git", from: "1.6.0"), 14 | ], 15 | targets: [ 16 | .target( 17 | name: "App", 18 | dependencies: [ 19 | .product(name: "Vapor", package: "vapor"), 20 | "SwiftProtobuf" 21 | ], 22 | swiftSettings: [ 23 | .unsafeFlags(["-cross-module-optimization"], .when(configuration: .release)), 24 | .unsafeFlags(["-enable-testing"], .when(configuration: .release)), 25 | .unsafeFlags(["-Ounchecked"], .when(configuration: .release)) 26 | ]), 27 | .target(name: "Run", dependencies: [.target(name: "App")]), 28 | .testTarget( 29 | name: "AppTests", 30 | dependencies: ["App"]), 31 | ] 32 | ) 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Geocoding API 2 | 3 | [![Build](https://github.com/open-meteo/geocoding-api/actions/workflows/test.yml/badge.svg)](https://github.com/open-meteo/geocoding-api/actions/workflows/test.yml) 4 | 5 | Todo: 6 | - Reconsider using protobuf library for json encoding (faster, but skips empty values, https://github.com/apple/swift-protobuf/issues/1171) 7 | - include additional postal database http://download.geonames.org/export/zip/ 8 | - correctly implement iso2 county code filter 9 | - GeoIP support + weighted results by distance 10 | - Coordinates proximity search 11 | 12 | 13 | ## Installation on ubuntu 20.04 14 | The standalone `geocodingapi` binary can run on any 64-bit linux with recent libc. Currently only basic installation instructions for ubuntu 22.04 are available. Later Docker and others can be provided. 15 | 16 | ```bash 17 | api install zip 18 | 19 | wget https://github.com/open-meteo/geocoding-api/releases/download/0.1.1/geocoding-api_0.0.6_jammy_amd64.deb 20 | dpkg -i geocoding-api_0.1.1_jammy_amd64.deb 21 | 22 | mkdir /var/lib/geocoding-api/data 23 | cd /var/lib/geocoding-api/data 24 | mkdir zip 25 | curl http://download.geonames.org/export/dump/allCountries.zip -o allCountries.zip 26 | curl http://download.geonames.org/export/dump/alternateNames.zip -o alternateNames.zip 27 | curl http://download.geonames.org/export/zip/allCountries.zip -o zip/allCountries.zip 28 | unzip allCountries.zip 29 | unzip alternateNames.zip 30 | cd zip; unzip allCountries.zip; cd .. 31 | 32 | systemctl enable geocoding-api.service 33 | systemctl start geocoding-api.service 34 | systemctl status geocoding-api.service 35 | ``` 36 | 37 | Geonames data are parsed and processed during the first start, which requires some times and memor. At least 6GB RAM is required and it takes about 25 minutes on a CPU with 2 Skylake cores. Database loading takes about 5 minutes after that. 38 | 39 | Additionally, nginx proxy should be used. 40 | 41 | ## Terms & Privacy 42 | Open-Meteo APIs are free for open-source developer and non-commercial use. We do not restrict access, but ask for fair use. 43 | 44 | If your application exceeds 10'000 requests per day, please contact us. We reserve the right to block applications and IP addresses that misuse our service. 45 | 46 | For commercial use of Open-Meteo APIs, please contact us. 47 | 48 | All data is provided as is without any warranty. 49 | 50 | We do not collect any personal data. We do not share any personal information. We do not integrate any third party analytics, ads, beacons or plugins. 51 | 52 | ## Data License 53 | API data are offered under Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) 54 | 55 | You are free to share: copy and redistribute the material in any medium or format and adapt: remix, transform, and build upon the material. 56 | 57 | Attribution: You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. 58 | 59 | You must include a link next to any location, Open-Meteo data are displayed like: 60 | 61 | Weather data by Open-Meteo.com 62 | 63 | NonCommercial: You may not use the material for commercial purposes. 64 | 65 | 66 | ## Source Code License 67 | Open-Meteo is open-source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can [find the license here](LICENSE). Exceptions are third party source-code with individual licensing in each file. 68 | -------------------------------------------------------------------------------- /Sources/App/AlternateNames.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | 4 | 5 | struct AlternateNames { 6 | let alternativesPreferred: [Int32: [Int32: String]] 7 | let postcodes: [Int32: [String]] 8 | let languages: [String] 9 | 10 | /** 11 | The table 'alternate names' : 12 | ----------------------------- 13 | 0. alternateNameId : the id of this alternate name, int 14 | 1. geonameid : geonameId referring to id in table 'geoname', int 15 | 2. isolanguage : iso 639 language code 2- or 3-characters; 4-characters 'post' for postal codes and 'iata','icao' and faac for airport codes, fr_1793 for French Revolution names, abbr for abbreviation, link to a website (mostly to wikipedia), wkdt for the wikidataid, varchar(7) 16 | 3. alternate name : alternate name or name variant, varchar(400) 17 | 4. isPreferredName : '1', if this alternate name is an official/preferred name 18 | 5. isShortName : '1', if this is a short name like 'California' for 'State of California' 19 | 6. isColloquial : '1', if this alternate name is a colloquial or slang term. Example: 'Big Apple' for 'New York'. 20 | 7. isHistoric : '1', if this alternate name is historic and was used in the past. Example 'Bombay' for 'Mumbai'. 21 | 8. from : from period when the name was used 22 | 9. to : to period when the name was used 23 | */ 24 | public init(data: Data, logger: Logger) { 25 | let start = Date() 26 | logger.info("Alternative names: Start loading") 27 | let tab = Character("\t").asciiValue! 28 | 29 | var languages = DeduplicatedStrings() 30 | var alternateNames = [Int32: [AlternateName]]() 31 | var postcodes = [Int32: [String]]() 32 | 33 | data.forEachLine { line in 34 | if line.isEmpty { 35 | return 36 | } 37 | var offset = 0 38 | 39 | let _ = line.seekUntil(value: tab, offset: &offset) // alternatenameid 40 | let geonameid = line.seekUntil(value: tab, offset: &offset).asciiToInt32 41 | let isolanguage = line.seekUntil(value: tab, offset: &offset) 42 | let alternateName = line.seekUntil(value: tab, offset: &offset).string 43 | let isPreferredName = line.seekUntil(value: tab, offset: &offset).asciiToInt8 44 | let isShortName = line.seekUntil(value: tab, offset: &offset).asciiToInt8 45 | let isColloquial = line.seekUntil(value: tab, offset: &offset).asciiToInt8 46 | //let isHistoric = line[line.seekUntil(value: tab, offset: &offset)].asciiToInt8 47 | 48 | let isolanguageString = isolanguage.string 49 | 50 | if isolanguageString == "link" || isolanguageString == "wkdt" || isolanguageString == "fr_1793" { 51 | return 52 | } 53 | 54 | if isColloquial == 1 { //isHistoric == 1 || 55 | return 56 | } 57 | 58 | if isolanguageString == "post" { 59 | if postcodes[geonameid] == nil { 60 | postcodes[geonameid] = [alternateName] 61 | } else { 62 | postcodes[geonameid]?.append(alternateName) 63 | } 64 | return 65 | } 66 | 67 | let alternateNameStruct = AlternateName( 68 | //geonameid: geonameid, 69 | languageId: languages.findOrAppend(isolanguage), 70 | alternateName: alternateName, 71 | isPreferredeName: isPreferredName != 0, 72 | isShortName: isShortName != 0 73 | ) 74 | 75 | if alternateNames[geonameid] != nil { 76 | alternateNames[geonameid]?.append(alternateNameStruct) 77 | } else { 78 | alternateNames[geonameid] = [alternateNameStruct] 79 | } 80 | } 81 | 82 | var alternativesPreferred = [Int32: [Int32: String]]() 83 | alternativesPreferred.reserveCapacity(alternateNames.count) 84 | for (id, names) in alternateNames { 85 | /// For each langauge, find tthe most suitable alternativeName. Prefer short ones 86 | let languageIds = names.unique(of: {$0.languageId}) 87 | var res = [Int32: String]() 88 | res.reserveCapacity(languageIds.count) 89 | for languageId in languageIds { 90 | let perLanguage = names.filter({$0.languageId == languageId }) 91 | res[languageId] = perLanguage.getPreferred() 92 | } 93 | alternativesPreferred[id] = res 94 | } 95 | 96 | self.languages = languages.strings 97 | self.alternativesPreferred = alternativesPreferred 98 | self.postcodes = postcodes 99 | 100 | logger.info("Alternative names: Finished loading in \(Date().timeIntervalSince(start)) seconds") 101 | } 102 | } 103 | 104 | fileprivate struct AlternateName { 105 | //let geonameid: Int32 106 | let languageId: Int32 107 | let alternateName: String 108 | let isPreferredeName: Bool 109 | let isShortName: Bool 110 | } 111 | 112 | fileprivate extension Array where Element == AlternateName { 113 | func getPreferred() -> String { 114 | var short: String? = nil 115 | var preferred: String? = nil 116 | var other: String? = nil 117 | for alternate in self { 118 | if alternate.isPreferredeName && alternate.isShortName { 119 | return alternate.alternateName 120 | } 121 | if alternate.isShortName { 122 | short = alternate.alternateName 123 | continue 124 | } 125 | if alternate.isPreferredeName { 126 | preferred = alternate.alternateName 127 | continue 128 | } 129 | other = alternate.alternateName 130 | } 131 | return short ?? preferred ?? other ?? "" 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /Sources/App/GeocodingDatabase.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | 4 | 5 | extension GeocodingDatabase { 6 | static let geonamesFile = URL(fileURLWithPath: "data/allCountries.txt") 7 | static let alternateNamesFiles = URL(fileURLWithPath: "data/alternateNames.txt") 8 | static let databaseFile = URL(fileURLWithPath: "data/database.bin") 9 | 10 | /// Read geonames txt files and create an index protobuf file 11 | public static func createDatabase(logger: Logger) throws { 12 | logger.info("Create new geocoding database") 13 | let alternativeNamesData = try Data(contentsOf: alternateNamesFiles, options: [.mappedIfSafe, .uncached]) 14 | let alternate = AlternateNames(data: alternativeNamesData, logger: logger) 15 | 16 | let geonamesData = try Data(contentsOf: geonamesFile, options: [.mappedIfSafe, .uncached]) 17 | let geonames = GeocodingDatabase.Geonames(data: geonamesData, alternativeNames: alternate, logger: logger) 18 | 19 | let searchTree = GeocodingDatabase(geonames: geonames, logger: logger) 20 | let data: Data = try searchTree.serializedData() 21 | let start = Date() 22 | logger.info("Write database to disk") 23 | try data.write(to: databaseFile) 24 | logger.info("Database written in \(Date().timeIntervalSince(start)) seconds, size \(ByteCountFormatter().string(fromByteCount: Int64(data.count)))") 25 | } 26 | 27 | public static func loadOrCreate(logger: Logger) throws -> GeocodingDatabase { 28 | if !FileManager.default.fileExists(atPath: databaseFile.path) { 29 | try Self.createDatabase(logger: logger) 30 | } 31 | let start = Date() 32 | logger.info("Loading existing database...") 33 | let data = try Data(contentsOf: URL(fileURLWithPath: "data/database.bin"), options: [.mappedIfSafe, .uncached]) 34 | let searchTree = try GeocodingDatabase(serializedBytes: data) 35 | logger.info("Finished loading in \(Date().timeIntervalSince(start)) seconds, \(searchTree.geonames.geonames.count) entries") 36 | return searchTree 37 | } 38 | 39 | /// Search for a string in the indexed location names and one language index 40 | public func search(_ searchString: String, languageId: Int32, maxCount: Int) -> [(Int32, Float)] { 41 | let stripped = searchString.folding(options: .diacriticInsensitive, locale: nil).lowercased() 42 | let results = PriorityQueue(length: maxCount) 43 | let onlyExact = searchString.count <= 2 44 | index.search(Substring(stripped), results: results, onlyExact: onlyExact, geonames: geonames.geonames) 45 | languageIndex[Int(languageId)].search(Substring(stripped), results: results, onlyExact: onlyExact, geonames: geonames.geonames) 46 | return results.queue.filter({$0.id > 0}) 47 | } 48 | 49 | /// Search for a string in the indexed location names and one language index 50 | public func proximity(latitude: Float, longitude: Float, maxCount: Int, maxDistanceKilometer: Float) -> [(Int32, Float)] { 51 | let results = geotree.knn(latitude: latitude, longitude: longitude, count: maxCount, maxDistanceKilometer: maxDistanceKilometer, elements: geonames.geonames) 52 | return results.filter({$0.id > 0}) 53 | } 54 | 55 | public init(geonames: Geonames, logger: Logger) { 56 | logger.info("GeoTree: Start loading") 57 | let startTree = Date() 58 | self.geotree = GeoTree(elements: geonames.geonames, depth: nil) 59 | logger.info("GeoTree: Finished loading in \(Date().timeIntervalSince(startTree)) seconds") 60 | 61 | let start = Date() 62 | logger.info("SearchTree: Start loading") 63 | 64 | self.geonames = geonames 65 | var languageIndex = [SearchTreeLoader]() 66 | languageIndex.reserveCapacity(geonames.languages.count) 67 | for _ in geonames.languages { 68 | languageIndex.append(SearchTreeLoader()) 69 | } 70 | let languageEmpty = geonames.languages.firstIndex(where: {$0 == ""})! 71 | let languageIata = geonames.languages.firstIndex(where: {$0 == "icao"})! 72 | let languageIcao = geonames.languages.firstIndex(where: {$0 == "iata"})! 73 | 74 | logger.info("SearchTree: Prepare language trees") 75 | for (id, geoname) in geonames.geonames { 76 | if !geonames.includeInSearchIndex(featureCode: geoname.featureCode) { 77 | continue 78 | } 79 | for name in geoname.alternativeNames { 80 | if name.0 == languageEmpty { 81 | continue 82 | } 83 | languageIndex[Int(name.0)].add(name.1, id: id) 84 | } 85 | } 86 | self.languageIndex = languageIndex.map({$0.immutable()}) 87 | 88 | logger.info("SearchTree: Load main index") 89 | let index = SearchTreeLoader() 90 | for (id, geoname) in geonames.geonames { 91 | if !geonames.includeInSearchIndex(featureCode: geoname.featureCode) { 92 | continue 93 | } 94 | index.add(geoname.name, id: id) 95 | for name in geoname.alternativeNames { 96 | if name.0 == languageEmpty || name.0 == languageIata || name.0 == languageIcao { 97 | index.add(name.1, id: id) 98 | } 99 | } 100 | for name in geoname.postcodes { 101 | index.add(name, id: id) 102 | } 103 | } 104 | self.index = index.immutable() 105 | 106 | logger.info("SearchTree: Finished loading in \(Date().timeIntervalSince(start)) seconds") 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Sources/App/GeocodingapiController.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | 4 | /** 5 | API Endpoints: 6 | /v1/search?name=Berlin (&country=DE &count=30 &lang=de) later maybe &page=1 7 | Queries with 0 or 1 character, return empty results 8 | 2 character only exact match 9 | 3 character and more fuzzy search 10 | 11 | // langauge ICAO and IATA also works! 12 | /v1/get?id=12345 &lang=de 13 | /v1/proximity?latitude=12&longitude=12 (&radius=30 &count=30 &page=1) 14 | /v1/geoip 15 | */ 16 | 17 | struct GeocodingapiController: RouteCollection { 18 | let database: GeocodingDatabase 19 | 20 | public init(_ app: Application) throws { 21 | database = try GeocodingDatabase.loadOrCreate(logger: app.logger) 22 | } 23 | 24 | func boot(routes: RoutesBuilder) throws { 25 | let cors = CORSMiddleware(configuration: .init( 26 | allowedOrigin: .all, 27 | allowedMethods: [.GET, /*.POST, .PUT,*/ .OPTIONS, /*.DELETE, .PATCH*/], 28 | allowedHeaders: [.accept, .authorization, .contentType, .origin, .xRequestedWith] 29 | )) 30 | let corsGroup = routes.grouped(cors, ErrorMiddleware.default(environment: try .detect())) 31 | let categoriesRoute = corsGroup.grouped("v1") 32 | categoriesRoute.get("search", use: self.search) 33 | //categoriesRoute.get("proximity", use: self.proxmity) 34 | categoriesRoute.get("get", use: self.get) 35 | } 36 | 37 | func search(_ request: Request) throws -> EventLoopFuture { 38 | struct SearchQuery: Content { 39 | let name: String 40 | let language: String? 41 | let countryCode: String? 42 | let format: ProtobufSerializationFormat? 43 | let count: Int? 44 | 45 | func getCount() throws -> Int { 46 | let count = self.count ?? 10 47 | guard count > 0 && count <= 100 else { 48 | throw GeocodingApiError.invalidCount 49 | } 50 | return count 51 | } 52 | } 53 | let start = Date() 54 | let params = try request.query.decode(SearchQuery.self) 55 | let language = params.language ?? "en" 56 | let languageId = database.geonames.languages.firstIndex(of: language) ?? database.geonames.languages.firstIndex(of: "en")! 57 | let count = try params.getCount() 58 | 59 | var name = params.name 60 | var areaIds: [Int32]? 61 | if name.contains(",") { // Split string by comma, so we can filter the results later by second part 62 | let parts = name.components(separatedBy: ",") 63 | name = parts[0].trimmingCharacters(in: .whitespacesAndNewlines) 64 | let areaName = parts[1].trimmingCharacters(in: .whitespacesAndNewlines) 65 | if areaName.count > 1 { 66 | areaIds = database.search(areaName, languageId: Int32(languageId), maxCount: 10).compactMap({ 67 | guard ["ADM1","ADM2","ADM3","ADM4","PCLI"].contains(database.geonames.geonames[$0.0]?.featureCode) else { 68 | return nil 69 | } 70 | return $0.0 71 | }) 72 | } 73 | } 74 | 75 | var results = params.name.count < 2 ? [] : database.search(name, languageId: Int32(languageId), maxCount: count) 76 | /// TODO country filter need to be inside database match, because `count` would be wrong otherwise 77 | if let countryCode = params.countryCode { 78 | /*guard let countryId = searchTree.geonames.countryIso2.firstIndex(of: countryCode) else { 79 | throw GeocodingApiError.invalidContryCode 80 | }*/ 81 | results = results.filter({ 82 | guard let c = database.geonames.geonames[$0.0]?.countryIso2 else { 83 | return false 84 | } 85 | return c == countryCode 86 | }) 87 | } 88 | if let areas = areaIds { 89 | results = results.filter({ // Filter the results by second part of the original string 90 | return areas.contains(database.geonames.geonames[$0.0]?.admin1ID ?? -1) 91 | || areas.contains(database.geonames.geonames[$0.0]?.admin2ID ?? -1) 92 | || areas.contains(database.geonames.geonames[$0.0]?.admin3ID ?? -1) 93 | || areas.contains(database.geonames.geonames[$0.0]?.admin4ID ?? -1) 94 | || areas.contains(database.geonames.geonames[$0.0]?.countryID ?? -1) 95 | }) 96 | } 97 | let mapped: [GeocodingApi.Geoname] = results.map({ 98 | guard let geoname = database.geonames.getResponse(id: $0.0, languageId: Int32(languageId), searchRank: $0.1) else { 99 | fatalError("Geoname in search index was not in database.") 100 | } 101 | return geoname 102 | }) 103 | var out = GeocodingApi.SearchResults() 104 | out.results = mapped 105 | out.generationtimeMs = Float(Date().timeIntervalSince(start)*1000) 106 | return request.eventLoop.makeSucceededFuture(try out.encode(format: params.format)) 107 | } 108 | 109 | 110 | /*func proxmity(_ request: Request) throws -> EventLoopFuture { 111 | struct SearchQuery: Content { 112 | let latitude: Float 113 | let longitude: Float 114 | let language: String? 115 | let countryCode: String? 116 | let format: ProtobufSerializationFormat? 117 | let count: Int? 118 | 119 | func getCount() throws -> Int { 120 | let count = self.count ?? 10 121 | guard count > 0 && count <= 100 else { 122 | throw GeocodingApiError.invalidCount 123 | } 124 | return count 125 | } 126 | } 127 | let start = Date() 128 | let params = try request.query.decode(SearchQuery.self) 129 | let language = params.language ?? "en" 130 | let languageId = database.geonames.languages.firstIndex(of: language) ?? database.geonames.languages.firstIndex(of: "en")! 131 | let count = try params.getCount() 132 | // TODO ranking by distance OR priority 133 | var results = database.proximity(latitude: params.latitude, longitude: params.longitude, maxCount: count, maxDistanceKilometer: 100) 134 | /// TODO country filter need to be inside database match, because `count` would be wrong otherwise 135 | if let countryCode = params.countryCode { 136 | /*guard let countryId = searchTree.geonames.countryIso2.firstIndex(of: countryCode) else { 137 | throw GeocodingApiError.invalidContryCode 138 | }*/ 139 | results = results.filter({ 140 | guard let c = database.geonames.geonames[$0.0]?.countryIso2 else { 141 | return false 142 | } 143 | return c == countryCode 144 | }) 145 | } 146 | let mapped: [GeocodingApi.Geoname] = results.map({ 147 | guard let geoname = database.geonames.getResponse(id: $0.0, languageId: Int32(languageId), searchRank: $0.1) else { 148 | fatalError("Geoname in search index was not in database.") 149 | } 150 | return geoname 151 | }) 152 | var out = GeocodingApi.SearchResults() 153 | out.results = mapped 154 | out.generationtimeMs = Float(Date().timeIntervalSince(start)*1000) 155 | return request.eventLoop.makeSucceededFuture(try out.encode(format: params.format)) 156 | }*/ 157 | 158 | func get(_ request: Request) throws -> EventLoopFuture{ 159 | struct GetQuery: Content { 160 | let id: Int32 161 | let language: String? 162 | let format: ProtobufSerializationFormat? 163 | } 164 | let params = try request.query.decode(GetQuery.self) 165 | let language = params.language ?? "en" 166 | let languageId = database.geonames.languages.firstIndex(of: language) ?? database.geonames.languages.firstIndex(of: "en")! 167 | 168 | guard let out = database.geonames.getResponse(id: params.id, languageId: Int32(languageId), searchRank: 0) else { 169 | throw GeocodingApiError.locationNotFound(id: params.id) 170 | } 171 | return request.eventLoop.makeSucceededFuture(try out.encode(format: params.format)) 172 | } 173 | } 174 | 175 | enum GeocodingApiError: Error { 176 | case locationNotFound(id: Int32) 177 | case invalidCount 178 | //case invalidContryCode 179 | } 180 | 181 | extension GeocodingApiError: AbortError { 182 | var status: HTTPResponseStatus { 183 | return .badRequest 184 | } 185 | 186 | var reason: String { 187 | switch self { 188 | case .locationNotFound(id: _): 189 | return "Location ID not found." 190 | //case .invalidContryCode: 191 | // return "Invalid country code" 192 | case .invalidCount: 193 | return "Parameter count must be between 1 and 100." 194 | } 195 | } 196 | } 197 | 198 | 199 | extension GeocodingDatabase.Geoname { 200 | func getName(languageId: Int32) -> String { 201 | return alternativeNames.first(where: {$0.0 == languageId})?.1 ?? name 202 | } 203 | } 204 | 205 | extension GeocodingDatabase.Geonames { 206 | func getResponse(id: Int32, languageId: Int32, searchRank: Float) -> GeocodingApi.Geoname? { 207 | guard let g = geonames[id] else { 208 | return nil 209 | } 210 | 211 | var out = GeocodingApi.Geoname() 212 | out.id = g.id 213 | out.name = g.getName(languageId: languageId) 214 | out.latitude = g.latitude 215 | out.longitude = g.longitude 216 | out.elevation = g.elevation 217 | out.countryCode = g.countryIso2 218 | out.countryID = g.countryID 219 | out.country = geonames[g.countryID]?.getName(languageId: languageId) ?? "" 220 | out.featureCode = g.featureCode 221 | out.admin1ID = g.admin1ID 222 | out.admin2ID = g.admin2ID 223 | out.admin3ID = g.admin3ID 224 | out.admin4ID = g.admin4ID 225 | out.admin1 = geonames[g.admin1ID]?.getName(languageId: languageId) ?? "" 226 | out.admin2 = geonames[g.admin2ID]?.getName(languageId: languageId) ?? "" 227 | out.admin3 = geonames[g.admin3ID]?.getName(languageId: languageId) ?? "" 228 | out.admin4 = geonames[g.admin4ID]?.getName(languageId: languageId) ?? "" 229 | out.population = g.population 230 | out.timezone = timezones[Int(g.timezoneIndex)] 231 | out.postcodes = g.postcodes 232 | //out.ranking = g.ranking 233 | //out.searchRank = searchRank 234 | return out 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /Sources/App/Geoname.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | 4 | 5 | /** 6 | Loads the main geonames table. 7 | 8 | Fields timezones, featureCodes and countryIso2 are highly redundant the kept in separat arrays to reduce memory. 9 | 10 | Admin codes 1 to 4 are hashed and kept as a lookup table to the representative geonameid 11 | */ 12 | extension GeocodingDatabase.Geonames { 13 | /** 14 | The main 'geoname' table has the following fields : 15 | --------------------------------------------------- 16 | 0. geonameid : integer id of record in geonames database 17 | 1. name : name of geographical point (utf8) varchar(200) 18 | 2. asciiname : name of geographical point in plain ascii characters, varchar(200) 19 | 3. alternatenames : alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000) 20 | 4. latitude : latitude in decimal degrees (wgs84) 21 | 5. longitude : longitude in decimal degrees (wgs84) 22 | 6. feature class : see http://www.geonames.org/export/codes.html, char(1) 23 | 7. feature code : see http://www.geonames.org/export/codes.html, varchar(10) 24 | 8. country code : ISO-3166 2-letter country code, 2 characters 25 | 9. cc2 : alternate country codes, comma separated, ISO-3166 2-letter country code, 200 characters 26 | 10. admin1 code : fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20) 27 | 11. admin2 code : code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80) 28 | 12. admin3 code : code for third level administrative division, varchar(20) 29 | 13. admin4 code : code for fourth level administrative division, varchar(20) 30 | 14. population : bigint (8 byte int) 31 | 15. elevation : in meters, integer 32 | 16. dem : digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat. 33 | 17. timezone : the iana timezone id (see file timeZone.txt) varchar(40) 34 | 18. modification date : date of last modification in yyyy-MM-dd format 35 | */ 36 | init(data: Data, alternativeNames: AlternateNames, logger: Logger) { 37 | let start = Date() 38 | logger.info("Geonames: Start loading") 39 | 40 | var timeszones = DeduplicatedStrings() 41 | //var featureCodes = DeduplicatedStrings() 42 | //var countryIso2 = DeduplicatedStrings() 43 | var geonames = [Int32: GeocodingDatabase.Geoname]() 44 | 45 | var admin1ToGeonameId = [Int: Int32]() 46 | var admin2ToGeonameId = [Int: Int32]() 47 | var admin3ToGeonameId = [Int: Int32]() 48 | var admin4ToGeonameId = [Int: Int32]() 49 | var countries = [String: Int32]() 50 | 51 | let tab = Character("\t").asciiValue! 52 | 53 | /// first pass, look for admin areas and count how many geonames we are about to index 54 | var count = 0 55 | data.forEachLine { line in 56 | if line.isEmpty { 57 | return 58 | } 59 | var offset = 0 60 | let positionGeonameid = line.seekUntil(value: tab, offset: &offset) 61 | let _ = line.seekUntil(value: tab, offset: &offset) 62 | let _ = line.seekUntil(value: tab, offset: &offset) 63 | let _ = line.seekUntil(value: tab, offset: &offset) 64 | let _ = line.seekUntil(value: tab, offset: &offset) 65 | let _ = line.seekUntil(value: tab, offset: &offset) 66 | let _ = line.seekUntil(value: tab, offset: &offset) 67 | let positionFeatureCode = line.seekUntil(value: tab, offset: &offset) 68 | let positionCountryCode = line.seekUntil(value: tab, offset: &offset) 69 | let _ = line.seekUntil(value: tab, offset: &offset) // positionCC2 70 | let positionAdmin1 = line.seekUntil(value: tab, offset: &offset) 71 | let positionAdmin2 = line.seekUntil(value: tab, offset: &offset) 72 | let positionAdmin3 = line.seekUntil(value: tab, offset: &offset) 73 | let positionAdmin4 = line.seekUntil(value: tab, offset: &offset) 74 | 75 | let featureCode = positionFeatureCode.string 76 | if !Self.includeGeoname(featureCode: featureCode) { 77 | return 78 | } 79 | 80 | count += 1 81 | 82 | let geonameid = positionGeonameid.asciiToInt32 83 | 84 | 85 | // If the geoname is a administrative area, store the reference 86 | if featureCode == "ADM1" { 87 | let admin1Hash = positionCountryCode.extendUntil(positionAdmin1).hashValue 88 | admin1ToGeonameId[admin1Hash] = geonameid 89 | } 90 | if featureCode == "ADM2" { 91 | let admin2Hash = positionCountryCode.extendUntil(positionAdmin2).hashValue 92 | admin2ToGeonameId[admin2Hash] = geonameid 93 | } 94 | if featureCode == "ADM3" { 95 | let admin3Hash = positionCountryCode.extendUntil(positionAdmin3).hashValue 96 | admin3ToGeonameId[admin3Hash] = geonameid 97 | } 98 | if featureCode == "ADM4" { 99 | let admin4Hash = positionCountryCode.extendUntil(positionAdmin4).hashValue 100 | admin4ToGeonameId[admin4Hash] = geonameid 101 | } 102 | if featureCode == "PCLI" { 103 | countries[positionCountryCode.string] = geonameid 104 | } 105 | } 106 | 107 | logger.info("Geonames: Reserving memory for \(count) entries") 108 | geonames.reserveCapacity(count) 109 | logger.info("Geonames: Start reading") 110 | 111 | data.forEachLine { line in 112 | if line.isEmpty { 113 | return 114 | } 115 | var offset = 0 116 | let positionGeonameid = line.seekUntil(value: tab, offset: &offset) 117 | let positionName = line.seekUntil(value: tab, offset: &offset) 118 | let _ = line.seekUntil(value: tab, offset: &offset) // positionAsciiname 119 | let _ = line.seekUntil(value: tab, offset: &offset) // positionAlterenateName 120 | let positionLatitude = line.seekUntil(value: tab, offset: &offset) 121 | let positionLongitude = line.seekUntil(value: tab, offset: &offset) 122 | let _ = line.seekUntil(value: tab, offset: &offset) // positionFeatureClass 123 | let positionFeatureCode = line.seekUntil(value: tab, offset: &offset) 124 | let positionCountryCode = line.seekUntil(value: tab, offset: &offset) 125 | let _ = line.seekUntil(value: tab, offset: &offset) // positionCC2 126 | let positionAdmin1 = line.seekUntil(value: tab, offset: &offset) 127 | let positionAdmin2 = line.seekUntil(value: tab, offset: &offset) 128 | let positionAdmin3 = line.seekUntil(value: tab, offset: &offset) 129 | let positionAdmin4 = line.seekUntil(value: tab, offset: &offset) 130 | let positionPopulation = line.seekUntil(value: tab, offset: &offset) 131 | let positionElevation = line.seekUntil(value: tab, offset: &offset) 132 | let positionDEM = line.seekUntil(value: tab, offset: &offset) 133 | let positionTimezone = line.seekUntil(value: tab, offset: &offset) 134 | 135 | let featureCode = positionFeatureCode.string 136 | if !Self.includeGeoname(featureCode: featureCode) { 137 | return 138 | } 139 | 140 | let geonameid = positionGeonameid.asciiToInt32 141 | let name = positionName.string 142 | 143 | let latitude = Float(positionLatitude.string)! 144 | let longitude = Float(positionLongitude.string)! 145 | //let featureClass = line[positionLongitude ..< positionFeatureClass].first ?? 0 146 | let countryCode = positionCountryCode.string 147 | /// We do not need the actual value, just a hash to test if it is equal is fine 148 | 149 | let admin1 = admin1ToGeonameId[positionCountryCode.extendUntil(positionAdmin1).hashValue] ?? 0 150 | let admin2 = admin2ToGeonameId[positionCountryCode.extendUntil(positionAdmin2).hashValue] ?? 0 151 | let admin3 = admin3ToGeonameId[positionCountryCode.extendUntil(positionAdmin3).hashValue] ?? 0 152 | let admin4 = admin4ToGeonameId[positionCountryCode.extendUntil(positionAdmin4).hashValue] ?? 0 153 | let countryID = countries[countryCode] ?? 0 154 | 155 | let population = positionPopulation.asciiToUInt32 156 | let elevation = positionElevation.isEmpty ? positionDEM.asciiToInt16 : positionElevation.asciiToInt16 157 | let timezone = positionTimezone 158 | 159 | 160 | var ranking = Self.populationToRank(population) 161 | let postcodes = alternativeNames.postcodes[geonameid] ?? [] 162 | 163 | if postcodes.count > 0 { 164 | ranking += 0.1 165 | } 166 | if featureCode == "PPL" { 167 | ranking += 0.1 168 | } 169 | if featureCode == "PPLA" || featureCode == "PPLC" { 170 | ranking += 0.3 171 | } 172 | if featureCode == "PPLA2" { 173 | ranking += 0.23 174 | } 175 | if featureCode == "PPLA3" { 176 | ranking += 0.2 177 | } 178 | if featureCode == "PPLA4" { 179 | ranking += 0.18 180 | } 181 | if featureCode == "PPLA5" { 182 | ranking += 0.15 183 | } 184 | var g = GeocodingDatabase.Geoname() 185 | g.id = geonameid 186 | g.name = name 187 | g.latitude = latitude 188 | g.longitude = longitude 189 | g.ranking = ranking 190 | g.elevation = Float(elevation) 191 | g.featureCode = featureCode 192 | g.countryIso2 = countryCode 193 | g.admin1ID = admin1 194 | g.admin2ID = admin2 195 | g.admin3ID = admin3 196 | g.admin4ID = admin4 197 | g.countryID = countryID 198 | g.timezoneIndex = timeszones.findOrAppend(timezone) 199 | g.population = population 200 | g.alternativeNames = alternativeNames.alternativesPreferred[geonameid] ?? [:] 201 | g.postcodes = postcodes 202 | geonames[geonameid] = g 203 | } 204 | 205 | precondition(geonames.count == count) 206 | 207 | var languagesMap = [String: UInt16]() 208 | languagesMap.reserveCapacity(alternativeNames.languages.count) 209 | for (id, language) in alternativeNames.languages.enumerated() { 210 | languagesMap[language] = UInt16(id) 211 | } 212 | 213 | self.geonames = geonames 214 | self.timezones = timeszones.strings 215 | //self.countryIso2 = countryIso2.strings 216 | //self.featureCodes = featureCodes.strings 217 | self.languages = alternativeNames.languages 218 | //self.countries = countries 219 | //self.languagesMap = languagesMap 220 | 221 | logger.info("Geonames: Finished loading in \(Date().timeIntervalSince(start)) seconds, \(geonames.count) entries") 222 | } 223 | 224 | func includeInSearchIndex(featureCode: String) -> Bool { 225 | //let featureCode = featureCodes[Int(geoname.featureCodeId)] 226 | switch featureCode { 227 | case "PCL": fallthrough 228 | case "ADM1": fallthrough 229 | case "ADM2": fallthrough 230 | case "ADM3": fallthrough 231 | case "ADM4": fallthrough 232 | case "ADM5": fallthrough 233 | case "LTER": fallthrough 234 | case "PRSH": fallthrough 235 | case "TERR": fallthrough 236 | case "ZN": fallthrough 237 | case "ZNB": return false 238 | default: return true 239 | } 240 | } 241 | 242 | /// Whether or not to include feature codes from loading 243 | static func includeGeoname(featureCode: String) -> Bool { 244 | switch featureCode { 245 | case "ADM1": fallthrough 246 | case "ADM2": fallthrough 247 | case "ADM3": fallthrough 248 | case "ADM4": fallthrough 249 | case "ADM5": fallthrough 250 | case "PCLI": fallthrough 251 | case "PCLD": fallthrough 252 | case "PCLIX": fallthrough 253 | case "PCLS": fallthrough 254 | case "PCLF": fallthrough 255 | case "PCL": fallthrough 256 | case "PPL": fallthrough 257 | case "PPLL": fallthrough 258 | case "PPLC": fallthrough 259 | case "PPLA": fallthrough 260 | case "PPLA2": fallthrough 261 | case "PPLA3": fallthrough 262 | case "PPLA4": fallthrough 263 | case "PPLX": fallthrough 264 | case "PPLS": fallthrough 265 | case "PPLCH": fallthrough 266 | case "PPLG": fallthrough 267 | case "AMUS": fallthrough 268 | case "AIRP": fallthrough 269 | case "MT": fallthrough 270 | case "MTS": fallthrough 271 | case "PK": fallthrough 272 | case "PKS": fallthrough 273 | case "PAN": fallthrough 274 | case "PANS": fallthrough 275 | case "PASS": fallthrough 276 | case "VALL": fallthrough 277 | case "VALX": fallthrough 278 | case "VALG": fallthrough 279 | case "VALS": fallthrough 280 | case "FLLS": fallthrough 281 | case "DAM": fallthrough 282 | case "PRK": fallthrough 283 | case "GLCR": fallthrough 284 | case "CONT": fallthrough 285 | case "UPLD": fallthrough 286 | case "ISL": fallthrough 287 | case "ISLET": fallthrough 288 | case "ISLF": fallthrough 289 | case "ISLM": fallthrough 290 | case "ISLS": fallthrough 291 | case "ISLT": fallthrough 292 | case "CAPE": fallthrough 293 | case "AIRF": fallthrough 294 | case "AIRB": fallthrough 295 | case "AIRH": return true 296 | default: return false 297 | } 298 | } 299 | 300 | // Rank higher popoluation counts higher 301 | static func populationToRank(_ population: UInt32) -> Float { 302 | if population <= 0 { 303 | return 0 304 | } 305 | let a: Float = 1.0 306 | let t: Float = -1.0/50000 307 | let b: Float = 25.0 308 | let e: Float = 2.7182818284590452353602874 309 | let rank = a / (1 + b * powf(e, t * Float(population))) 310 | return rank 311 | } 312 | } 313 | 314 | /** 315 | Helper to quickly index large amounts of duplicate strings 316 | */ 317 | struct DeduplicatedStrings { 318 | var strings = [String]() 319 | var positions = [Int: T]() 320 | 321 | mutating func findOrAppend(_ element: UnsafeRawBufferPointer) -> T { 322 | if let index = positions[element.hashValue] { 323 | return index 324 | } 325 | strings.append(element.string) 326 | positions[element.hashValue] = T(strings.endIndex - 1) 327 | return T(strings.endIndex - 1) 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /Sources/App/PointerExtensions.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | 4 | extension Data { 5 | func forEachLine(_ fn: (UnsafeRawBufferPointer) -> ()) { 6 | var start = startIndex 7 | let nl = Character("\n").asciiValue! 8 | withUnsafeBytes { dataPtr in 9 | for i in dataPtr.indices { 10 | if self[i] == nl { 11 | fn(UnsafeRawBufferPointer(rebasing: dataPtr[start.. UnsafeRawBufferPointer { 28 | for i in offset ..< endIndex { 29 | if self[i] == value { 30 | let ptr = UnsafeRawBufferPointer(rebasing: self[offset ..< i]) 31 | offset = i+1 32 | return ptr 33 | } 34 | } 35 | fatalError() 36 | } 37 | 38 | func extendUntil(_ other: UnsafeRawBufferPointer) -> UnsafeRawBufferPointer { 39 | let end = other.baseAddress!.advanced(by: other.count) 40 | let count = self.baseAddress!.distance(to: end) 41 | return UnsafeRawBufferPointer(start: self.baseAddress, count: count) 42 | } 43 | 44 | var asciiToInt32: Int32 { 45 | let ascii0 = Character("0").asciiValue! 46 | var ret: Int32 = 0; 47 | for val in self { 48 | if val == 45 { 49 | ret = ret * -1 50 | } else { 51 | ret = ret * 10 + Int32(val - ascii0) 52 | } 53 | } 54 | return ret 55 | } 56 | 57 | var asciiToUInt32: UInt32 { 58 | let ascii0 = Character("0").asciiValue! 59 | var ret: UInt32 = 0; 60 | for val in self { 61 | if val == 45 { 62 | return 0 63 | } else { 64 | ret = ret * 10 + UInt32(val - ascii0) 65 | } 66 | } 67 | return ret 68 | } 69 | 70 | var asciiToInt16: Int16 { 71 | let ascii0 = Character("0").asciiValue! 72 | var ret: Int16 = 0; 73 | for val in self { 74 | if val == 45 { 75 | ret = ret * -1 76 | } else { 77 | ret = ret * 10 + Int16(val - ascii0) 78 | } 79 | } 80 | return ret 81 | } 82 | 83 | var asciiToInt8: Int8 { 84 | let ascii0 = Character("0").asciiValue! 85 | var ret: Int8 = 0; 86 | if self.count > 2 { 87 | print(self.string) 88 | } 89 | for val in self { 90 | if val == 45 { 91 | ret = ret * -1 92 | } else { 93 | ret = ret * 10 + Int8(val - ascii0) 94 | } 95 | } 96 | return ret 97 | } 98 | 99 | /*var asciiToInt: Int64 { 100 | let ascii0 = Character("0").asciiValue! 101 | var ret: Int64 = 0; 102 | for val in self { 103 | if val == 45 { 104 | ret = ret * -1 105 | } else { 106 | ret = ret * 10 + Int64(val - ascii0) 107 | } 108 | } 109 | return ret 110 | }*/ 111 | 112 | var float: Float { 113 | return Float(string) ?? .nan 114 | } 115 | 116 | var string: String { 117 | if isEmpty { 118 | return "" 119 | } 120 | /// Note: Although it says `bytesNoCopy` it will always copy data. This is nicest way to convert a pointer with a fixed length to a string 121 | guard let base = self.baseAddress, let s = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: base), length: count, encoding: .utf8, freeWhenDone: false) else { 122 | fatalError("String could not be converted") 123 | } 124 | return s 125 | } 126 | } 127 | 128 | extension Array { 129 | /// Create a unique array of a mapped result 130 | func unique(of fn: (Element) -> T) -> [T] { 131 | var mapped = self.map(fn) 132 | mapped.sort() 133 | 134 | guard var previous = mapped.first else { 135 | return [] 136 | } 137 | var count = 1 138 | for value in mapped { 139 | if value != previous { 140 | count += 1 141 | previous = value 142 | } 143 | } 144 | 145 | var result = [T]() 146 | result.reserveCapacity(count) 147 | guard var previous = mapped.first else { 148 | return [] 149 | } 150 | result.append(previous) 151 | for value in mapped { 152 | if value != previous { 153 | result.append(value) 154 | previous = value 155 | } 156 | } 157 | assert(count == result.count) 158 | return result 159 | 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /Sources/App/PostalCodes.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | 4 | 5 | struct PostalCodes { 6 | /** 7 | country code : iso country code, 2 characters 8 | postal code : varchar(20) 9 | place name : varchar(180) 10 | admin name1 : 1. order subdivision (state) varchar(100) 11 | admin code1 : 1. order subdivision (state) varchar(20) 12 | admin name2 : 2. order subdivision (county/province) varchar(100) 13 | admin code2 : 2. order subdivision (county/province) varchar(20) 14 | admin name3 : 3. order subdivision (community) varchar(100) 15 | admin code3 : 3. order subdivision (community) varchar(20) 16 | latitude : estimated latitude (wgs84) 17 | longitude : estimated longitude (wgs84) 18 | accuracy : accuracy of lat/lng from 1=estimated, 4=geonameid, 6=centroid of addresses or shape 19 | */ 20 | public init(data: Data, logger: Logger) { 21 | let start = Date() 22 | logger.info("Postal codes: Start loading") 23 | //let tab = Character("\t").asciiValue! 24 | 25 | data.forEachLine { line in 26 | if line.isEmpty { 27 | return 28 | } 29 | // TODO need implemtation 30 | /*var offset = 0 31 | 32 | let countryCode = line.seekUntil(value: tab, offset: &offset) 33 | let postalCode = line.seekUntil(value: tab, offset: &offset).string 34 | let placeName = line.seekUntil(value: tab, offset: &offset) 35 | let _ = line.seekUntil(value: tab, offset: &offset) // adminName1 36 | let _ = line.seekUntil(value: tab, offset: &offset) // adminCode1 37 | let _ = line.seekUntil(value: tab, offset: &offset) // adminName2 38 | let _ = line.seekUntil(value: tab, offset: &offset) // adminCode2 39 | let _ = line.seekUntil(value: tab, offset: &offset) // adminName3 40 | let _ = line.seekUntil(value: tab, offset: &offset) // adminCode3 41 | let latitude = line.seekUntil(value: tab, offset: &offset).float 42 | let longitude = line.seekUntil(value: tab, offset: &offset).float 43 | let accuracy = line.seekUntil(value: tab, offset: &offset)*/ 44 | } 45 | 46 | logger.info("Postal codes: Finished loading in \(Date().timeIntervalSince(start)) seconds") 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Sources/App/Protobuf+Vapor.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | import SwiftProtobuf 4 | 5 | 6 | enum ProtobufSerializationFormat: String, Codable { 7 | case json 8 | case protobuf 9 | } 10 | 11 | extension Message { 12 | /// Encode a protobuf message to a vapor response given a format 13 | func encode(format: ProtobufSerializationFormat?) throws -> Response { 14 | let start = Date() 15 | let response = Response() 16 | switch format ?? .json { 17 | case .json: 18 | var o = JSONEncodingOptions() 19 | o.preserveProtoFieldNames = true 20 | response.body = Response.Body(data: try self.jsonUTF8Data(options: o)) 21 | response.headers.contentType = .json 22 | case .protobuf: 23 | response.body = Response.Body(data: try self.serializedData()) 24 | response.headers.contentType = .init(type: "application", subType: "x-protobuf") 25 | } 26 | response.headers.add(name: "X-Encoding-Time", value: "\(Date().timeIntervalSince(start) * 100) ms") 27 | return response 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Sources/App/QuadTree.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Vapor 3 | 4 | 5 | protocol QuadTreeElement { 6 | var latitude: Float {get} 7 | var longitude: Float {get} 8 | } 9 | 10 | extension QuadTreeElement { 11 | /// Aproximated distance 12 | @inlinable func distanceKilometers(latitude: Float, longitude: Float) -> Float { 13 | return sqrt(powf(self.latitude - latitude, 2) + powf(self.longitude - longitude, 2)) / 360 * 40030 14 | } 15 | } 16 | 17 | extension GeocodingDatabase.Geoname: QuadTreeElement {} 18 | 19 | /** 20 | Order all points in tiles of latitude and longitudes 21 | */ 22 | extension GeocodingDatabase.GeoTree { 23 | public init(elements: [Int32: T], depth: Int? = nil, logger: Logger? = nil) { 24 | let maxDepth = depth ?? Int(log2f(Float(elements.count / 2000)) / log2f(2)) 25 | 26 | var ordered: [Int32] = elements.map{$0.0} 27 | /// Store the left hand side value of each tile 28 | var values = [Float]() 29 | let totalTiles = (0.. Int { 61 | var sum = 0 62 | for z in 0..<1000 { 63 | sum += Int(pow(2, Double(z))) 64 | if sum * 2 == values.count { 65 | return z+1 66 | } 67 | } 68 | fatalError() 69 | } 70 | 71 | public func knn(latitude: Float, longitude: Float, count: Int, maxDistanceKilometer: Float, elements: [Int32: T]) -> [(id: Int32, distance: Float)] { 72 | 73 | let deltaLat = (maxDistanceKilometer / (6371 * .pi * 2)) * 360 74 | let deltaLon = asin(sin(maxDistanceKilometer / 6371) / cos(latitude.degreeToRadians)).radiansToDegree 75 | 76 | let queue = DistanceQueue(length: count) 77 | let searchLatitudeRange = latitude - deltaLat ... latitude + deltaLat 78 | let searchLongitudeRange = longitude - deltaLon ... longitude + deltaLon 79 | let maxDepth = maxDepth() 80 | //print("maxDepth=\(maxDepth), searchLatitudeRange=\(searchLatitudeRange), searchLongitudeRange=\(searchLongitudeRange)") 81 | 82 | let tilesPerDepth = (0.. 1 else { 101 | //print("search finished") 102 | break 103 | } 104 | //print("go up again, because end reached") 105 | tileIndex = indexAtDepth[z-1] 106 | z = z-1 107 | continue 108 | } 109 | 110 | // mark this tile as searched 111 | indexAtDepth[z] = tileIndex + 1 112 | 113 | let valueOffset = valuesOffsets[z] + tileIndex * 2 114 | let valueRange = values[valueOffset] ... values[valueOffset+1] 115 | let doLatitude = z % 2 == 0 116 | 117 | //print("z=\(z) tileIndex=\(tileIndex) doLatitude=\(doLatitude) valueOffset=\(valueOffset) valueRange=\(valueRange)") 118 | 119 | // check if value range matches 120 | if valueRange.overlaps(doLatitude ? searchLatitudeRange : searchLongitudeRange) { 121 | if z != maxDepth - 1 { 122 | //print("matched, going down") 123 | // go down 124 | z = z+1 125 | tileIndex = tileIndex * 2 126 | checkedLeftHalf[z] = false 127 | continue 128 | } 129 | // perform search 130 | let pointsPerTile = ordered.count.divideCeiled(by: tilesPerDepth[z]) 131 | let range = pointsPerTile * tileIndex ..< min(pointsPerTile * (tileIndex+1), ordered.count) 132 | //print("matched, adding values, range=\(range)") 133 | for i in ordered[range] { 134 | let distance = elements[i]!.distanceKilometers(latitude: latitude, longitude: longitude) 135 | guard distance <= maxDistanceKilometer else { 136 | continue 137 | } 138 | queue.insert(id: i, priority: distance) 139 | } 140 | } 141 | 142 | if checkedLeftHalf[z] { 143 | // go up 144 | //print("go up again") 145 | tileIndex = indexAtDepth[z-1] 146 | z = z-1 147 | } else { 148 | // check right half 149 | //print("check right half") 150 | checkedLeftHalf[z] = true 151 | tileIndex += 1 152 | } 153 | } 154 | return queue.queue 155 | } 156 | } 157 | 158 | extension Float { 159 | @inlinable var radiansToDegree: Float { 160 | return self * 180 / .pi 161 | } 162 | @inlinable var degreeToRadians: Float { 163 | return self / 180 * .pi 164 | } 165 | } 166 | 167 | public final class DistanceQueue { 168 | public var queue: [(id: Int32, distance: Float)] 169 | 170 | public init(length: Int) { 171 | queue = [(Int32, Float)](repeating: (0, 1000000000), count: length) 172 | } 173 | 174 | public func insert(id: Int32, priority: Float) { 175 | guard let pos = queue.firstIndex(where: { 176 | if $0.distance == priority { 177 | return $0.id < id 178 | } 179 | return $0.distance >= priority 180 | }) else { 181 | return 182 | } 183 | if pos < queue.count - 1 { 184 | queue[pos+1.. Int{ 192 | let div = self / divisor 193 | let remainig = self % divisor 194 | return remainig == 0 ? div : div + 1 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /Sources/App/Structures.swift: -------------------------------------------------------------------------------- 1 | /** 2 | boot: 3 | - read geoname & alternate txt file 4 | - do we need a preprocess step?? sqlite? just use sql lite fulltext search? 5 | - initialse id hash table 6 | - initilaise search tree (transfer special chacters like å to a, ß to s. Preverse spaces for "New york"... index fuzzy with "New yrk"? 7 | 8 | multi pass: 9 | - first load countries, then admin1, then admin2, admin3? 10 | */ 11 | 12 | import Foundation 13 | import Vapor 14 | 15 | 16 | extension GeocodingDatabase.SearchTree { 17 | public func search(_ search: Substring, results: PriorityQueue, onlyExact: Bool = false, factor: Float = 1.5, geonames: [Int32: GeocodingDatabase.Geoname]) { 18 | guard let next = search.first else { 19 | /// search string finished, append everything afterwards 20 | for id in ids { 21 | results.insert(id: id, priority: factor + geonames[id]!.ranking) 22 | } 23 | if onlyExact { 24 | return 25 | } 26 | for b in buffer { 27 | results.insert(id: b.id, priority: factor / Float(b.remaining.count + 1) + geonames[b.id]!.ranking) 28 | } 29 | for b in branches { 30 | b.value.search(search, results: results, onlyExact: onlyExact, factor: factor / 2, geonames: geonames) 31 | } 32 | return 33 | } 34 | for b in buffer { 35 | if b.remaining == search { 36 | results.insert(id: b.id, priority: factor + geonames[b.id]!.ranking) 37 | continue 38 | } 39 | if onlyExact { 40 | continue 41 | } 42 | if b.remaining.starts(with: search) { 43 | results.insert(id: b.id, priority: factor / Float(b.remaining.count + 1) + geonames[b.id]!.ranking) 44 | } 45 | } 46 | branches[String(next)]?.search(search.dropFirst(), results: results, onlyExact: onlyExact, geonames: geonames) 47 | } 48 | } 49 | 50 | /** 51 | Similar to SearchTree, but mutable. While creating the database, it is used to add entries 52 | */ 53 | final class SearchTreeLoader { 54 | /// fully matching IDs 55 | var ids = [Int32]() 56 | 57 | var branches = [String: SearchTreeLoader]() 58 | 59 | /// keep up to 4096 entries before node split 60 | var buffer = [GeocodingDatabase.PartialName]() 61 | 62 | public func add(_ str: String, id: Int32) { 63 | let stripped = str.folding(options: .diacriticInsensitive, locale: nil).lowercased() 64 | self.addInternal(Substring(stripped), id: id) 65 | } 66 | 67 | private func addInternal(_ str: Substring, id: Int32) { 68 | guard let charOrg = str.first else { 69 | if !ids.contains(id) { 70 | ids.append(id) 71 | } 72 | return 73 | } 74 | let char = String(charOrg) 75 | if branches.isEmpty { 76 | var p = GeocodingDatabase.PartialName() 77 | p.remaining = String(str) 78 | p.id = id 79 | buffer.append(p) 80 | if buffer.count >= 4096 { 81 | for e in buffer { 82 | let char = String(e.remaining.first!) 83 | if branches[char] == nil { 84 | branches[char] = Self.init() 85 | } 86 | branches[char]?.addInternal(e.remaining.dropFirst(), id: e.id) 87 | } 88 | buffer.removeAll() 89 | } 90 | return 91 | } 92 | if branches[char] == nil { 93 | branches[char] = Self.init() 94 | } 95 | branches[char]?.addInternal(str.dropFirst(), id: id) 96 | } 97 | 98 | /// Convert to immutable SearchTree structure 99 | public func immutable() -> GeocodingDatabase.SearchTree { 100 | var s = GeocodingDatabase.SearchTree() 101 | s.branches = branches.mapValues({$0.immutable()}) 102 | s.ids = ids 103 | s.buffer = buffer 104 | return s 105 | } 106 | } 107 | 108 | 109 | /// Order search results by priority 110 | public final class PriorityQueue { 111 | public var queue: [(id: Int32, priority: Float)] 112 | 113 | public init(length: Int) { 114 | queue = [(Int32, Float)](repeating: (0, 0), count: length) 115 | } 116 | 117 | public func insert(id: Int32, priority: Float) { 118 | // if duplicate id, remove it and then insert like regular 119 | if let duplicate = queue.firstIndex(where: {$0.id == id}) { 120 | if queue[duplicate].priority >= priority { 121 | return 122 | } 123 | if duplicate < queue.count-1 { 124 | // remove it from queue 125 | queue[duplicate.. id 131 | } 132 | return $0.priority <= priority 133 | }) else { 134 | return 135 | } 136 | if pos < queue.count - 1 { 137 | queue[pos+1.. alternativeNames = 16; 150 | var postcodes: [String] { 151 | get {return _storage._postcodes} 152 | set {_uniqueStorage()._postcodes = newValue} 153 | } 154 | 155 | var unknownFields = SwiftProtobuf.UnknownStorage() 156 | 157 | init() {} 158 | 159 | fileprivate var _storage = _StorageClass.defaultInstance 160 | } 161 | 162 | init() {} 163 | } 164 | 165 | // MARK: - Code below here is support for the SwiftProtobuf runtime. 166 | 167 | extension GeocodingApi: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 168 | static let protoMessageName: String = "GeocodingApi" 169 | static let _protobuf_nameMap = SwiftProtobuf._NameMap() 170 | 171 | mutating func decodeMessage(decoder: inout D) throws { 172 | while let _ = try decoder.nextFieldNumber() { 173 | } 174 | } 175 | 176 | func traverse(visitor: inout V) throws { 177 | try unknownFields.traverse(visitor: &visitor) 178 | } 179 | 180 | static func ==(lhs: GeocodingApi, rhs: GeocodingApi) -> Bool { 181 | if lhs.unknownFields != rhs.unknownFields {return false} 182 | return true 183 | } 184 | } 185 | 186 | extension GeocodingApi.SearchResults: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 187 | static let protoMessageName: String = GeocodingApi.protoMessageName + ".SearchResults" 188 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 189 | 1: .same(proto: "results"), 190 | 2: .standard(proto: "generationtime_ms"), 191 | ] 192 | 193 | mutating func decodeMessage(decoder: inout D) throws { 194 | while let fieldNumber = try decoder.nextFieldNumber() { 195 | // The use of inline closures is to circumvent an issue where the compiler 196 | // allocates stack space for every case branch when no optimizations are 197 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 198 | switch fieldNumber { 199 | case 1: try { try decoder.decodeRepeatedMessageField(value: &self.results) }() 200 | case 2: try { try decoder.decodeSingularFloatField(value: &self.generationtimeMs) }() 201 | default: break 202 | } 203 | } 204 | } 205 | 206 | func traverse(visitor: inout V) throws { 207 | if !self.results.isEmpty { 208 | try visitor.visitRepeatedMessageField(value: self.results, fieldNumber: 1) 209 | } 210 | if self.generationtimeMs != 0 { 211 | try visitor.visitSingularFloatField(value: self.generationtimeMs, fieldNumber: 2) 212 | } 213 | try unknownFields.traverse(visitor: &visitor) 214 | } 215 | 216 | static func ==(lhs: GeocodingApi.SearchResults, rhs: GeocodingApi.SearchResults) -> Bool { 217 | if lhs.results != rhs.results {return false} 218 | if lhs.generationtimeMs != rhs.generationtimeMs {return false} 219 | if lhs.unknownFields != rhs.unknownFields {return false} 220 | return true 221 | } 222 | } 223 | 224 | extension GeocodingApi.Geoname: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 225 | static let protoMessageName: String = GeocodingApi.protoMessageName + ".Geoname" 226 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 227 | 1: .same(proto: "id"), 228 | 2: .same(proto: "name"), 229 | 4: .same(proto: "latitude"), 230 | 5: .same(proto: "longitude"), 231 | 6: .same(proto: "ranking"), 232 | 7: .same(proto: "elevation"), 233 | 8: .standard(proto: "feature_code"), 234 | 9: .standard(proto: "country_code"), 235 | 18: .standard(proto: "country_id"), 236 | 19: .same(proto: "country"), 237 | 10: .standard(proto: "admin1_id"), 238 | 11: .standard(proto: "admin2_id"), 239 | 12: .standard(proto: "admin3_id"), 240 | 13: .standard(proto: "admin4_id"), 241 | 20: .same(proto: "admin1"), 242 | 21: .same(proto: "admin2"), 243 | 22: .same(proto: "admin3"), 244 | 23: .same(proto: "admin4"), 245 | 14: .same(proto: "timezone"), 246 | 15: .same(proto: "population"), 247 | 17: .same(proto: "postcodes"), 248 | ] 249 | 250 | fileprivate class _StorageClass { 251 | var _id: Int32 = 0 252 | var _name: String = String() 253 | var _latitude: Float = 0 254 | var _longitude: Float = 0 255 | var _ranking: Float = 0 256 | var _elevation: Float = 0 257 | var _featureCode: String = String() 258 | var _countryCode: String = String() 259 | var _countryID: Int32 = 0 260 | var _country: String = String() 261 | var _admin1ID: Int32 = 0 262 | var _admin2ID: Int32 = 0 263 | var _admin3ID: Int32 = 0 264 | var _admin4ID: Int32 = 0 265 | var _admin1: String = String() 266 | var _admin2: String = String() 267 | var _admin3: String = String() 268 | var _admin4: String = String() 269 | var _timezone: String = String() 270 | var _population: UInt32 = 0 271 | var _postcodes: [String] = [] 272 | 273 | static let defaultInstance = _StorageClass() 274 | 275 | private init() {} 276 | 277 | init(copying source: _StorageClass) { 278 | _id = source._id 279 | _name = source._name 280 | _latitude = source._latitude 281 | _longitude = source._longitude 282 | _ranking = source._ranking 283 | _elevation = source._elevation 284 | _featureCode = source._featureCode 285 | _countryCode = source._countryCode 286 | _countryID = source._countryID 287 | _country = source._country 288 | _admin1ID = source._admin1ID 289 | _admin2ID = source._admin2ID 290 | _admin3ID = source._admin3ID 291 | _admin4ID = source._admin4ID 292 | _admin1 = source._admin1 293 | _admin2 = source._admin2 294 | _admin3 = source._admin3 295 | _admin4 = source._admin4 296 | _timezone = source._timezone 297 | _population = source._population 298 | _postcodes = source._postcodes 299 | } 300 | } 301 | 302 | fileprivate mutating func _uniqueStorage() -> _StorageClass { 303 | if !isKnownUniquelyReferenced(&_storage) { 304 | _storage = _StorageClass(copying: _storage) 305 | } 306 | return _storage 307 | } 308 | 309 | mutating func decodeMessage(decoder: inout D) throws { 310 | _ = _uniqueStorage() 311 | try withExtendedLifetime(_storage) { (_storage: _StorageClass) in 312 | while let fieldNumber = try decoder.nextFieldNumber() { 313 | // The use of inline closures is to circumvent an issue where the compiler 314 | // allocates stack space for every case branch when no optimizations are 315 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 316 | switch fieldNumber { 317 | case 1: try { try decoder.decodeSingularInt32Field(value: &_storage._id) }() 318 | case 2: try { try decoder.decodeSingularStringField(value: &_storage._name) }() 319 | case 4: try { try decoder.decodeSingularFloatField(value: &_storage._latitude) }() 320 | case 5: try { try decoder.decodeSingularFloatField(value: &_storage._longitude) }() 321 | case 6: try { try decoder.decodeSingularFloatField(value: &_storage._ranking) }() 322 | case 7: try { try decoder.decodeSingularFloatField(value: &_storage._elevation) }() 323 | case 8: try { try decoder.decodeSingularStringField(value: &_storage._featureCode) }() 324 | case 9: try { try decoder.decodeSingularStringField(value: &_storage._countryCode) }() 325 | case 10: try { try decoder.decodeSingularInt32Field(value: &_storage._admin1ID) }() 326 | case 11: try { try decoder.decodeSingularInt32Field(value: &_storage._admin2ID) }() 327 | case 12: try { try decoder.decodeSingularInt32Field(value: &_storage._admin3ID) }() 328 | case 13: try { try decoder.decodeSingularInt32Field(value: &_storage._admin4ID) }() 329 | case 14: try { try decoder.decodeSingularStringField(value: &_storage._timezone) }() 330 | case 15: try { try decoder.decodeSingularUInt32Field(value: &_storage._population) }() 331 | case 17: try { try decoder.decodeRepeatedStringField(value: &_storage._postcodes) }() 332 | case 18: try { try decoder.decodeSingularInt32Field(value: &_storage._countryID) }() 333 | case 19: try { try decoder.decodeSingularStringField(value: &_storage._country) }() 334 | case 20: try { try decoder.decodeSingularStringField(value: &_storage._admin1) }() 335 | case 21: try { try decoder.decodeSingularStringField(value: &_storage._admin2) }() 336 | case 22: try { try decoder.decodeSingularStringField(value: &_storage._admin3) }() 337 | case 23: try { try decoder.decodeSingularStringField(value: &_storage._admin4) }() 338 | default: break 339 | } 340 | } 341 | } 342 | } 343 | 344 | func traverse(visitor: inout V) throws { 345 | try withExtendedLifetime(_storage) { (_storage: _StorageClass) in 346 | if _storage._id != 0 { 347 | try visitor.visitSingularInt32Field(value: _storage._id, fieldNumber: 1) 348 | } 349 | if !_storage._name.isEmpty { 350 | try visitor.visitSingularStringField(value: _storage._name, fieldNumber: 2) 351 | } 352 | if _storage._latitude != 0 { 353 | try visitor.visitSingularFloatField(value: _storage._latitude, fieldNumber: 4) 354 | } 355 | if _storage._longitude != 0 { 356 | try visitor.visitSingularFloatField(value: _storage._longitude, fieldNumber: 5) 357 | } 358 | if _storage._ranking != 0 { 359 | try visitor.visitSingularFloatField(value: _storage._ranking, fieldNumber: 6) 360 | } 361 | if _storage._elevation != 0 { 362 | try visitor.visitSingularFloatField(value: _storage._elevation, fieldNumber: 7) 363 | } 364 | if !_storage._featureCode.isEmpty { 365 | try visitor.visitSingularStringField(value: _storage._featureCode, fieldNumber: 8) 366 | } 367 | if !_storage._countryCode.isEmpty { 368 | try visitor.visitSingularStringField(value: _storage._countryCode, fieldNumber: 9) 369 | } 370 | if _storage._admin1ID != 0 { 371 | try visitor.visitSingularInt32Field(value: _storage._admin1ID, fieldNumber: 10) 372 | } 373 | if _storage._admin2ID != 0 { 374 | try visitor.visitSingularInt32Field(value: _storage._admin2ID, fieldNumber: 11) 375 | } 376 | if _storage._admin3ID != 0 { 377 | try visitor.visitSingularInt32Field(value: _storage._admin3ID, fieldNumber: 12) 378 | } 379 | if _storage._admin4ID != 0 { 380 | try visitor.visitSingularInt32Field(value: _storage._admin4ID, fieldNumber: 13) 381 | } 382 | if !_storage._timezone.isEmpty { 383 | try visitor.visitSingularStringField(value: _storage._timezone, fieldNumber: 14) 384 | } 385 | if _storage._population != 0 { 386 | try visitor.visitSingularUInt32Field(value: _storage._population, fieldNumber: 15) 387 | } 388 | if !_storage._postcodes.isEmpty { 389 | try visitor.visitRepeatedStringField(value: _storage._postcodes, fieldNumber: 17) 390 | } 391 | if _storage._countryID != 0 { 392 | try visitor.visitSingularInt32Field(value: _storage._countryID, fieldNumber: 18) 393 | } 394 | if !_storage._country.isEmpty { 395 | try visitor.visitSingularStringField(value: _storage._country, fieldNumber: 19) 396 | } 397 | if !_storage._admin1.isEmpty { 398 | try visitor.visitSingularStringField(value: _storage._admin1, fieldNumber: 20) 399 | } 400 | if !_storage._admin2.isEmpty { 401 | try visitor.visitSingularStringField(value: _storage._admin2, fieldNumber: 21) 402 | } 403 | if !_storage._admin3.isEmpty { 404 | try visitor.visitSingularStringField(value: _storage._admin3, fieldNumber: 22) 405 | } 406 | if !_storage._admin4.isEmpty { 407 | try visitor.visitSingularStringField(value: _storage._admin4, fieldNumber: 23) 408 | } 409 | } 410 | try unknownFields.traverse(visitor: &visitor) 411 | } 412 | 413 | static func ==(lhs: GeocodingApi.Geoname, rhs: GeocodingApi.Geoname) -> Bool { 414 | if lhs._storage !== rhs._storage { 415 | let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in 416 | let _storage = _args.0 417 | let rhs_storage = _args.1 418 | if _storage._id != rhs_storage._id {return false} 419 | if _storage._name != rhs_storage._name {return false} 420 | if _storage._latitude != rhs_storage._latitude {return false} 421 | if _storage._longitude != rhs_storage._longitude {return false} 422 | if _storage._ranking != rhs_storage._ranking {return false} 423 | if _storage._elevation != rhs_storage._elevation {return false} 424 | if _storage._featureCode != rhs_storage._featureCode {return false} 425 | if _storage._countryCode != rhs_storage._countryCode {return false} 426 | if _storage._countryID != rhs_storage._countryID {return false} 427 | if _storage._country != rhs_storage._country {return false} 428 | if _storage._admin1ID != rhs_storage._admin1ID {return false} 429 | if _storage._admin2ID != rhs_storage._admin2ID {return false} 430 | if _storage._admin3ID != rhs_storage._admin3ID {return false} 431 | if _storage._admin4ID != rhs_storage._admin4ID {return false} 432 | if _storage._admin1 != rhs_storage._admin1 {return false} 433 | if _storage._admin2 != rhs_storage._admin2 {return false} 434 | if _storage._admin3 != rhs_storage._admin3 {return false} 435 | if _storage._admin4 != rhs_storage._admin4 {return false} 436 | if _storage._timezone != rhs_storage._timezone {return false} 437 | if _storage._population != rhs_storage._population {return false} 438 | if _storage._postcodes != rhs_storage._postcodes {return false} 439 | return true 440 | } 441 | if !storagesAreEqual {return false} 442 | } 443 | if lhs.unknownFields != rhs.unknownFields {return false} 444 | return true 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /Sources/App/api.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | message GeocodingApi { 4 | message SearchResults { 5 | repeated Geoname results = 1; 6 | float generationtime_ms = 2; 7 | } 8 | 9 | message Geoname { 10 | int32 id = 1; 11 | string name = 2; 12 | float latitude = 4; 13 | float longitude = 5; 14 | float ranking = 6; 15 | float elevation = 7; 16 | string feature_code = 8; 17 | string country_code = 9; 18 | int32 country_id = 18; 19 | string country = 19; 20 | int32 admin1_id = 10; 21 | int32 admin2_id = 11; 22 | int32 admin3_id = 12; 23 | int32 admin4_id = 13; 24 | string admin1 = 20; 25 | string admin2 = 21; 26 | string admin3 = 22; 27 | string admin4 = 23; 28 | string timezone = 14; 29 | uint32 population = 15; 30 | //map alternativeNames = 16; 31 | repeated string postcodes = 17; 32 | } 33 | } -------------------------------------------------------------------------------- /Sources/App/configure.swift: -------------------------------------------------------------------------------- 1 | import Vapor 2 | 3 | 4 | public func configure(_ app: Application) throws { 5 | TimeZone.ReferenceType.default = TimeZone(abbreviation: "GMT")! 6 | 7 | app.http.server.configuration.responseCompression = .enabled 8 | // https://github.com/vapor/vapor/pull/2677 9 | app.http.server.configuration.supportPipelining = false 10 | 11 | #if Xcode 12 | app.logger.logLevel = .debug 13 | app.http.server.configuration.port = 8912 14 | #endif 15 | 16 | try routes(app) 17 | } 18 | 19 | func routes(_ app: Application) throws { 20 | try app.routes.register(collection: try GeocodingapiController(app)) 21 | } 22 | -------------------------------------------------------------------------------- /Sources/App/database.pb.swift: -------------------------------------------------------------------------------- 1 | // DO NOT EDIT. 2 | // swift-format-ignore-file 3 | // 4 | // Generated by the Swift generator plugin for the protocol buffer compiler. 5 | // Source: database.proto 6 | // 7 | // For information on using the generated types, please see the documentation: 8 | // https://github.com/apple/swift-protobuf/ 9 | 10 | import Foundation 11 | import SwiftProtobuf 12 | 13 | // If the compiler emits an error on this type, it is because this file 14 | // was generated by a version of the `protoc` Swift plug-in that is 15 | // incompatible with the version of SwiftProtobuf to which you are linking. 16 | // Please ensure that you are building against the same version of the API 17 | // that was used to generate this file. 18 | fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { 19 | struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} 20 | typealias Version = _2 21 | } 22 | 23 | struct GeocodingDatabase { 24 | // SwiftProtobuf.Message conformance is added in an extension below. See the 25 | // `Message` and `Message+*Additions` files in the SwiftProtobuf library for 26 | // methods supported on all messages. 27 | 28 | var geonames: GeocodingDatabase.Geonames { 29 | get {return _geonames ?? GeocodingDatabase.Geonames()} 30 | set {_geonames = newValue} 31 | } 32 | /// Returns true if `geonames` has been explicitly set. 33 | var hasGeonames: Bool {return self._geonames != nil} 34 | /// Clears the value of `geonames`. Subsequent reads from it will return its default value. 35 | mutating func clearGeonames() {self._geonames = nil} 36 | 37 | var index: GeocodingDatabase.SearchTree { 38 | get {return _index ?? GeocodingDatabase.SearchTree()} 39 | set {_index = newValue} 40 | } 41 | /// Returns true if `index` has been explicitly set. 42 | var hasIndex: Bool {return self._index != nil} 43 | /// Clears the value of `index`. Subsequent reads from it will return its default value. 44 | mutating func clearIndex() {self._index = nil} 45 | 46 | var languageIndex: [GeocodingDatabase.SearchTree] = [] 47 | 48 | var geotree: GeocodingDatabase.GeoTree { 49 | get {return _geotree ?? GeocodingDatabase.GeoTree()} 50 | set {_geotree = newValue} 51 | } 52 | /// Returns true if `geotree` has been explicitly set. 53 | var hasGeotree: Bool {return self._geotree != nil} 54 | /// Clears the value of `geotree`. Subsequent reads from it will return its default value. 55 | mutating func clearGeotree() {self._geotree = nil} 56 | 57 | var unknownFields = SwiftProtobuf.UnknownStorage() 58 | 59 | struct Geoname { 60 | // SwiftProtobuf.Message conformance is added in an extension below. See the 61 | // `Message` and `Message+*Additions` files in the SwiftProtobuf library for 62 | // methods supported on all messages. 63 | 64 | var id: Int32 { 65 | get {return _storage._id} 66 | set {_uniqueStorage()._id = newValue} 67 | } 68 | 69 | var name: String { 70 | get {return _storage._name} 71 | set {_uniqueStorage()._name = newValue} 72 | } 73 | 74 | var latitude: Float { 75 | get {return _storage._latitude} 76 | set {_uniqueStorage()._latitude = newValue} 77 | } 78 | 79 | var longitude: Float { 80 | get {return _storage._longitude} 81 | set {_uniqueStorage()._longitude = newValue} 82 | } 83 | 84 | var ranking: Float { 85 | get {return _storage._ranking} 86 | set {_uniqueStorage()._ranking = newValue} 87 | } 88 | 89 | var elevation: Float { 90 | get {return _storage._elevation} 91 | set {_uniqueStorage()._elevation = newValue} 92 | } 93 | 94 | var featureCode: String { 95 | get {return _storage._featureCode} 96 | set {_uniqueStorage()._featureCode = newValue} 97 | } 98 | 99 | var countryIso2: String { 100 | get {return _storage._countryIso2} 101 | set {_uniqueStorage()._countryIso2 = newValue} 102 | } 103 | 104 | var countryID: Int32 { 105 | get {return _storage._countryID} 106 | set {_uniqueStorage()._countryID = newValue} 107 | } 108 | 109 | var admin1ID: Int32 { 110 | get {return _storage._admin1ID} 111 | set {_uniqueStorage()._admin1ID = newValue} 112 | } 113 | 114 | var admin2ID: Int32 { 115 | get {return _storage._admin2ID} 116 | set {_uniqueStorage()._admin2ID = newValue} 117 | } 118 | 119 | var admin3ID: Int32 { 120 | get {return _storage._admin3ID} 121 | set {_uniqueStorage()._admin3ID = newValue} 122 | } 123 | 124 | var admin4ID: Int32 { 125 | get {return _storage._admin4ID} 126 | set {_uniqueStorage()._admin4ID = newValue} 127 | } 128 | 129 | var timezoneIndex: Int32 { 130 | get {return _storage._timezoneIndex} 131 | set {_uniqueStorage()._timezoneIndex = newValue} 132 | } 133 | 134 | var population: UInt32 { 135 | get {return _storage._population} 136 | set {_uniqueStorage()._population = newValue} 137 | } 138 | 139 | var alternativeNames: Dictionary { 140 | get {return _storage._alternativeNames} 141 | set {_uniqueStorage()._alternativeNames = newValue} 142 | } 143 | 144 | var postcodes: [String] { 145 | get {return _storage._postcodes} 146 | set {_uniqueStorage()._postcodes = newValue} 147 | } 148 | 149 | var unknownFields = SwiftProtobuf.UnknownStorage() 150 | 151 | init() {} 152 | 153 | fileprivate var _storage = _StorageClass.defaultInstance 154 | } 155 | 156 | struct Geonames { 157 | // SwiftProtobuf.Message conformance is added in an extension below. See the 158 | // `Message` and `Message+*Additions` files in the SwiftProtobuf library for 159 | // methods supported on all messages. 160 | 161 | var geonames: Dictionary = [:] 162 | 163 | var timezones: [String] = [] 164 | 165 | var languages: [String] = [] 166 | 167 | var unknownFields = SwiftProtobuf.UnknownStorage() 168 | 169 | init() {} 170 | } 171 | 172 | struct GeoTree { 173 | // SwiftProtobuf.Message conformance is added in an extension below. See the 174 | // `Message` and `Message+*Additions` files in the SwiftProtobuf library for 175 | // methods supported on all messages. 176 | 177 | var ordered: [Int32] = [] 178 | 179 | var values: [Float] = [] 180 | 181 | var unknownFields = SwiftProtobuf.UnknownStorage() 182 | 183 | init() {} 184 | } 185 | 186 | struct SearchTree { 187 | // SwiftProtobuf.Message conformance is added in an extension below. See the 188 | // `Message` and `Message+*Additions` files in the SwiftProtobuf library for 189 | // methods supported on all messages. 190 | 191 | var ids: [Int32] = [] 192 | 193 | var branches: Dictionary = [:] 194 | 195 | var buffer: [GeocodingDatabase.PartialName] = [] 196 | 197 | var unknownFields = SwiftProtobuf.UnknownStorage() 198 | 199 | init() {} 200 | } 201 | 202 | struct PartialName { 203 | // SwiftProtobuf.Message conformance is added in an extension below. See the 204 | // `Message` and `Message+*Additions` files in the SwiftProtobuf library for 205 | // methods supported on all messages. 206 | 207 | var id: Int32 = 0 208 | 209 | var remaining: String = String() 210 | 211 | var unknownFields = SwiftProtobuf.UnknownStorage() 212 | 213 | init() {} 214 | } 215 | 216 | init() {} 217 | 218 | fileprivate var _geonames: GeocodingDatabase.Geonames? = nil 219 | fileprivate var _index: GeocodingDatabase.SearchTree? = nil 220 | fileprivate var _geotree: GeocodingDatabase.GeoTree? = nil 221 | } 222 | 223 | // MARK: - Code below here is support for the SwiftProtobuf runtime. 224 | 225 | extension GeocodingDatabase: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 226 | static let protoMessageName: String = "GeocodingDatabase" 227 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 228 | 1: .same(proto: "geonames"), 229 | 2: .same(proto: "index"), 230 | 3: .same(proto: "languageIndex"), 231 | 4: .same(proto: "geotree"), 232 | ] 233 | 234 | mutating func decodeMessage(decoder: inout D) throws { 235 | while let fieldNumber = try decoder.nextFieldNumber() { 236 | // The use of inline closures is to circumvent an issue where the compiler 237 | // allocates stack space for every case branch when no optimizations are 238 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 239 | switch fieldNumber { 240 | case 1: try { try decoder.decodeSingularMessageField(value: &self._geonames) }() 241 | case 2: try { try decoder.decodeSingularMessageField(value: &self._index) }() 242 | case 3: try { try decoder.decodeRepeatedMessageField(value: &self.languageIndex) }() 243 | case 4: try { try decoder.decodeSingularMessageField(value: &self._geotree) }() 244 | default: break 245 | } 246 | } 247 | } 248 | 249 | func traverse(visitor: inout V) throws { 250 | // The use of inline closures is to circumvent an issue where the compiler 251 | // allocates stack space for every if/case branch local when no optimizations 252 | // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and 253 | // https://github.com/apple/swift-protobuf/issues/1182 254 | try { if let v = self._geonames { 255 | try visitor.visitSingularMessageField(value: v, fieldNumber: 1) 256 | } }() 257 | try { if let v = self._index { 258 | try visitor.visitSingularMessageField(value: v, fieldNumber: 2) 259 | } }() 260 | if !self.languageIndex.isEmpty { 261 | try visitor.visitRepeatedMessageField(value: self.languageIndex, fieldNumber: 3) 262 | } 263 | try { if let v = self._geotree { 264 | try visitor.visitSingularMessageField(value: v, fieldNumber: 4) 265 | } }() 266 | try unknownFields.traverse(visitor: &visitor) 267 | } 268 | 269 | static func ==(lhs: GeocodingDatabase, rhs: GeocodingDatabase) -> Bool { 270 | if lhs._geonames != rhs._geonames {return false} 271 | if lhs._index != rhs._index {return false} 272 | if lhs.languageIndex != rhs.languageIndex {return false} 273 | if lhs._geotree != rhs._geotree {return false} 274 | if lhs.unknownFields != rhs.unknownFields {return false} 275 | return true 276 | } 277 | } 278 | 279 | extension GeocodingDatabase.Geoname: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 280 | static let protoMessageName: String = GeocodingDatabase.protoMessageName + ".Geoname" 281 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 282 | 1: .same(proto: "id"), 283 | 2: .same(proto: "name"), 284 | 4: .same(proto: "latitude"), 285 | 5: .same(proto: "longitude"), 286 | 6: .same(proto: "ranking"), 287 | 7: .same(proto: "elevation"), 288 | 8: .standard(proto: "feature_code"), 289 | 9: .standard(proto: "country_iso2"), 290 | 18: .standard(proto: "country_id"), 291 | 10: .standard(proto: "admin1_id"), 292 | 11: .standard(proto: "admin2_id"), 293 | 12: .standard(proto: "admin3_id"), 294 | 13: .standard(proto: "admin4_id"), 295 | 14: .standard(proto: "timezone_index"), 296 | 15: .same(proto: "population"), 297 | 16: .same(proto: "alternativeNames"), 298 | 17: .same(proto: "postcodes"), 299 | ] 300 | 301 | fileprivate class _StorageClass { 302 | var _id: Int32 = 0 303 | var _name: String = String() 304 | var _latitude: Float = 0 305 | var _longitude: Float = 0 306 | var _ranking: Float = 0 307 | var _elevation: Float = 0 308 | var _featureCode: String = String() 309 | var _countryIso2: String = String() 310 | var _countryID: Int32 = 0 311 | var _admin1ID: Int32 = 0 312 | var _admin2ID: Int32 = 0 313 | var _admin3ID: Int32 = 0 314 | var _admin4ID: Int32 = 0 315 | var _timezoneIndex: Int32 = 0 316 | var _population: UInt32 = 0 317 | var _alternativeNames: Dictionary = [:] 318 | var _postcodes: [String] = [] 319 | 320 | static let defaultInstance = _StorageClass() 321 | 322 | private init() {} 323 | 324 | init(copying source: _StorageClass) { 325 | _id = source._id 326 | _name = source._name 327 | _latitude = source._latitude 328 | _longitude = source._longitude 329 | _ranking = source._ranking 330 | _elevation = source._elevation 331 | _featureCode = source._featureCode 332 | _countryIso2 = source._countryIso2 333 | _countryID = source._countryID 334 | _admin1ID = source._admin1ID 335 | _admin2ID = source._admin2ID 336 | _admin3ID = source._admin3ID 337 | _admin4ID = source._admin4ID 338 | _timezoneIndex = source._timezoneIndex 339 | _population = source._population 340 | _alternativeNames = source._alternativeNames 341 | _postcodes = source._postcodes 342 | } 343 | } 344 | 345 | fileprivate mutating func _uniqueStorage() -> _StorageClass { 346 | if !isKnownUniquelyReferenced(&_storage) { 347 | _storage = _StorageClass(copying: _storage) 348 | } 349 | return _storage 350 | } 351 | 352 | mutating func decodeMessage(decoder: inout D) throws { 353 | _ = _uniqueStorage() 354 | try withExtendedLifetime(_storage) { (_storage: _StorageClass) in 355 | while let fieldNumber = try decoder.nextFieldNumber() { 356 | // The use of inline closures is to circumvent an issue where the compiler 357 | // allocates stack space for every case branch when no optimizations are 358 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 359 | switch fieldNumber { 360 | case 1: try { try decoder.decodeSingularInt32Field(value: &_storage._id) }() 361 | case 2: try { try decoder.decodeSingularStringField(value: &_storage._name) }() 362 | case 4: try { try decoder.decodeSingularFloatField(value: &_storage._latitude) }() 363 | case 5: try { try decoder.decodeSingularFloatField(value: &_storage._longitude) }() 364 | case 6: try { try decoder.decodeSingularFloatField(value: &_storage._ranking) }() 365 | case 7: try { try decoder.decodeSingularFloatField(value: &_storage._elevation) }() 366 | case 8: try { try decoder.decodeSingularStringField(value: &_storage._featureCode) }() 367 | case 9: try { try decoder.decodeSingularStringField(value: &_storage._countryIso2) }() 368 | case 10: try { try decoder.decodeSingularInt32Field(value: &_storage._admin1ID) }() 369 | case 11: try { try decoder.decodeSingularInt32Field(value: &_storage._admin2ID) }() 370 | case 12: try { try decoder.decodeSingularInt32Field(value: &_storage._admin3ID) }() 371 | case 13: try { try decoder.decodeSingularInt32Field(value: &_storage._admin4ID) }() 372 | case 14: try { try decoder.decodeSingularInt32Field(value: &_storage._timezoneIndex) }() 373 | case 15: try { try decoder.decodeSingularUInt32Field(value: &_storage._population) }() 374 | case 16: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &_storage._alternativeNames) }() 375 | case 17: try { try decoder.decodeRepeatedStringField(value: &_storage._postcodes) }() 376 | case 18: try { try decoder.decodeSingularInt32Field(value: &_storage._countryID) }() 377 | default: break 378 | } 379 | } 380 | } 381 | } 382 | 383 | func traverse(visitor: inout V) throws { 384 | try withExtendedLifetime(_storage) { (_storage: _StorageClass) in 385 | if _storage._id != 0 { 386 | try visitor.visitSingularInt32Field(value: _storage._id, fieldNumber: 1) 387 | } 388 | if !_storage._name.isEmpty { 389 | try visitor.visitSingularStringField(value: _storage._name, fieldNumber: 2) 390 | } 391 | if _storage._latitude != 0 { 392 | try visitor.visitSingularFloatField(value: _storage._latitude, fieldNumber: 4) 393 | } 394 | if _storage._longitude != 0 { 395 | try visitor.visitSingularFloatField(value: _storage._longitude, fieldNumber: 5) 396 | } 397 | if _storage._ranking != 0 { 398 | try visitor.visitSingularFloatField(value: _storage._ranking, fieldNumber: 6) 399 | } 400 | if _storage._elevation != 0 { 401 | try visitor.visitSingularFloatField(value: _storage._elevation, fieldNumber: 7) 402 | } 403 | if !_storage._featureCode.isEmpty { 404 | try visitor.visitSingularStringField(value: _storage._featureCode, fieldNumber: 8) 405 | } 406 | if !_storage._countryIso2.isEmpty { 407 | try visitor.visitSingularStringField(value: _storage._countryIso2, fieldNumber: 9) 408 | } 409 | if _storage._admin1ID != 0 { 410 | try visitor.visitSingularInt32Field(value: _storage._admin1ID, fieldNumber: 10) 411 | } 412 | if _storage._admin2ID != 0 { 413 | try visitor.visitSingularInt32Field(value: _storage._admin2ID, fieldNumber: 11) 414 | } 415 | if _storage._admin3ID != 0 { 416 | try visitor.visitSingularInt32Field(value: _storage._admin3ID, fieldNumber: 12) 417 | } 418 | if _storage._admin4ID != 0 { 419 | try visitor.visitSingularInt32Field(value: _storage._admin4ID, fieldNumber: 13) 420 | } 421 | if _storage._timezoneIndex != 0 { 422 | try visitor.visitSingularInt32Field(value: _storage._timezoneIndex, fieldNumber: 14) 423 | } 424 | if _storage._population != 0 { 425 | try visitor.visitSingularUInt32Field(value: _storage._population, fieldNumber: 15) 426 | } 427 | if !_storage._alternativeNames.isEmpty { 428 | try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: _storage._alternativeNames, fieldNumber: 16) 429 | } 430 | if !_storage._postcodes.isEmpty { 431 | try visitor.visitRepeatedStringField(value: _storage._postcodes, fieldNumber: 17) 432 | } 433 | if _storage._countryID != 0 { 434 | try visitor.visitSingularInt32Field(value: _storage._countryID, fieldNumber: 18) 435 | } 436 | } 437 | try unknownFields.traverse(visitor: &visitor) 438 | } 439 | 440 | static func ==(lhs: GeocodingDatabase.Geoname, rhs: GeocodingDatabase.Geoname) -> Bool { 441 | if lhs._storage !== rhs._storage { 442 | let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in 443 | let _storage = _args.0 444 | let rhs_storage = _args.1 445 | if _storage._id != rhs_storage._id {return false} 446 | if _storage._name != rhs_storage._name {return false} 447 | if _storage._latitude != rhs_storage._latitude {return false} 448 | if _storage._longitude != rhs_storage._longitude {return false} 449 | if _storage._ranking != rhs_storage._ranking {return false} 450 | if _storage._elevation != rhs_storage._elevation {return false} 451 | if _storage._featureCode != rhs_storage._featureCode {return false} 452 | if _storage._countryIso2 != rhs_storage._countryIso2 {return false} 453 | if _storage._countryID != rhs_storage._countryID {return false} 454 | if _storage._admin1ID != rhs_storage._admin1ID {return false} 455 | if _storage._admin2ID != rhs_storage._admin2ID {return false} 456 | if _storage._admin3ID != rhs_storage._admin3ID {return false} 457 | if _storage._admin4ID != rhs_storage._admin4ID {return false} 458 | if _storage._timezoneIndex != rhs_storage._timezoneIndex {return false} 459 | if _storage._population != rhs_storage._population {return false} 460 | if _storage._alternativeNames != rhs_storage._alternativeNames {return false} 461 | if _storage._postcodes != rhs_storage._postcodes {return false} 462 | return true 463 | } 464 | if !storagesAreEqual {return false} 465 | } 466 | if lhs.unknownFields != rhs.unknownFields {return false} 467 | return true 468 | } 469 | } 470 | 471 | extension GeocodingDatabase.Geonames: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 472 | static let protoMessageName: String = GeocodingDatabase.protoMessageName + ".Geonames" 473 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 474 | 1: .same(proto: "geonames"), 475 | 2: .same(proto: "timezones"), 476 | 3: .same(proto: "languages"), 477 | ] 478 | 479 | mutating func decodeMessage(decoder: inout D) throws { 480 | while let fieldNumber = try decoder.nextFieldNumber() { 481 | // The use of inline closures is to circumvent an issue where the compiler 482 | // allocates stack space for every case branch when no optimizations are 483 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 484 | switch fieldNumber { 485 | case 1: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap.self, value: &self.geonames) }() 486 | case 2: try { try decoder.decodeRepeatedStringField(value: &self.timezones) }() 487 | case 3: try { try decoder.decodeRepeatedStringField(value: &self.languages) }() 488 | default: break 489 | } 490 | } 491 | } 492 | 493 | func traverse(visitor: inout V) throws { 494 | if !self.geonames.isEmpty { 495 | try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap.self, value: self.geonames, fieldNumber: 1) 496 | } 497 | if !self.timezones.isEmpty { 498 | try visitor.visitRepeatedStringField(value: self.timezones, fieldNumber: 2) 499 | } 500 | if !self.languages.isEmpty { 501 | try visitor.visitRepeatedStringField(value: self.languages, fieldNumber: 3) 502 | } 503 | try unknownFields.traverse(visitor: &visitor) 504 | } 505 | 506 | static func ==(lhs: GeocodingDatabase.Geonames, rhs: GeocodingDatabase.Geonames) -> Bool { 507 | if lhs.geonames != rhs.geonames {return false} 508 | if lhs.timezones != rhs.timezones {return false} 509 | if lhs.languages != rhs.languages {return false} 510 | if lhs.unknownFields != rhs.unknownFields {return false} 511 | return true 512 | } 513 | } 514 | 515 | extension GeocodingDatabase.GeoTree: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 516 | static let protoMessageName: String = GeocodingDatabase.protoMessageName + ".GeoTree" 517 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 518 | 1: .same(proto: "ordered"), 519 | 2: .same(proto: "values"), 520 | ] 521 | 522 | mutating func decodeMessage(decoder: inout D) throws { 523 | while let fieldNumber = try decoder.nextFieldNumber() { 524 | // The use of inline closures is to circumvent an issue where the compiler 525 | // allocates stack space for every case branch when no optimizations are 526 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 527 | switch fieldNumber { 528 | case 1: try { try decoder.decodeRepeatedInt32Field(value: &self.ordered) }() 529 | case 2: try { try decoder.decodeRepeatedFloatField(value: &self.values) }() 530 | default: break 531 | } 532 | } 533 | } 534 | 535 | func traverse(visitor: inout V) throws { 536 | if !self.ordered.isEmpty { 537 | try visitor.visitPackedInt32Field(value: self.ordered, fieldNumber: 1) 538 | } 539 | if !self.values.isEmpty { 540 | try visitor.visitPackedFloatField(value: self.values, fieldNumber: 2) 541 | } 542 | try unknownFields.traverse(visitor: &visitor) 543 | } 544 | 545 | static func ==(lhs: GeocodingDatabase.GeoTree, rhs: GeocodingDatabase.GeoTree) -> Bool { 546 | if lhs.ordered != rhs.ordered {return false} 547 | if lhs.values != rhs.values {return false} 548 | if lhs.unknownFields != rhs.unknownFields {return false} 549 | return true 550 | } 551 | } 552 | 553 | extension GeocodingDatabase.SearchTree: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 554 | static let protoMessageName: String = GeocodingDatabase.protoMessageName + ".SearchTree" 555 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 556 | 1: .same(proto: "ids"), 557 | 2: .same(proto: "branches"), 558 | 3: .same(proto: "buffer"), 559 | ] 560 | 561 | mutating func decodeMessage(decoder: inout D) throws { 562 | while let fieldNumber = try decoder.nextFieldNumber() { 563 | // The use of inline closures is to circumvent an issue where the compiler 564 | // allocates stack space for every case branch when no optimizations are 565 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 566 | switch fieldNumber { 567 | case 1: try { try decoder.decodeRepeatedInt32Field(value: &self.ids) }() 568 | case 2: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap.self, value: &self.branches) }() 569 | case 3: try { try decoder.decodeRepeatedMessageField(value: &self.buffer) }() 570 | default: break 571 | } 572 | } 573 | } 574 | 575 | func traverse(visitor: inout V) throws { 576 | if !self.ids.isEmpty { 577 | try visitor.visitPackedInt32Field(value: self.ids, fieldNumber: 1) 578 | } 579 | if !self.branches.isEmpty { 580 | try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap.self, value: self.branches, fieldNumber: 2) 581 | } 582 | if !self.buffer.isEmpty { 583 | try visitor.visitRepeatedMessageField(value: self.buffer, fieldNumber: 3) 584 | } 585 | try unknownFields.traverse(visitor: &visitor) 586 | } 587 | 588 | static func ==(lhs: GeocodingDatabase.SearchTree, rhs: GeocodingDatabase.SearchTree) -> Bool { 589 | if lhs.ids != rhs.ids {return false} 590 | if lhs.branches != rhs.branches {return false} 591 | if lhs.buffer != rhs.buffer {return false} 592 | if lhs.unknownFields != rhs.unknownFields {return false} 593 | return true 594 | } 595 | } 596 | 597 | extension GeocodingDatabase.PartialName: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { 598 | static let protoMessageName: String = GeocodingDatabase.protoMessageName + ".PartialName" 599 | static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 600 | 1: .same(proto: "id"), 601 | 2: .same(proto: "remaining"), 602 | ] 603 | 604 | mutating func decodeMessage(decoder: inout D) throws { 605 | while let fieldNumber = try decoder.nextFieldNumber() { 606 | // The use of inline closures is to circumvent an issue where the compiler 607 | // allocates stack space for every case branch when no optimizations are 608 | // enabled. https://github.com/apple/swift-protobuf/issues/1034 609 | switch fieldNumber { 610 | case 1: try { try decoder.decodeSingularInt32Field(value: &self.id) }() 611 | case 2: try { try decoder.decodeSingularStringField(value: &self.remaining) }() 612 | default: break 613 | } 614 | } 615 | } 616 | 617 | func traverse(visitor: inout V) throws { 618 | if self.id != 0 { 619 | try visitor.visitSingularInt32Field(value: self.id, fieldNumber: 1) 620 | } 621 | if !self.remaining.isEmpty { 622 | try visitor.visitSingularStringField(value: self.remaining, fieldNumber: 2) 623 | } 624 | try unknownFields.traverse(visitor: &visitor) 625 | } 626 | 627 | static func ==(lhs: GeocodingDatabase.PartialName, rhs: GeocodingDatabase.PartialName) -> Bool { 628 | if lhs.id != rhs.id {return false} 629 | if lhs.remaining != rhs.remaining {return false} 630 | if lhs.unknownFields != rhs.unknownFields {return false} 631 | return true 632 | } 633 | } 634 | -------------------------------------------------------------------------------- /Sources/App/database.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | message GeocodingDatabase { 4 | Geonames geonames = 1; 5 | SearchTree index = 2; 6 | repeated SearchTree languageIndex = 3; 7 | GeoTree geotree = 4; 8 | 9 | message Geoname { 10 | int32 id = 1; 11 | string name = 2; 12 | float latitude = 4; 13 | float longitude = 5; 14 | float ranking = 6; 15 | float elevation = 7; 16 | string feature_code = 8; 17 | string country_iso2 = 9; 18 | int32 country_id = 18; 19 | int32 admin1_id = 10; 20 | int32 admin2_id = 11; 21 | int32 admin3_id = 12; 22 | int32 admin4_id = 13; 23 | int32 timezone_index = 14; 24 | uint32 population = 15; 25 | map alternativeNames = 16; 26 | repeated string postcodes = 17; 27 | } 28 | 29 | message Geonames { 30 | map geonames = 1; 31 | repeated string timezones = 2; 32 | repeated string languages = 3; 33 | } 34 | 35 | message GeoTree { 36 | repeated int32 ordered = 1; 37 | repeated float values = 2; 38 | } 39 | 40 | message SearchTree { 41 | repeated int32 ids = 1; 42 | map branches = 2; 43 | repeated PartialName buffer = 3; 44 | } 45 | 46 | message PartialName { 47 | int32 id = 1; 48 | string remaining = 2; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Sources/Run/main.swift: -------------------------------------------------------------------------------- 1 | import App 2 | import Vapor 3 | 4 | #if Xcode 5 | let projectHome = String(#file[...#file.range(of: "/Sources/")!.lowerBound]) 6 | FileManager.default.changeCurrentDirectoryPath(projectHome) 7 | #endif 8 | 9 | var env = try Environment.detect() 10 | try LoggingSystem.bootstrap(from: &env) 11 | let app = try await Application.make(env) 12 | try configure(app) 13 | try await app.execute() 14 | try await app.asyncShutdown() 15 | -------------------------------------------------------------------------------- /Tests/AppTests/QuadTreeTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import App 3 | 4 | struct Point: QuadTreeElement { 5 | let latitude: Float 6 | let longitude: Float 7 | } 8 | 9 | final class QuadTreeTests: XCTestCase { 10 | func testInsert() { 11 | return 12 | var points: [Int32: Point] = [:] 13 | for i in 0..<256 { 14 | points[Int32(i)] = Point(latitude: Float(i)/10, longitude: Float(i)/10) 15 | } 16 | let tree = GeocodingDatabase.GeoTree(elements: points, depth: 5) 17 | print(tree.ordered) 18 | print(tree.values) 19 | 20 | let res = tree.knn(latitude: 0.72, longitude: 0.71, count: 5, maxDistanceKilometer: 500, elements: points) 21 | print(res) 22 | XCTAssertEqual(res[0].id, 7) 23 | XCTAssertEqual(res[0].distance, 2.486387) 24 | XCTAssertEqual(res[1].id, 8) 25 | XCTAssertEqual(res[1].distance, 13.3895855) 26 | 27 | //return 28 | for i in 0..<200 { 29 | let res = tree.knn(latitude: Float(i)/10+0.02, longitude: Float(i)/10+0.01, count: 5, maxDistanceKilometer: 500, elements: points) 30 | print(res) 31 | XCTAssertEqual(res[0].id, Int32(i)) 32 | XCTAssertNotEqual(res[1].id, Int32(i)) 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Tests/AppTests/geocoding_apiTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import App 3 | import Vapor 4 | 5 | final class geocoding_apiTests: XCTestCase { 6 | 7 | func testUnicodeNormalisation() { 8 | let a = "Rügen caractères spéciaux contrairement à la langue française".folding(options: .diacriticInsensitive, locale: nil).lowercased() 9 | XCTAssertEqual(a, "rugen caracteres speciaux contrairement a la langue francaise") 10 | } 11 | 12 | func testPriorityQueue() { 13 | let q = PriorityQueue(length: 5) 14 | q.insert(id: 1, priority: 0.5) 15 | q.insert(id: 2, priority: 0.6) 16 | q.insert(id: 3, priority: 0.6) 17 | // insert a duplicate with a higher priority 18 | q.insert(id: 3, priority: 0.7) 19 | q.insert(id: 3, priority: 0.6) 20 | q.insert(id: 4, priority: 0.6) 21 | q.insert(id: 5, priority: 0.6) 22 | q.insert(id: 6, priority: 0.8) 23 | q.insert(id: 7, priority: 0.0) 24 | XCTAssertEqual(q.queue[0].id, 6) 25 | XCTAssertEqual(q.queue[1].id, 3) 26 | XCTAssertEqual(q.queue[2].id, 2) 27 | XCTAssertEqual(q.queue[3].id, 4) 28 | XCTAssertEqual(q.queue[4].id, 5) 29 | } 30 | 31 | func testExample() throws { 32 | let logger = Logger(label: "test") 33 | let data = """ 34 | 1639953\t2760454\tja\tツークシュピッツェ\t\t\t\t\t\t 35 | 1639954\t2760454\tnl\tZugspitze\t\t\t\t\t\t 36 | 1639955\t2760454\tpt\tZugspitze\t\t\t\t\t\t 37 | 1639956\t2760454\tsk\tZugspitze\t\t\t\t\t\t 38 | 1639957\t2760454\tsv\tZugspitze\t\t\t\t\t\t 39 | 1639958\t2760454\ttr\tZugspitze Dağı\t\t\t\t\t\t 40 | 1904539\t2760454\tit\tZugspitze\t\t\t\t\t\t 41 | 2957082\t2760454\tlink\thttps://en.wikipedia.org/wiki/Zugspitze\t\t\t\t\t\t 42 | 3052258\t2760454\tlink\thttps://ru.wikipedia.org/wiki/%D0%A6%D1%83%D0%B3%D1%88%D0%BF%D0%B8%D1%82%D1%86%D0%B5\t\t\t\t\t\t 43 | 8199248\t2760454\tfa\tتسوگ‌اشپیتسه\t\t\t\t\t\t 44 | 8199249\t2760454\tuk\tЦугшпітце\t\t\t\t\t\t 45 | 8199250\t2760454\tbar\tZugspitz\t\t\t\t\t\t 46 | 8199251\t2760454\tko\t추크슈피체 산\t\t\t\t\t\t 47 | 8199252\t2760454\the\tצוגשפיצה\t\t\t\t\t\t 48 | 8199253\t2760454\tmr\tत्सुगस्पिट्से\t\t\t\t\t\t 49 | 8199254\t2760454\tbe\tГара Цугшпіцэ\t\t\t\t\t\t 50 | 8199255\t2760454\tka\tცუგშპიცე\t\t\t\t\t\t 51 | 8199256\t2760454\tpnb\tسوگسپتزے\t\t\t\t\t\t 52 | 8199257\t2760454\tlt\tCūgšpicė\t\t\t\t\t\t 53 | 8199258\t2760454\tru\tЦугшпитце\t\t\t\t\t\t 54 | 8199259\t2760454\tzh\t楚格峰\t\t\t\t\t\t 55 | 11324584\t2760454\tar\tقمة تسوغشبيتسه\t\t\t\t\t\t 56 | 11324585\t2760454\tmk\tЦугшпице\t\t\t\t\t\t 57 | 15440607\t2760454\twkdt\tQ3375\t\t\t\t\t 58 | """.data(using: .utf8)! 59 | 60 | let names = AlternateNames(data: data, logger: logger) 61 | XCTAssertEqual(names.alternativesPreferred.count, 1) 62 | XCTAssertEqual(names.alternativesPreferred[2760454]?.count, 21) 63 | 64 | let data2 = """ 65 | 1529666\tBahnhof Grenzau\tBahnhof Grenzau\tBahnhof Grenzau,Grenzau\t50.45663\t7.66505\tS\tRSTN\tDE\t\t08\t00\t07143\t07143032\t0\t\t232\tEurope/Berlin\t2020-10-14 66 | 2038682\tBahnhof Annaburg\tBahnhof Annaburg\tAnnaburg,Bahnhof Annaburg,Bahnhof Annaburg West\t51.72858\t13.03311\tS\tRSTN\tDE\t\t11\t\t\t\t0\t\t77\tEurope/Berlin\t2020-10-14 67 | 2657946\tWyhlen\tWyhlen\tWyhlen\t47.54729\t7.69331\tP\tPPLX\tDE\t\t01\t083\t08336\t08336105\t0\t\t269\tEurope/Berlin\t2020-11-12 68 | 2658739\tSchiener Bach\tSchiener Bach\tSchiener Bach\t47.6802\t8.86131\tH\tSTM\tDE\tDE,CH\t00\t\t\t\t0\t\t512\tEurope/Zurich\t2015-09-06 69 | 2659829\tLunkenbach\tLunkenbach\tLunckenbach,Lunkenbach\t47.68136\t8.84938\tH\tSTM\tDE\tDE,CH\t00\t\t\t\t0\t\t462\tEurope/Zurich\t2015-09-06 70 | 2744273\tWitte Venn\tWitte Venn\tWitte Veen,Witte Venn\t52.15\t6.88333\tH\tMRSH\tDE\t\t00\t\t\t\t0\t\t40\tEurope/Amsterdam\t2014-08-05 71 | 2744666\tWesterwoldsche A\tWesterwoldsche A\tWesterwoldsche A,Westerwoldsche Aa,Westerwoldse Aa\t53.23333\t7.2\tH\tSTMC\tDE\t\t00\t\t\t\t0\t\t-1\tEurope/Amsterdam\t2014-08-05 72 | 2745605\tHoge Veenkanal\tHoge Veenkanal\tHoge Veenkanal,Verlangde Hoogeveensche Vaart,Verlengde Hoogeveensche Vaart,Verlengde Hoogeveense Vaart\t52.73333\t6.51667\tH\tCNL\tDE\t\t00\t\t\t\t0\t\t12\tEurope/Amsterdam\t2014-08-05 73 | """.data(using: .utf8)! 74 | 75 | let geonames = GeocodingDatabase.Geonames(data: data2, alternativeNames: names, logger: logger) 76 | XCTAssertEqual(geonames.geonames.count, 1) 77 | 78 | /*let tree = SearchTree.load(geonames: geonames) 79 | let res = tree.search(Substring("Bahn")) 80 | XCTAssertEqual(res, [1529666, 2038682])*/ 81 | } 82 | 83 | func testPopulationRanking() { 84 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(0), 0) 85 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(10), 0.038468935) 86 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(1000), 0.03920805) 87 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(10000), 0.046580374) 88 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(50000), 0.09806819) 89 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(100000), 0.22813433) 90 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(200000), 0.6859223) 91 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(500000), 0.9988663) 92 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(1000000), 1.0) 93 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(2000000), 1.0) 94 | XCTAssertEqual(GeocodingDatabase.Geonames.populationToRank(10000000), 1.0) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /build/geocoding-api.env: -------------------------------------------------------------------------------- 1 | VAPOR_ENV=production 2 | API_BIND="127.0.0.1:8082" 3 | LOG_LEVEL=info -------------------------------------------------------------------------------- /build/geocoding-api.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description = Run Open-Meteo geocoding API 3 | StartLimitIntervalSec=0 4 | 5 | [Service] 6 | EnvironmentFile=/etc/default/geocoding-api.env 7 | PassEnvironment=VAPOR_ENV LOG_LEVEL SWIFT_BACKTRACE 8 | Type=simple 9 | User=geocoding-api 10 | Group=geocoding-api 11 | WorkingDirectory=/var/lib/geocoding-api/ 12 | ExecStart=/usr/local/bin/geocoding-api serve -b $API_BIND --env $VAPOR_ENV 13 | Restart=always 14 | RestartSec=1 15 | LimitNOFILE=infinity 16 | 17 | [Install] 18 | WantedBy = multi-user.target -------------------------------------------------------------------------------- /build/geocoding-before-install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | echo "Running before-install.sh" 4 | 5 | /usr/bin/mkdir -p /var/lib/geocoding-api/ 6 | /usr/sbin/useradd --user-group geocoding-api || echo "User exists already" 7 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Docker Compose file for Vapor 2 | # 3 | # Install Docker on your system to run and test 4 | # your Vapor app in a production-like environment. 5 | # 6 | # Note: This file is intended for testing and does not 7 | # implement best practices for a production deployment. 8 | # 9 | # Learn more: https://docs.docker.com/compose/reference/ 10 | # 11 | # Build images: docker-compose build 12 | # Start app: docker-compose up open-meteo 13 | # Run commands: docker-compose run open-meteo --help 14 | # Stop all: docker-compose down (add -v to wipe data) 15 | # 16 | version: '3.7' 17 | 18 | volumes: 19 | db_data: 20 | 21 | x-shared_environment: &shared_environment 22 | LOG_LEVEL: ${LOG_LEVEL:-info} 23 | 24 | services: 25 | open-meteo: 26 | image: open-meteo:latest 27 | volumes: 28 | - db_data:/app/data 29 | build: 30 | context: . 31 | environment: 32 | <<: *shared_environment 33 | ports: 34 | - '8080:8080' 35 | user: '0' 36 | command: ["serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"] --------------------------------------------------------------------------------