From 1d8269f5c0a32af7d8899893e2451dced26fd027 Mon Sep 17 00:00:00 2001 From: Roman Pushkin Date: Tue, 25 Feb 2020 20:42:05 -0800 Subject: [PATCH] Move version 2 to LibreTaxi repo --- .gitignore | 22 ++ Gopkg.lock | 215 +++++++++++++ Gopkg.toml | 54 ++++ LICENSE | 662 ++++++++++++++++++++++++++++++++++++++ README.md | 73 +++++ bin/run_postgres.sh | 25 ++ bin/run_rabbit.sh | 3 + callback/callback.go | 38 +++ config/config.go | 32 ++ context/context.go | 24 ++ db/init.sql | 52 +++ docker-compose.yml | 28 ++ libretaxi.go | 176 ++++++++++ locales/all/en.po | 105 ++++++ locales/all/es.po | 102 ++++++ locales/all/fa.po | 102 ++++++ locales/all/pt-br.po | 102 ++++++ locales/all/pt-pt.po | 102 ++++++ locales/all/ru.po | 105 ++++++ menu/ask_location_menu.go | 52 +++ menu/feed_menu.go | 64 ++++ menu/init_menu.go | 63 ++++ menu/menu.go | 108 +++++++ menu/post_menu.go | 184 +++++++++++ objects/post.go | 11 + objects/user.go | 41 +++ rabbit/rabbit.go | 224 +++++++++++++ repository/repository.go | 140 ++++++++ sender/sender.go | 43 +++ util/util.go | 12 + validation/validation.go | 82 +++++ 31 files changed, 3046 insertions(+) create mode 100644 .gitignore create mode 100644 Gopkg.lock create mode 100644 Gopkg.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100755 bin/run_postgres.sh create mode 100755 bin/run_rabbit.sh create mode 100644 callback/callback.go create mode 100644 config/config.go create mode 100644 context/context.go create mode 100644 db/init.sql create mode 100644 docker-compose.yml create mode 100644 libretaxi.go create mode 100644 locales/all/en.po create mode 100644 locales/all/es.po create mode 100644 locales/all/fa.po create mode 100644 locales/all/pt-br.po create mode 100644 locales/all/pt-pt.po create mode 100644 locales/all/ru.po create mode 100644 menu/ask_location_menu.go create mode 100644 menu/feed_menu.go create mode 100644 menu/init_menu.go create mode 100644 menu/menu.go create mode 100644 menu/post_menu.go create mode 100644 objects/post.go create mode 100644 objects/user.go create mode 100644 rabbit/rabbit.go create mode 100644 repository/repository.go create mode 100644 sender/sender.go create mode 100644 util/util.go create mode 100644 validation/validation.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..d4743495 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +vendor/ + +.idea/ + +libretaxi +libretaxi.yml + +migration/ diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 00000000..9303bd66 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,215 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" + name = "github.com/fsnotify/fsnotify" + packages = ["."] + pruneopts = "UT" + revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" + version = "v1.4.7" + +[[projects]] + digest = "1:51712f342cdefcad2c867f399a3ce8223675221d4386c81cfcccd8f0656e722e" + name = "github.com/go-telegram-bot-api/telegram-bot-api" + packages = ["."] + pruneopts = "UT" + revision = "9860bdfd3a171ceafb6e1eafa163482a6ef92643" + version = "v4.6.4" + +[[projects]] + digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" + name = "github.com/hashicorp/hcl" + packages = [ + ".", + "hcl/ast", + "hcl/parser", + "hcl/printer", + "hcl/scanner", + "hcl/strconv", + "hcl/token", + "json/parser", + "json/scanner", + "json/token", + ] + pruneopts = "UT" + revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" + version = "v1.0.0" + +[[projects]] + digest = "1:c1969ca636a3249ca89cc658fb22280f69bb6f191787b0a2437690daddb25e7d" + name = "github.com/leonelquinteros/gotext" + packages = [ + ".", + "plurals", + ] + pruneopts = "UT" + revision = "477ce49ddf8f201350f40fdb5ed80a65d155cc33" + version = "v1.4.0" + +[[projects]] + digest = "1:9ff22c26414baf7deaf74f2a788fe7b97666048bcbe346c52cfe823442abbdfb" + name = "github.com/lib/pq" + packages = [ + ".", + "oid", + "scram", + ] + pruneopts = "UT" + revision = "99274577be97ac9b1d95a2d61d566dc9b7cc6a54" + version = "v1.3.0" + +[[projects]] + digest = "1:5a0ef768465592efca0412f7e838cdc0826712f8447e70e6ccc52eb441e9ab13" + name = "github.com/magiconair/properties" + packages = ["."] + pruneopts = "UT" + revision = "de8848e004dd33dc07a2947b3d76f618a7fc7ef1" + version = "v1.8.1" + +[[projects]] + digest = "1:53bc4cd4914cd7cd52139990d5170d6dc99067ae31c56530621b18b35fc30318" + name = "github.com/mitchellh/mapstructure" + packages = ["."] + pruneopts = "UT" + revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe" + version = "v1.1.2" + +[[projects]] + digest = "1:6eea828983c70075ca297bb915ffbcfd3e34c5a50affd94428a65df955c0ff9c" + name = "github.com/pelletier/go-toml" + packages = ["."] + pruneopts = "UT" + revision = "903d9455db9ff1d7ac1ab199062eca7266dd11a3" + version = "v1.6.0" + +[[projects]] + digest = "1:bb495ec276ab82d3dd08504bbc0594a65de8c3b22c6f2aaa92d05b73fbf3a82e" + name = "github.com/spf13/afero" + packages = [ + ".", + "mem", + ] + pruneopts = "UT" + revision = "588a75ec4f32903aa5e39a2619ba6a4631e28424" + version = "v1.2.2" + +[[projects]] + digest = "1:ff4cd55a3666b6ea3a876c9e133bfb54d6c812e725409a773f2c94a0b3a92f4f" + name = "github.com/spf13/cast" + packages = ["."] + pruneopts = "UT" + revision = "1ffadf551085444af981432dd0f6d1160c11ec64" + version = "v1.3.1" + +[[projects]] + digest = "1:1b753ec16506f5864d26a28b43703c58831255059644351bbcb019b843950900" + name = "github.com/spf13/jwalterweatherman" + packages = ["."] + pruneopts = "UT" + revision = "94f6ae3ed3bceceafa716478c5fbf8d29ca601a1" + version = "v1.1.0" + +[[projects]] + digest = "1:524b71991fc7d9246cc7dc2d9e0886ccb97648091c63e30eef619e6862c955dd" + name = "github.com/spf13/pflag" + packages = ["."] + pruneopts = "UT" + revision = "2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab" + version = "v1.0.5" + +[[projects]] + digest = "1:83d0e0f3f46dc86daf27e4d7c834c8c492db787c53c09d94183de7478db92142" + name = "github.com/spf13/viper" + packages = ["."] + pruneopts = "UT" + revision = "4525543ce4fe90f7970f5e2cdc300b8ffc8c0582" + version = "v1.6.2" + +[[projects]] + branch = "master" + digest = "1:5ca236e4ecfeb92a57b7a4c7f139023384e7f726640f61b17820473cc82dfb77" + name = "github.com/streadway/amqp" + packages = ["."] + pruneopts = "UT" + revision = "1c71cc93ed716f9a6f4c2ae8955c25f9176d9f19" + +[[projects]] + digest = "1:f4b32291cad5efac2bfdba89ccde6aa04618b62ce06c1a571da2dc4f3f2677fb" + name = "github.com/subosito/gotenv" + packages = ["."] + pruneopts = "UT" + revision = "2ef7124db659d49edac6aa459693a15ae36c671a" + version = "v1.2.0" + +[[projects]] + digest = "1:420817f94b6c172dabb8a054d0b2d257d7437a87c7c8c7ee432bc008a577fc46" + name = "github.com/technoweenie/multipartstreamer" + packages = ["."] + pruneopts = "UT" + revision = "a90a01d73ae432e2611d178c18367fbaa13e0154" + version = "v1.0.1" + +[[projects]] + digest = "1:9d8dd533fab0651b2d03970664d7f57880cfa092e0e3d36e8fdd8e371b65a7d9" + name = "go.uber.org/ratelimit" + packages = [ + ".", + "internal/clock", + ] + pruneopts = "UT" + revision = "cd1f0abeddc3fe992a7be8d533332897936efbc0" + version = "v0.1.0" + +[[projects]] + branch = "master" + digest = "1:46aee4748419921a611e49842c732b3b8afe6a0926017ad1a68b9d0e11fdd288" + name = "golang.org/x/sys" + packages = ["unix"] + pruneopts = "UT" + revision = "34d275377bf96a094e8d5b0c61750ddd54cd6b36" + +[[projects]] + digest = "1:1093f2eb4b344996604f7d8b29a16c5b22ab9e1b25652140d3fede39f640d5cd" + name = "golang.org/x/text" + packages = [ + "internal/gen", + "internal/triegen", + "internal/ucd", + "transform", + "unicode/cldr", + "unicode/norm", + ] + pruneopts = "UT" + revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" + version = "v0.3.2" + +[[projects]] + digest = "1:c4b5592c342f273e18de68e16957f536f6648f2e90c9d7ece653ac90c22079a9" + name = "gopkg.in/ini.v1" + packages = ["."] + pruneopts = "UT" + revision = "94291fffe2b14f4632ec0e67c1bfecfc1287a168" + version = "v1.51.1" + +[[projects]] + digest = "1:b75b3deb2bce8bc079e16bb2aecfe01eb80098f5650f9e93e5643ca8b7b73737" + name = "gopkg.in/yaml.v2" + packages = ["."] + pruneopts = "UT" + revision = "1f64d6156d11335c3f22d9330b0ad14fc1e789ce" + version = "v2.2.7" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = [ + "github.com/go-telegram-bot-api/telegram-bot-api", + "github.com/leonelquinteros/gotext", + "github.com/lib/pq", + "github.com/spf13/viper", + "github.com/streadway/amqp", + "go.uber.org/ratelimit", + ] + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 00000000..168d3a47 --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,54 @@ +# Gopkg.toml example +# +# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + + +[prune] + go-tests = true + unused-packages = true + +[[constraint]] + name = "github.com/spf13/viper" + version = "1.6.2" + +[[constraint]] + name = "github.com/go-telegram-bot-api/telegram-bot-api" + version = "4.6.4" + +[[constraint]] + name = "github.com/lib/pq" + version = "1.3.0" + +[[constraint]] + branch = "master" + name = "github.com/streadway/amqp" + +[[constraint]] + name = "go.uber.org/ratelimit" + version = "0.1.0" + +[[constraint]] + name = "github.com/leonelquinteros/gotext" + version = "1.4.0" diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..a871fcfd --- /dev/null +++ b/LICENSE @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/README.md b/README.md new file mode 100644 index 00000000..cc191f6c --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# LibreTaxi v2, #deleteuber + +``` +Roses are red +violets are blue +workers are tired of getting exploited +and we're all coming for you +``` + +LibreTaxi is open-source Uber proof-of-concept that works though [Telegram](https://telegram.org/). + +See it in action: https://t.me/libretaxi_bot + +Public feed: https://t.me/libretaxi_all + +It is closer to Craigslist rideshare rather than Uber, but it works, and works great! The app that is easy to use, supports multiple languages, fast and cool. There are tens of thousands users worldwide, and we're on the way to 1M users. So please spread the word! + +* [How it works - English](https://telegra.ph/LibreTaxi-20---you-will-love-it-02-02) +* [How it works - Spanish](https://telegra.ph/LibreTaxi-20---te-va-a-enamorar-02-09) +* [How it works - Russian](https://telegra.ph/Novaya-versiya-Libre-taksi-vam-ponravitsya-02-08) +* [How it works - Portuguese](https://telegra.ph/LibreTaxi-20---Vai-o-amar-02-12) + +## Prerequisites + +1. [Install Go](https://golang.org/doc/install) +2. [Install Go dep](https://github.com/golang/dep) +3. Download the repo to `~/go/src/libretaxi` (not libretaxi2). +4. Install Docker with docker-compose +5. Run PostgreSQL and RabbitMQ with default credentials (see connection strings below) +``` +docker-compose up -d +``` + +## Setting up RabbitMQ (for development and production) + +`rabbitmq:3-management` contains UI plugin for queue management. Plugin port is 8080 (15672 in container). +Login **guest/guest**. + +Login to RabbitUI here: http://localhost:8080 + +There is only one queue at the moment: + +* `messages` queue, http://localhost:8080/#/queues/%2F/messages - picked up by message handler, enqueued by libretaxi + +Note that there is one message producer, and one message consumer threads (goroutines) in application. + +Port 5672 is RabbitMQ itself. + +## LibreTaxi settings + +Init settings for `./libretaxi.yml`: + +``` +telegram_token: YOUR_TOKEN +db_conn_str: postgres://libretaxi:libretaxi@localhost:15432/libretaxi +rabbit_url: amqp://127.0.0.1:8079/ +admin_channel_chat_id: -1001324105405 +public_channel_chat_id: -1001470847849 +``` + +Admin channel is the place where you shadow ban spamers. +See https://stackoverflow.com/a/41779623/337085 for how to get id for you private channel. +You'll need to invite `@get_id_bot` and type `/my_id@get_id_bot`. You'll see chat id. + +## Running + +When all services are running, run libretaxi: + +``` +dep ensure # or ~/go/bin/dep ensure +go build +./libretaxi +``` diff --git a/bin/run_postgres.sh b/bin/run_postgres.sh new file mode 100755 index 00000000..83f45bc4 --- /dev/null +++ b/bin/run_postgres.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +CID=$( + docker run -d -v libretaxi:/var/lib/postgresql/data \ + -p 127.0.0.1:5432:5432 -e POSTGRES_USER=libretaxi -e POSTGRES_TEMPLATE_EXTENSIONS=true \ + -e POSTGRES_PASS=libretaxi -e POSTGRES_DBNAME=libretaxi -e POSTGRES_MULTIPLE_EXTENSIONS=postgis,hstore,postgis_topology \ + kartoza/postgis:12.0 +) +IPADDR=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' $CID) + +cat << EOF +=== DOCKER INFO: === +IP/PORT: $IPADDR:5432 +=== COMMANDS HELP: === +psql -U libretaxi -h localhost -p 5432 -d libretaxi + Run PostgreSQL CLI (password is libretaxi) +\c libretaxi + Connect to the database +\dt+ + List tables in the database +exit + Exit from PostgreSQL CLI +EOF + +docker exec -ti $CID bash \ No newline at end of file diff --git a/bin/run_rabbit.sh b/bin/run_rabbit.sh new file mode 100755 index 00000000..20ed71f6 --- /dev/null +++ b/bin/run_rabbit.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +docker run -d --hostname my-rabbit --name libretaxi-rabbit -p 5672:5672 -p 8080:15672 rabbitmq:3-management \ No newline at end of file diff --git a/callback/callback.go b/callback/callback.go new file mode 100644 index 00000000..129abd8e --- /dev/null +++ b/callback/callback.go @@ -0,0 +1,38 @@ +package callback + +import ( + "encoding/json" + "libretaxi/context" + "log" +) + +type TgCallbackHandler struct { +} + +type ActionData struct { + Action string + Id int64 +} + +func(callbackHandler *TgCallbackHandler) Handle(context *context.Context, jsonString string) { + var actionData ActionData + json.Unmarshal([]byte(jsonString), &actionData) + + log.Printf("Action: %s, Id: %d\n", actionData.Action, actionData.Id) + + switch actionData.Action { + case "REPORT_POST": + post := context.Repo.FindPost(actionData.Id) + post.ReportCnt++ + context.Repo.SavePost(post) + case "SHADOW_BAN": + user := context.Repo.FindUser(actionData.Id) + user.ShadowBanned = true + context.Repo.SaveUser(user) + } +} + +func NewTgCallbackHandler() (callbackHandler *TgCallbackHandler) { + ch := &TgCallbackHandler{} + return ch +} \ No newline at end of file diff --git a/config/config.go b/config/config.go new file mode 100644 index 00000000..b1d97e43 --- /dev/null +++ b/config/config.go @@ -0,0 +1,32 @@ +package config + +import ( + "github.com/spf13/viper" + "fmt" +) + +type Config struct { + Telegram_Token string + Db_Conn_Str string + Rabbit_Url string + Admin_Channel_Chat_Id int64 + Public_Channel_Chat_Id int64 +} + +var config Config + +func C() *Config { + return &config +} + +func Init(file string) { + viper.SetConfigName(file) + viper.AddConfigPath(".") + + err := viper.ReadInConfig() + if err != nil { + panic(fmt.Errorf("Error in config file: %s", err)) + } + + viper.Unmarshal(&config) +} diff --git a/context/context.go b/context/context.go new file mode 100644 index 00000000..ecc89bb8 --- /dev/null +++ b/context/context.go @@ -0,0 +1,24 @@ +package context + +import ( + "github.com/go-telegram-bot-api/telegram-bot-api" + "libretaxi/config" + "libretaxi/rabbit" + "libretaxi/repository" +) + +type Context struct { + Bot *tgbotapi.BotAPI + Repo *repository.Repository + RabbitPublish *rabbit.RabbitClient // for publishing only + RabbitConsume *rabbit.RabbitClient // for consuming only + Config *config.Config +} + +// drop-in replacement for telegram Send method, posts with highest priority +func (context * Context) Send(message tgbotapi.MessageConfig) { + context.RabbitPublish.PublishTgMessage(rabbit.MessageBag{ + Message: message, + Priority: 255, // highest priority, lowest is 0 + }) +} diff --git a/db/init.sql b/db/init.sql new file mode 100644 index 00000000..f9630a0f --- /dev/null +++ b/db/init.sql @@ -0,0 +1,52 @@ +-- drop index idx_user_id_at_dismissed_feature_callouts; +-- drop index idx_created_at_utc_posts; +-- drop index idx_user_id_and_created_at_utc; +-- drop table dismissed_feature_callouts; +-- drop index users_geog_idx; +-- drop table posts; +-- drop table users; + +create table if not exists users +( + "userId" bigint not null, + "menuId" int, + "username" text, + "firstName" text, + "lastName" text, + "lon" double precision, + "lat" double precision, + "geog" geography(POINT, 4326), + "languageCode" text, + "reportCnt" int default(0), + "shadowBanned" boolean default(false), + "createdAtUtc" timestamp without time zone not null default (now() at time zone 'utc'), + + primary key ("userId") +); + +create index if not exists users_geog_idx on users using gist(geog); + +create table if not exists posts +( + "postId" bigint generated by default as identity primary key, + "userId" bigint not null references "users" ("userId"), + "text" text, + "lon" double precision, + "lat" double precision, + "geog" geography(POINT, 4326), + "reportCnt" int default(0), + "createdAtUtc" timestamp without time zone not null default (now() at time zone 'utc') +); + +create index if not exists idx_created_at_utc_posts on "posts"("createdAtUtc"); +create index if not exists idx_user_id_and_created_at_utc on "posts"("userId", "createdAtUtc"); + +create table if not exists dismissed_feature_callouts ( + "id" bigint generated by default as identity primary key, + "userId" bigint not null, -- do not reference to users table, so it can be used when user isn't present + "featureName" text not null, + "createdAtUtc" timestamp without time zone not null default (now() at time zone 'utc'), + unique ("userId","featureName") +); + +create index if not exists idx_user_id_at_dismissed_feature_callouts on "dismissed_feature_callouts"("userId"); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..e917f18e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,28 @@ +version: "3" + +volumes: + db: {} + rabbit: {} + +services: + db: + image: kartoza/postgis:12.0 + volumes: + - db:/var/lib/postgresql + - ./db/init.sql:/docker-entrypoint-initdb.d/setup-db.sql + environment: + - POSTGRES_USER=libretaxi + - POSTGRES_TEMPLATE_EXTENSIONS=true + - POSTGRES_PASS=libretaxi + - POSTGRES_DBNAME=libretaxi + - POSTGRES_MULTIPLE_EXTENSIONS=postgis,hstore,postgis_topology + ports: + - 127.0.0.1:15432:5432 + rabbit: + hostname: my-rabbit + image: rabbitmq:3-management + volumes: + - rabbit:/var/lib/rabbitmq + ports: + - 127.0.0.1:8079:5672 + - 127.0.0.1:8080:15672 diff --git a/libretaxi.go b/libretaxi.go new file mode 100644 index 00000000..92e494b8 --- /dev/null +++ b/libretaxi.go @@ -0,0 +1,176 @@ +package main + +import ( + "database/sql" + "github.com/go-telegram-bot-api/telegram-bot-api" + "github.com/leonelquinteros/gotext" + _ "github.com/lib/pq" // important + "go.uber.org/ratelimit" + "libretaxi/callback" + "libretaxi/config" + "libretaxi/context" + "libretaxi/menu" + "libretaxi/rabbit" + "libretaxi/repository" + "libretaxi/sender" + "log" + "math/rand" + "time" +) + +func initContext() *context.Context { + log.Printf("Using '%s' telegram token\n", config.C().Telegram_Token) + log.Printf("Using '%s' database connection string", config.C().Db_Conn_Str) + log.Printf("Using '%s' RabbitMQ connection string", config.C().Rabbit_Url) + + context := &context.Context{} + + bot, err := tgbotapi.NewBotAPI(config.C().Telegram_Token) + if err != nil { + log.Panic(err) + } + // bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + db, err := sql.Open("postgres", config.C().Db_Conn_Str) + if err != nil { + log.Fatal(err) + } else { + log.Print("Successfully connected to the database") + } + + context.Bot = bot + context.Repo = repository.NewRepository(db) + context.Config = config.C() + return context +} + +// Message producer (app logic) +func main1() { + context := initContext() + context.RabbitPublish = rabbit.NewRabbitClient(config.C().Rabbit_Url, "messages") + + u := tgbotapi.NewUpdate(0) + u.Timeout = 60 + u.Limit = 99 + + updates, _ := context.Bot.GetUpdatesChan(u) + + for update := range updates { + if update.Message != nil { + + // Ignore the case where message comes from a chat, not from user. We do not support chats. + if update.Message.From == nil { + continue + } + + userId := update.Message.Chat.ID + + log.Printf("[%d - %s] %s", userId, update.Message.From.UserName, update.Message.Text) + menu.HandleMessage(context, userId, update.Message) + + } else if update.CallbackQuery != nil { + + // A couple of places where we directly interact with Telegram API without a queue. Not a good thing, + // must be enqueued as well. + + cb := update.CallbackQuery + context.Bot.AnswerCallbackQuery(tgbotapi.NewCallback(cb.ID, "👌 OK")) + + emptyKeyboard := tgbotapi.NewInlineKeyboardMarkup([]tgbotapi.InlineKeyboardButton{}) + removeButton := tgbotapi.NewEditMessageReplyMarkup(cb.Message.Chat.ID, cb.Message.MessageID, emptyKeyboard) + + _, err := context.Bot.Send(removeButton) + if err != nil { + log.Println(err) + } + + + callback.NewTgCallbackHandler().Handle(context, cb.Data) + } + } +} + +// Message consumer (send to Telegram respecting rate limits) +func main2() { + context := initContext() + context.RabbitConsume = rabbit.NewRabbitClient(config.C().Rabbit_Url, "messages") + + s := sender.NewSender(context) + s.Start() +} + +func getLocale(languageCode string) *gotext.Locale { + locale := gotext.NewLocale("./locales", "all") + + if languageCode == "ru" || languageCode == "es" { + locale.AddDomain(languageCode) + } else { + locale.AddDomain("en") + } + return locale +} + +func massAnnounce() { + context := &context.Context{} + db, err := sql.Open("postgres", config.C().Db_Conn_Str) + if err != nil { + log.Fatal(err) + } else { + log.Print("Successfully connected to the database") + } + + context.Repo = repository.NewRepository(db) + context.Config = config.C() + context.RabbitPublish = rabbit.NewRabbitClient(config.C().Rabbit_Url, "messages") + + var userId int64 + var languageCode string + + rows, err := db.Query("select \"userId\", \"languageCode\" from users where \"languageCode\"='pt-br'") + if err != nil { + log.Fatal(err) + } + defer rows.Close() + + rl := ratelimit.New(5) // don't load DB too much + + for rows.Next() { + err := rows.Scan(&userId, &languageCode) + if err == nil && context.Repo.ShowCallout(userId, "pt_br_translation_announcement") { + + locale := getLocale(languageCode) + link := locale.Get("main.welcome_link") + text := link + " 👉👉👉 /start 👈👈👈" + msg := tgbotapi.NewMessage(userId, text) + + context.RabbitPublish.PublishTgMessage(rabbit.MessageBag{ + Message: msg, + Priority: 0, // LOWEST + }) + + log.Println("Mass sending to ", userId, languageCode) + + context.Repo.DismissCallout(userId, "pt_br_translation_announcement") + + rl.Take() + } + } + err = rows.Err() + if err != nil { + log.Fatal(err) + } +} + +func main() { + rand.Seed(time.Now().UnixNano()) + config.Init("libretaxi") + + go main1() + go main2() + //go massAnnounce() + + forever := make(chan bool) + <- forever +} diff --git a/locales/all/en.po b/locales/all/en.po new file mode 100644 index 00000000..9a95e001 --- /dev/null +++ b/locales/all/en.po @@ -0,0 +1,105 @@ +msgid "init_menu.welcome" +msgstr "Welcome to LibreTaxi 2.0!\n" +"Source code: https://github.com/ro31337/libretaxi2\n" +"Made by Roman Pushkin and supporters\n" +"License: AGPL-3.0" + +msgid "ask_location_menu.click_next" +msgstr "Click \"Next\" (from mobile phone) to share your location. Or fake it with 📎 Paperclip -> 📍 Location" + +msgid "ask_location_menu.next_button" +msgstr "Next" + +msgid "feed_menu.greeting" +msgstr "You'll see 🚗 drivers and 👋 passengers here." + +msgid "feed_menu.search_button" +msgstr "Find 🚗 or 👋" + +msgid "feed_menu.location_button" +msgstr "📍 Change location" + +msgid "feed_menu.location_changed" +msgstr "👌 Location updated" + +msgid "feed_menu.error" +msgstr "😕 Can't understand your choice" + +msgid "post_menu.report_button" +msgstr "☝️️Report ⚠️" + +msgid "post_menu.wait" +msgstr "🕙 Wait for 5 minutes" + +# Do not translate /cancel +msgid "post_menu.copy_and_paste" +msgstr "Copy & paste text starting with 🚗 (driver) or 👋 (passenger) in the following format, or /cancel, examples:" + +msgid "post_menu.driver_example" +msgstr "" +"🚗 Ride offer\n" +"From: foobar square\n" +"To: airport\n" +"Date: today\n" +"Time: now\n" +"Payment: cash, venmo" + +msgid "post_menu.passenger_example" +msgstr "" +"👋 Ride wanted\n" +"From: foobar st, 42\n" +"To: downtown\n" +"Date: today\n" +"Time: now\n" +"Pax: 1" + +# Here is how we check if the user just copied the text or changed it. It's just a string from the previous postings. +# Note how we have "foobar" in both postings above. It's the magic string, non-existent address, you should think +# about an address that doesn't exist in your own language. Or you can leave "foobar" if you didn't get it ;) +# Keep it lowercased! +msgid "validation.dummy_addr_lowercase" +msgstr "foobar" + +msgid "post_menu.sent" +msgstr "✅ Sent to users around you (25km) and to @libretaxi_all" + +# "Contact" is a verb here. For example, we'll have a posting where it says "blabla, I'm looking for ride, contact @username". +# So you're translating this verb "contact" below. +msgid "post_menu.via" +msgstr "Contact" + +# When we have an error we say something like: +# "Your input is invalid, try again or /cancel" +# So this "or" part needs to be translated below. +msgid "post_menu.or" +msgstr "or" + +msgid "validation.text_too_long" +msgstr "🚫 Text is too long, 300 characters max (you have %d)" + +msgid "validation.text_too_short" +msgstr "🚫 Text is too short, 20 characters min (you have %d)" + +msgid "validation.prefix" +msgstr "🚫 Text must start with 🚗 or 👋" + +msgid "validation.no_at" +msgstr "🚫 No @ symbol please" + +msgid "validation.no_offensive_language" +msgstr "🚫 No bad words please 🤦" + +msgid "validation.change_from_to" +msgstr "🚫 Post again, change \"From\" and \"To\"" + +msgid "validation.empty_lines1" +msgstr "🚫 Only 2 empty lines max please (you have %d)" + +msgid "validation.empty_lines1" +msgstr "🚫 Only 9 max lines please (you have %d)" + +msgid "validation.min_lines" +msgstr "🚫 At least 5 lines please (you have %d)" + +msgid "main.welcome_link" +msgstr "https://telegra.ph/LibreTaxi-20---you-will-love-it-02-02" diff --git a/locales/all/es.po b/locales/all/es.po new file mode 100644 index 00000000..b7fed314 --- /dev/null +++ b/locales/all/es.po @@ -0,0 +1,102 @@ +msgid "init_menu.welcome" +msgstr "Bienvenido a LibreTaxi 2.0!" + +msgid "ask_location_menu.click_next" +msgstr "Pulse \"Siguiente\" (desde teléfono celular) para compartir su ubicación. O puede 📎 Clip -> 📍 Ubicación para mejor privacidad." + +msgid "ask_location_menu.next_button" +msgstr "Siguiente" + +msgid "feed_menu.greeting" +msgstr "Encontraras 🚗 conductores y 👋 pasajeros aquí." + +msgid "feed_menu.search_button" +msgstr "Encontrar 🚗 o 👋" + +msgid "feed_menu.location_button" +msgstr "📍 Cambiar ubicación" + +msgid "feed_menu.location_changed" +msgstr "👌 Ubicación actualizada" + +msgid "feed_menu.error" +msgstr "😕 No puedo entender su elección." + +msgid "post_menu.report_button" +msgstr "☝️️Reportar ⚠️" + +msgid "post_menu.wait" +msgstr "🕙 Esperar por 5 minutos" + +# Do not translate /cancel +msgid "post_menu.copy_and_paste" +msgstr "Copiar & pegar texto que empieza con 🚗 (conductor) o 👋 (pasajero) en el siguiente formato, or /cancel, ejemplos:" + +msgid "post_menu.driver_example" +msgstr "" +"🚗 Viaje ofrecido\n" +"Desde: foobar\n" +"Hasta: Aerpuerto\n" +"Fecha: hoy\n" +"Horario: ahora\n" +"Pago: efectivo, venmo" + +msgid "post_menu.passenger_example" +msgstr "" +"👋 Viaje deseado\n" +"Desde: foobar, 42\n" +"Hasta: El centro\n" +"Fecha: hoy\n" +"Horario: ahora\n" +"Pasajero: 1" + +# Here is how we check if the user just copied the text or changed it. It's just a string from the previous postings. +# Note how we have "foobar" in both postings above. It's the magic string, non-existent address, you should think +# about an address that doesn't exist in your own language. Or you can leave "foobar" if you didn't get it ;) +# Keep it lowercased! +msgid "validation.dummy_addr_lowercase" +msgstr "foobar" + +msgid "post_menu.sent" +msgstr "✅ Enviados a usuarios de hasta (25km) and to @libretaxi_all" + +# "Contact" is a verb here. For example, we'll have a posting where it says "blabla, I'm looking for ride, contact @username". +# So you're translating this verb "contact" below. +msgid "post_menu.via" +msgstr "Contactar" + +# When we have an error we say something like: +# "Your input is invalid, try again or /cancel" +# So this "or" part needs to be translated below. +msgid "post_menu.or" +msgstr "o" + +msgid "validation.text_too_long" +msgstr "🚫 El texto es muy largo, máximo 300 caracteres (tienes %d)" + +msgid "validation.text_too_short" +msgstr "🚫 El texto es muy corto, minimo 20 caracteres (tienes %d)" + +msgid "validation.prefix" +msgstr "🚫 El texto es debe empezar con 🚗 o 👋" + +msgid "validation.no_at" +msgstr "🚫 El simbolo @ no esta permitido" + +msgid "validation.no_offensive_language" +msgstr "🚫 Por favor sin malas palabras 🤦" + +msgid "validation.change_from_to" +msgstr "🚫 Publica de nuevo, cambia \"Desde\" y \"Hasta\"" + +msgid "validation.empty_lines1" +msgstr "🚫 Solo 2 líneas vacías como máximo (tienes %d)" + +msgid "validation.empty_lines1" +msgstr "🚫 Solo 9 líneas máximas por favor (tienes %d)" + +msgid "validation.min_lines" +msgstr "🚫 Al menos 5 líneas por favor (tienes %d)" + +msgid "main.welcome_link" +msgstr "https://telegra.ph/LibreTaxi-20---te-va-a-enamorar-02-09" diff --git a/locales/all/fa.po b/locales/all/fa.po new file mode 100644 index 00000000..68d41b08 --- /dev/null +++ b/locales/all/fa.po @@ -0,0 +1,102 @@ +msgid "init_menu.welcome" +msgstr "Welcome to LibreTaxi 2.0!" + +msgid "ask_location_menu.click_next" +msgstr "Click \"Next\" (from mobile phone) to share your location." + +msgid "ask_location_menu.next_button" +msgstr "Next" + +msgid "feed_menu.greeting" +msgstr "You'll see 🚗 drivers and 👋 passengers here." + +msgid "feed_menu.search_button" +msgstr "Find 🚗 or 👋" + +msgid "feed_menu.location_button" +msgstr "📍 Change location" + +msgid "feed_menu.location_changed" +msgstr "👌 Location updated" + +msgid "feed_menu.error" +msgstr "😕 Can't understand your choice" + +msgid "post_menu.report_button" +msgstr "☝️️Report ⚠️" + +msgid "post_menu.wait" +msgstr "🕙 Wait for 5 minutes" + +# Do not translate /cancel +msgid "post_menu.copy_and_paste" +msgstr "Copy & paste text starting with 🚗 (driver) or 👋 (passenger) in the following format, or /cancel, examples:" + +msgid "post_menu.driver_example" +msgstr "" +"🚗 Ride offer\n" +"From: foobar square\n" +"To: airport\n" +"Date: today\n" +"Time: now\n" +"Payment: cash, venmo" + +msgid "post_menu.passenger_example" +msgstr "" +"👋 Ride wanted\n" +"From: foobar st, 42\n" +"To: downtown\n" +"Date: today\n" +"Time: now\n" +"Pax: 1" + +# Here is how we check if the user just copied the text or changed it. It's just a string from the previous postings. +# Note how we have "foobar" in both postings above. It's the magic string, non-existent address, you should think +# about an address that doesn't exist in your own language. Or you can leave "foobar" if you didn't get it ;) +# Keep it lowercased! +msgid "validation.dummy_addr_lowercase" +msgstr "foobar" + +msgid "post_menu.sent" +msgstr "✅ Sent to users around you (25km)" + +# "Contact" is a verb here. For example, we'll have a posting where it says "blabla, I'm looking for ride, contact @username". +# So you're translating this verb "contact" below. +msgid "post_menu.via" +msgstr "Contact" + +# When we have an error we say something like: +# "Your input is invalid, try again or /cancel" +# So this "or" part needs to be translated below. +msgid "post_menu.or" +msgstr "or" + +msgid "validation.text_too_long" +msgstr "🚫 Text is too long, 300 characters max (you have %d)" + +msgid "validation.text_too_short" +msgstr "🚫 Text is too short, 20 characters min (you have %d)" + +msgid "validation.prefix" +msgstr "🚫 Text must start with 🚗 or 👋" + +msgid "validation.no_at" +msgstr "🚫 No @ symbol please" + +msgid "validation.no_offensive_language" +msgstr "🚫 No bad words please 🤦" + +msgid "validation.change_from_to" +msgstr "🚫 Post again, change \"From\" and \"To\"" + +msgid "validation.empty_lines1" +msgstr "🚫 Only 2 empty lines max please (you have %d)" + +msgid "validation.empty_lines1" +msgstr "🚫 Only 9 max lines please (you have %d)" + +msgid "validation.min_lines" +msgstr "🚫 At least 5 lines please (you have %d)" + +msgid "main.welcome_link" +msgstr "https://telegra.ph/LibreTaxi-20---you-will-love-it-02-02" diff --git a/locales/all/pt-br.po b/locales/all/pt-br.po new file mode 100644 index 00000000..1e0c7105 --- /dev/null +++ b/locales/all/pt-br.po @@ -0,0 +1,102 @@ +msgid "init_menu.welcome" +msgstr "Bemvindo a LibreTaxi 2.0!" + +msgid "ask_location_menu.click_next" +msgstr "Clicar \"Seguinte\" para partilhar localização (do telemovel) . Ou editar com 📎 Clipe -> 📍 Localização" + +msgid "ask_location_menu.next_button" +msgstr "Seguinte" + +msgid "feed_menu.greeting" +msgstr "Ofertas de 🚗 motoristas e 👋 passageiros serão publicadas aqui." + +msgid "feed_menu.search_button" +msgstr "Encontrar 🚗 ou 👋" + +msgid "feed_menu.location_button" +msgstr "📍 Actualizar localização" + +msgid "feed_menu.location_changed" +msgstr "👌 Localização actualizada" + +msgid "feed_menu.error" +msgstr "😕 Pedido não entendido" + +msgid "post_menu.report_button" +msgstr "☝️️Reportar ⚠️" + +msgid "post_menu.wait" +msgstr "🕙 Esperar 5 minutos por favor" + +# Do not translate /cancel +msgid "post_menu.copy_and_paste" +msgstr "Copiar & colar o texto començando com 🚗 (motorista) ou 👋 (passageiro) no seguinte formato, ou escrever /cancel (para anular), exemplos:" + +msgid "post_menu.driver_example" +msgstr "" +"🚗 Oferta de boleia\n" +"De: praça fulano\n" +"Para: aeroporto\n" +"Data: hoje\n" +"Hora: agora\n" +"Pagamento: cash, coins, troca,..." + +msgid "post_menu.passenger_example" +msgstr "" +"👋 Procura de boleia\n" +"De: Avenida fulano, 42\n" +"Para: Baixa\n" +"Data: hoje\n" +"Hora: agora\n" +"Pax: 2" + +# Here is how we check if the user just copied the text or changed it. It's just a string from the previous postings. +# Note how we have "foobar" in both postings above. It's the magic string, non-existent address, you should think +# about an address that doesn't exist in your own language. Or you can leave "foobar" if you didn't get it ;) +# Keep it lowercased! +msgid "validation.dummy_addr_lowercase" +msgstr "fulano" + +msgid "post_menu.sent" +msgstr "✅ Enviado para usuários na zona (25km) and to @libretaxi_all" + +# "Contact" is a verb here. For example, we'll have a posting where it says "blabla, I'm looking for ride, contact @username". +# So you're translating this verb "contact" below. +msgid "post_menu.via" +msgstr "Contactar" + +# When we have an error we say something like: +# "Your input is invalid, try again or /cancel" +# So this "or" part needs to be translated below. +msgid "post_menu.or" +msgstr "ou" + +msgid "validation.text_too_long" +msgstr "🚫 Texto demasiado longo, 300 caracteres max (tem %d)" + +msgid "validation.text_too_short" +msgstr "🚫 Texto demasiado curto, 20 caracteres min (tem %d)" + +msgid "validation.prefix" +msgstr "🚫 Texto deve começar com 🚗 ou 👋" + +msgid "validation.no_at" +msgstr "🚫 Simbolo @ não autorisado" + +msgid "validation.no_offensive_language" +msgstr "🚫 Respeito por favor! 🤦" + +msgid "validation.change_from_to" +msgstr "🚫 Recomeça por favor, mude \"De\" e \"Para\"" + +msgid "validation.empty_lines1" +msgstr "🚫 Maximo 2 linhas vazias por favor (tem %d)" + +msgid "validation.empty_lines1" +msgstr "🚫 Maximo 9 linhas por favor (tem %d)" + +msgid "validation.min_lines" +msgstr "🚫 Minimo 5 linhas por favor (tem %d)" + +msgid "main.welcome_link" +msgstr "https://telegra.ph/LibreTaxi-20---Vai-o-amar-02-12" diff --git a/locales/all/pt-pt.po b/locales/all/pt-pt.po new file mode 100644 index 00000000..1e0c7105 --- /dev/null +++ b/locales/all/pt-pt.po @@ -0,0 +1,102 @@ +msgid "init_menu.welcome" +msgstr "Bemvindo a LibreTaxi 2.0!" + +msgid "ask_location_menu.click_next" +msgstr "Clicar \"Seguinte\" para partilhar localização (do telemovel) . Ou editar com 📎 Clipe -> 📍 Localização" + +msgid "ask_location_menu.next_button" +msgstr "Seguinte" + +msgid "feed_menu.greeting" +msgstr "Ofertas de 🚗 motoristas e 👋 passageiros serão publicadas aqui." + +msgid "feed_menu.search_button" +msgstr "Encontrar 🚗 ou 👋" + +msgid "feed_menu.location_button" +msgstr "📍 Actualizar localização" + +msgid "feed_menu.location_changed" +msgstr "👌 Localização actualizada" + +msgid "feed_menu.error" +msgstr "😕 Pedido não entendido" + +msgid "post_menu.report_button" +msgstr "☝️️Reportar ⚠️" + +msgid "post_menu.wait" +msgstr "🕙 Esperar 5 minutos por favor" + +# Do not translate /cancel +msgid "post_menu.copy_and_paste" +msgstr "Copiar & colar o texto començando com 🚗 (motorista) ou 👋 (passageiro) no seguinte formato, ou escrever /cancel (para anular), exemplos:" + +msgid "post_menu.driver_example" +msgstr "" +"🚗 Oferta de boleia\n" +"De: praça fulano\n" +"Para: aeroporto\n" +"Data: hoje\n" +"Hora: agora\n" +"Pagamento: cash, coins, troca,..." + +msgid "post_menu.passenger_example" +msgstr "" +"👋 Procura de boleia\n" +"De: Avenida fulano, 42\n" +"Para: Baixa\n" +"Data: hoje\n" +"Hora: agora\n" +"Pax: 2" + +# Here is how we check if the user just copied the text or changed it. It's just a string from the previous postings. +# Note how we have "foobar" in both postings above. It's the magic string, non-existent address, you should think +# about an address that doesn't exist in your own language. Or you can leave "foobar" if you didn't get it ;) +# Keep it lowercased! +msgid "validation.dummy_addr_lowercase" +msgstr "fulano" + +msgid "post_menu.sent" +msgstr "✅ Enviado para usuários na zona (25km) and to @libretaxi_all" + +# "Contact" is a verb here. For example, we'll have a posting where it says "blabla, I'm looking for ride, contact @username". +# So you're translating this verb "contact" below. +msgid "post_menu.via" +msgstr "Contactar" + +# When we have an error we say something like: +# "Your input is invalid, try again or /cancel" +# So this "or" part needs to be translated below. +msgid "post_menu.or" +msgstr "ou" + +msgid "validation.text_too_long" +msgstr "🚫 Texto demasiado longo, 300 caracteres max (tem %d)" + +msgid "validation.text_too_short" +msgstr "🚫 Texto demasiado curto, 20 caracteres min (tem %d)" + +msgid "validation.prefix" +msgstr "🚫 Texto deve começar com 🚗 ou 👋" + +msgid "validation.no_at" +msgstr "🚫 Simbolo @ não autorisado" + +msgid "validation.no_offensive_language" +msgstr "🚫 Respeito por favor! 🤦" + +msgid "validation.change_from_to" +msgstr "🚫 Recomeça por favor, mude \"De\" e \"Para\"" + +msgid "validation.empty_lines1" +msgstr "🚫 Maximo 2 linhas vazias por favor (tem %d)" + +msgid "validation.empty_lines1" +msgstr "🚫 Maximo 9 linhas por favor (tem %d)" + +msgid "validation.min_lines" +msgstr "🚫 Minimo 5 linhas por favor (tem %d)" + +msgid "main.welcome_link" +msgstr "https://telegra.ph/LibreTaxi-20---Vai-o-amar-02-12" diff --git a/locales/all/ru.po b/locales/all/ru.po new file mode 100644 index 00000000..0b4db356 --- /dev/null +++ b/locales/all/ru.po @@ -0,0 +1,105 @@ +msgid "init_menu.welcome" +msgstr "Добро пожаловать в новую версию Либре-такси!\n" +"Исходный код: https://github.com/ro31337/libretaxi2\n" +"Запрограммировал Роман Пушкин и друзья\n" +"Лицензия: AGPL-3.0" + +msgid "ask_location_menu.click_next" +msgstr "Нажмите \"Далее\" (с мессенжера в телефоне) чтобы установить локацию. Или 📎 скрепка -> 📍 Местоположение для большей приватности." + +msgid "ask_location_menu.next_button" +msgstr "Далее" + +msgid "feed_menu.greeting" +msgstr "Тут вы увидите 🚗 водителей и 👋 пассажиров." + +msgid "feed_menu.search_button" +msgstr "Найти 🚗 или 👋" + +msgid "feed_menu.location_button" +msgstr "📍 Сменить локацию" + +msgid "feed_menu.location_changed" +msgstr "👌 Новая локация установлена" + +msgid "feed_menu.error" +msgstr "😕 Не могу понять ваш выбор" + +msgid "post_menu.report_button" +msgstr "☝️️Пожаловаться ⚠️" + +msgid "post_menu.wait" +msgstr "🕙 Подождите 5 минут" + +# Do not translate /cancel +msgid "post_menu.copy_and_paste" +msgstr "Скопируйте текст, который начинается с 🚗 (если вы водитель) или 👋 (если пассажир) и измените необходимые поля, или /cancel:" + +msgid "post_menu.driver_example" +msgstr "" +"🚗 Подвезу\n" +"Откуда: район Речного вокзала\n" +"Куда: на Дубровку\n" +"Дата: сегодня\n" +"Время: сейчас\n" +"Оплата: наличные, на карту сбер\n" + +msgid "post_menu.passenger_example" +msgstr "" +"👋 Ищу водителя\n" +"Откуда: Дубровская улица, дом 1\n" +"Куда: аэропорт\n" +"Дата: сегодня\n" +"Время: сейчас\n" +"Пассажиров: 1" + +# Here is how we check if the user just copied the text or changed it. It's just a string from the previous postings. +# Note how we have "foobar" in both postings above. It's the magic string, non-existent address, you should think +# about an address that doesn't exist in your own language. Or you can leave "foobar" if you didn't get it ;) +# Keep it lowercased! +msgid "validation.dummy_addr_lowercase" +msgstr "дубров" + +msgid "post_menu.sent" +msgstr "✅ Отправлено всем в радиусе 25 км и в @libretaxi_all" + +# "Contact" is a verb here. For example, we'll have a posting where it says "blabla, I'm looking for ride, contact @username". +# So you're translating this verb "contact" below. +msgid "post_menu.via" +msgstr "Контакт: " + +# When we have an error we say something like: +# "Your input is invalid, try again or /cancel" +# So this "or" part needs to be translated below. Important: keep space at the end! +msgid "post_menu.or" +msgstr "или" + +msgid "validation.text_too_long" +msgstr "🚫 Сообщение очень длинное, 300 букв максимум (у вас %d)" + +msgid "validation.text_too_short" +msgstr "🚫 Текст слишком короткий, 20 букв минимум (у вас %d)" + +msgid "validation.prefix" +msgstr "🚫 Текст должен начинаться с 🚗 или 👋" + +msgid "validation.no_at" +msgstr "🚫 Не указывайте символ @" + +msgid "validation.no_offensive_language" +msgstr "🚫 Уважайте культуру речи 🤦" + +msgid "validation.change_from_to" +msgstr "🚫 Еще раз, но измените \"Откуда\" и \"Куда\"" + +msgid "validation.empty_lines1" +msgstr "🚫 Две пустые строки максимум, если можно (у вас %d)" + +msgid "validation.empty_lines2" +msgstr "🚫 Девять строк максимум пожалуйста (у вас %d)" + +msgid "validation.min_lines" +msgstr "🚫 Надо хотя бы пять строк (у вас %d)" + +msgid "main.welcome_link" +msgstr "https://telegra.ph/Novaya-versiya-Libre-taksi-vam-ponravitsya-02-08" diff --git a/menu/ask_location_menu.go b/menu/ask_location_menu.go new file mode 100644 index 00000000..471cdc9a --- /dev/null +++ b/menu/ask_location_menu.go @@ -0,0 +1,52 @@ +package menu + +import ( + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "libretaxi/context" + "libretaxi/objects" + "log" +) + +type AskLocationMenuHandler struct { + user *objects.User + context *context.Context + message *tgbotapi.Message +} + +func (handler *AskLocationMenuHandler) saveLocation() { + handler.user.Lon = handler.message.Location.Longitude + handler.user.Lat = handler.message.Location.Latitude + handler.context.Repo.SaveUser(handler.user) +} + +func (handler *AskLocationMenuHandler) Handle(user *objects.User, context *context.Context, message *tgbotapi.Message) { + log.Println("Ask location menu") + + handler.user = user + handler.context = context + handler.message = message + + if message.Location != nil { + log.Printf("Saving location: %+v\n", message.Location) + handler.saveLocation() + + // update state + user.MenuId = objects.Menu_Feed + context.Repo.SaveUser(user) + return + } else { + var buttons = []tgbotapi.KeyboardButton{ + tgbotapi.NewKeyboardButtonLocation(user.Locale().Get("ask_location_menu.next_button")), + } + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("ask_location_menu.click_next")) + msg.ReplyMarkup = tgbotapi.NewReplyKeyboard(buttons) + + context.Send(msg) + } +} + +func NewAskLocationMenu() *AskLocationMenuHandler { + handler := &AskLocationMenuHandler{} + return handler +} diff --git a/menu/feed_menu.go b/menu/feed_menu.go new file mode 100644 index 00000000..69d7ed63 --- /dev/null +++ b/menu/feed_menu.go @@ -0,0 +1,64 @@ +package menu + +import ( + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "libretaxi/context" + "libretaxi/objects" + "log" +) + +type FeedMenuHandler struct { +} + +func getKeyboard(user *objects.User) tgbotapi.ReplyKeyboardMarkup { + keyboard := tgbotapi.NewReplyKeyboard( + tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton(user.Locale().Get("feed_menu.search_button")), + tgbotapi.NewKeyboardButtonLocation(user.Locale().Get("feed_menu.location_button")), + ), + ) + keyboard.OneTimeKeyboard = true + return keyboard +} + +func (handler *FeedMenuHandler) Handle(user *objects.User, context *context.Context, message *tgbotapi.Message) { + log.Println("Feed menu") + + if len(message.Text) == 0 && message.Location == nil { + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("feed_menu.greeting")) + msg.ReplyMarkup = getKeyboard(user) + + context.Send(msg) + + } else if message.Text == user.Locale().Get("feed_menu.search_button") { + + user.MenuId = objects.Menu_Post + context.Repo.SaveUser(user) + + } else if message.Location != nil { + + user.Lon = message.Location.Longitude + user.Lat = message.Location.Latitude + context.Repo.SaveUser(user) + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("feed_menu.location_changed")) + msg.ReplyMarkup = getKeyboard(user) + context.Send(msg) + + } else { + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("feed_menu.error")) + msg.ReplyMarkup = getKeyboard(user) + context.Send(msg) + + } + + //user.MenuId = objects.Menu_AskLocation + //context.Repo.SaveUser(user) +} + +func NewFeedMenu() *FeedMenuHandler { + handler := &FeedMenuHandler{} + return handler +} diff --git a/menu/init_menu.go b/menu/init_menu.go new file mode 100644 index 00000000..7e77ad7a --- /dev/null +++ b/menu/init_menu.go @@ -0,0 +1,63 @@ +package menu + +import ( + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "libretaxi/context" + "libretaxi/objects" + "libretaxi/util" + "log" +) + +type InitMenuHandler struct { + context *context.Context + user *objects.User +} + +func (handler *InitMenuHandler) postToPublicChannel() { + // post to public channel once per user, so users can't spam it with /start command + if !handler.context.Repo.ShowCallout(handler.user.UserId, "public_channel_callout_when_initialized") { + return; + } + + text := "" + + if len(handler.user.Username) == 0 { + userTextContact := fmt.Sprintf("[%s %s](tg://user?id=%d)", + util.EscapeMarkdown(handler.user.FirstName), + util.EscapeMarkdown(handler.user.LastName), + handler.user.UserId) + text = fmt.Sprintf("%s has joined LibreTaxi", userTextContact) + } else { + text = fmt.Sprintf("@%s has joined LibreTaxi", handler.user.Username) + } + + msg := tgbotapi.NewMessage(handler.context.Config.Public_Channel_Chat_Id, text) + if len(handler.user.Username) == 0 { + msg.ParseMode = "MarkdownV2" + } + handler.context.Send(msg) + handler.context.Repo.DismissCallout(handler.user.UserId, "public_channel_callout_when_initialized") +} + +func (handler *InitMenuHandler) Handle(user *objects.User, context *context.Context, message *tgbotapi.Message) { + log.Println("Init menu") + + handler.context = context + handler.user = user + + // Send welcome message + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("init_menu.welcome")) + msg.DisableWebPagePreview = true + context.Send(msg) + + user.MenuId = objects.Menu_AskLocation + context.Repo.SaveUser(user) + + handler.postToPublicChannel(); +} + +func NewInitMenu() *InitMenuHandler { + handler := &InitMenuHandler{} + return handler +} diff --git a/menu/menu.go b/menu/menu.go new file mode 100644 index 00000000..7cdc6aa4 --- /dev/null +++ b/menu/menu.go @@ -0,0 +1,108 @@ +package menu + +import ( + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "libretaxi/context" + "libretaxi/objects" + "log" +) + +type Handler interface { + Handle(user *objects.User, context *context.Context, message *tgbotapi.Message) +} + +func isStateChanged(context *context.Context, previousState objects.MenuId, userId int64) (result bool) { + user := context.Repo.FindUser(userId) + + if user == nil { + return true + } + + return user.MenuId != previousState +} + +func oneTimeMessages(context *context.Context, user *objects.User) { + // Send welcome link: on first interaction (here) or by mass-send (not implemented yet), but only once per user + if context.Repo.ShowCallout(user.UserId, "welcome_2_0_message") { + context.Repo.DismissCallout(user.UserId, "welcome_2_0_message") + + context.Send(tgbotapi.NewMessage( + user.UserId, + user.Locale().Get("main.welcome_link"))) + } +} + +func HandleMessage(context *context.Context, userId int64, message *tgbotapi.Message) { + log.Printf("Message: '%s'", message.Text) + previousState := objects.Menu_Ban + + for isStateChanged(context, previousState, userId) == true { + user := context.Repo.FindUser(userId) + + // Init user if it's not present + if user == nil { + user = &objects.User{ + UserId: userId, + MenuId: objects.Menu_Init, + ReportCnt: 0, + ShadowBanned: false, + } + } + + // Save recent user information + if message.From != nil { + + user.Username = message.From.UserName + user.FirstName = message.From.FirstName + user.LastName = message.From.LastName + user.LanguageCode = message.From.LanguageCode + + context.Repo.SaveUser(user) + } + + oneTimeMessages(context, user) + + //fmt.Printf("%+v\n", message.Location) + + if message.Text == "/start" { + user.MenuId = objects.Menu_Init + message.Text = "" + context.Repo.SaveUser(user) + } + + if message.Text == "/cancel" { + user.MenuId = objects.Menu_Feed + message.Text = "" + context.Repo.SaveUser(user) + } + + fmt.Println(user.LanguageCode) + + previousState = user.MenuId + var handler Handler + + switch user.MenuId { + case objects.Menu_Init: + handler = NewInitMenu() + case objects.Menu_AskLocation: + handler = NewAskLocationMenu() + case objects.Menu_Feed: + handler = NewFeedMenu() + case objects.Menu_Post: + handler = NewPostMenu() + default: + handler = nil + } + + if handler != nil { + handler.Handle(user, context, message) + } else { + log.Printf("Handler not implemented for menu with id %d\n", user.MenuId) + } + + // Important! We need to redefine the message as indicator it has been processed. + // Otherwise it can go into infinite loop. + message = &tgbotapi.Message{} + } +} \ No newline at end of file diff --git a/menu/post_menu.go b/menu/post_menu.go new file mode 100644 index 00000000..16ba6445 --- /dev/null +++ b/menu/post_menu.go @@ -0,0 +1,184 @@ +package menu + +import ( + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "libretaxi/context" + "libretaxi/objects" + "libretaxi/rabbit" + "libretaxi/util" + "libretaxi/validation" + "log" + "math/rand" + "strings" +) + +type PostMenuHandler struct { + user *objects.User + context *context.Context +} + +func (handler *PostMenuHandler) postToAdminChannel(text string) { + msg := tgbotapi.NewMessage(handler.context.Config.Admin_Channel_Chat_Id, text) + if len(handler.user.Username) == 0 { + msg.ParseMode = "MarkdownV2" + } + banKeyboard := tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("☝️ Shadow ban", fmt.Sprintf("{\"Action\":\"SHADOW_BAN\",\"Id\":%d}", handler.user.UserId)), + ), + ) + msg.ReplyMarkup = banKeyboard + + handler.context.Send(msg) +} + +func (handler *PostMenuHandler) postToPublicChannel(text string) { + // TODO fix line below: Error sending Telegram message: Bad Request: can't parse entities: Can't find end of Italic entity at byte offset 148 + // msg := tgbotapi.NewMessage(handler.context.Config.Public_Channel_Chat_Id, text + "\nVia 👉 @libretaxi_bot") + msg := tgbotapi.NewMessage(handler.context.Config.Public_Channel_Chat_Id, text) + if len(handler.user.Username) == 0 { + msg.ParseMode = "MarkdownV2" + } + handler.context.Send(msg) +} + +func (handler *PostMenuHandler) informUsersAround(lon float64, lat float64, text string, postId int64, user *objects.User) { + textWithContacts := "" + via := user.Locale().Get("post_menu.via") + + if len(handler.user.Username) == 0 { // use markdown + userTextContact := fmt.Sprintf("[%s %s](tg://user?id=%d)", + util.EscapeMarkdown(handler.user.FirstName), + util.EscapeMarkdown(handler.user.LastName), + handler.user.UserId) + textWithContacts = fmt.Sprintf("%s\n\n%s %s", + util.EscapeMarkdown(text), + util.EscapeMarkdown(via), + userTextContact) + } else { + textWithContacts = fmt.Sprintf("%s\n\n%s @%s", text, via, handler.user.Username) + } + + // Post to the admin channel first, do not bother in case of shadow ban + if !handler.user.ShadowBanned { + handler.postToAdminChannel(textWithContacts) + handler.postToPublicChannel(textWithContacts) + } + + // In case of shadow ban, post to current user only and return + if handler.user.ShadowBanned { + msg := tgbotapi.NewMessage(handler.user.UserId, textWithContacts) + + if len(handler.user.Username) == 0 { + msg.ParseMode = "MarkdownV2" + } + + handler.context.RabbitPublish.PublishTgMessage(rabbit.MessageBag{ + Message: msg, + PostId: postId, + Priority: 0, // lowest priority for shadow banned :-P TODO: make it everywhere + }) + return + } + + // Post to users around + userIds := handler.context.Repo.UserIdsAround(lon, lat) + + for i, _ := range userIds { + userId := userIds[i] + msg := tgbotapi.NewMessage(userId, textWithContacts) + + if len(handler.user.Username) == 0 { + // IMPORTANT! + // Currently markdown not escaped. It means when a user sends, for example "Looking for passenger(s)", + // Telegram will NOT accept this request, it will fail with + // Bad Request: can't parse entities: Character '(' is reserved and must be escaped with the preceding '\' + // TODO: always escape markdown (user input) + msg.ParseMode = "MarkdownV2" + } + + reportKeyboard := tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(user.Locale().Get("post_menu.report_button"), + fmt.Sprintf("{\"Action\":\"REPORT_POST\",\"Id\":%d}", postId)), + ), + ) + msg.ReplyMarkup = reportKeyboard + + // Mass-send with lower priority (lower than 100, more than 1). + // Random priority below is to ensure the normal distrubution of messages between multiple users at the same point of time. + handler.context.RabbitPublish.PublishTgMessage(rabbit.MessageBag{ + Message: msg, + PostId: postId, + Priority: uint8(rand.Intn(99) + 1), // random priority 1..100 + }) + } +} + +func (handler *PostMenuHandler) Handle(user *objects.User, context *context.Context, message *tgbotapi.Message) { + log.Println("Post menu") + + handler.user = user + handler.context = context + + if context.Repo.UserPostedRecently(user.UserId) { + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("post_menu.wait")) + context.Send(msg) + + user.MenuId = objects.Menu_Feed + context.Repo.SaveUser(user) + + } else if len(message.Text) == 0 { + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("post_menu.copy_and_paste")) + context.Send(msg) + + // IMPORTANT! Do not use Markdown'ish symbols here, like (, ), [, ]... because when user copies and pastes the + // message below, when username isn't set up, "informUsersAround" method above will turn message into + // markdown. If these symbols are present, it will mix up the entire message (probably won't be accepted by Telegram) + + msg = tgbotapi.NewMessage(user.UserId, user.Locale().Get("post_menu.driver_example")) + context.Send(msg) + + msg = tgbotapi.NewMessage(user.UserId, user.Locale().Get("post_menu.passenger_example")) + context.Send(msg) + } else { + + textValidation := validation.NewTextValidation() + error := textValidation.Validate(message.Text, user.Locale()) + + if len(error) > 0 { + msg := tgbotapi.NewMessage(user.UserId, error + " " + user.Locale().Get("post_menu.or") + " /cancel") + + context.Send(msg) + return + } + + cleanText := strings.TrimSpace(message.Text) + + post := &objects.Post{ + UserId: user.UserId, + Text: cleanText, + Lon: user.Lon, + Lat: user.Lat, + ReportCnt: 0, + } + + context.Repo.SavePost(post) + + go handler.informUsersAround(post.Lon, post.Lat, cleanText, post.PostId, user) + + msg := tgbotapi.NewMessage(user.UserId, user.Locale().Get("post_menu.sent")) + context.Send(msg) + + user.MenuId = objects.Menu_Feed + context.Repo.SaveUser(user) + } +} + +func NewPostMenu() *PostMenuHandler { + handler := &PostMenuHandler{} + return handler +} diff --git a/objects/post.go b/objects/post.go new file mode 100644 index 00000000..a6d1d831 --- /dev/null +++ b/objects/post.go @@ -0,0 +1,11 @@ +package objects + +type Post struct { + PostId int64 + UserId int64 + Text string + Lon float64 + Lat float64 + ReportCnt int +} + diff --git a/objects/user.go b/objects/user.go new file mode 100644 index 00000000..a1cdb0bc --- /dev/null +++ b/objects/user.go @@ -0,0 +1,41 @@ +package objects + +import "github.com/leonelquinteros/gotext" + +type MenuId int + +const ( + Menu_Init MenuId = 100 + Menu_AskLocation MenuId = 200 + Menu_Feed MenuId = 300 + Menu_Post MenuId = 400 + Menu_Ban MenuId = 999999 +) + +type User struct { + UserId int64 + MenuId MenuId + Username string + FirstName string + LastName string + Lon float64 + Lat float64 + LanguageCode string + ReportCnt int + ShadowBanned bool + locale *gotext.Locale +} + +func (u *User) Locale() *gotext.Locale { + // TODO: init locale in one transaction + if u.locale == nil { + u.locale = gotext.NewLocale("./locales", "all") + + if u.LanguageCode == "ru" || u.LanguageCode == "es" || u.LanguageCode == "pt-pt" || u.LanguageCode == "pt-br" { // ... etc + u.locale.AddDomain(u.LanguageCode) + } else { + u.locale.AddDomain("en") + } + } + return u.locale +} \ No newline at end of file diff --git a/rabbit/rabbit.go b/rabbit/rabbit.go new file mode 100644 index 00000000..a2bcdaaa --- /dev/null +++ b/rabbit/rabbit.go @@ -0,0 +1,224 @@ +/* + + IMPORTANT! + This implementation includes publishing and consuming for the same client. + Do not publish and consume for the same channel. Do not publish with one channel for multiple goroutines. + Create multiple instances with the same name. + See more here: https://github.com/streadway/amqp/issues/283 + + > Use a separate channel for publishing and if you publish from multiple goroutines, one channel per goroutine. + + Example: + + func rabbitHandler(text string) { + fmt.Printf("Got message from rabbit: '%s'\n", text) + } + + func main() { + url := "amqp://127.0.0.1/" + rabbitConsume := rabbit.NewClient(url, "test") + rabbitConsume.Connect() + rabbitConsume.RegisterHandler(rabbitHandler) + defer rabbitConsume.Close() + + rabbitPublish := rabbit.NewClient(url, "test") + rabbitPublish.Connect() + defer rabbitPublish.Close() + for i := 0; i < 10; i++ { + rabbitPublish.PublishText("hello there!") + } + } + +*/ + +package rabbit + +// https://github.com/3onyc/docker-events-amqp + +import ( + "encoding/json" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" + "github.com/streadway/amqp" + "go.uber.org/ratelimit" + "log" + "time" +) + +type RabbitClient struct { + url string + queueName string + connection *amqp.Connection + channel *amqp.Channel +} + +type Handler func(messageBag *MessageBag) + +type MessageBag struct { + PostId int64 // optional + Message tgbotapi.MessageConfig + Priority uint8 // 0..9 +} + +func (rc *RabbitClient) Connect() { + for { + var err error + + rc.connection, err = amqp.Dial(rc.url) + if err != nil { + log.Printf("Can't connect to rabbit %s, will retry after 1 sec: %s\n", rc.url, err) + time.Sleep(time.Second * 1) + continue + } + + rc.channel, err = rc.connection.Channel() + if err != nil { + rc.Close() + log.Printf("Can't create channel (connect was ok) for rabbit %s, will retry after 1 sec: %s\n", rc.url, err) + time.Sleep(time.Second * 1) + continue + } + + args := make(amqp.Table) + args["x-message-ttl"] = int32(1000 * 60 * 60 * 24 * 10) // 10 days + args["x-max-priority"] = int32(255) + + _, err = rc.channel.QueueDeclare( + rc.queueName, + true, + false, + false, + false, + args, + ) + + if err != nil { + rc.Close() + log.Printf("Can't declare queue (connect, channel were ok) for rabbit %s, will retry after 1 sec: %s\n", rc.url, err) + time.Sleep(time.Second * 1) + continue + } + + break + } +} + +func (rc *RabbitClient) PublishTgMessage(messageBag MessageBag) { + for { + body, err := json.Marshal(messageBag) + + if err != nil { + log.Println("Error marshaling a message.") + log.Println(err) + return + } + + log.Printf("Publishing %+v ...\n", string(body)) + + err = rc.channel.Publish( + "", + rc.queueName, + false, + false, + amqp.Publishing{ + DeliveryMode: amqp.Persistent, // so the message will be save on RabbitMQ restart + ContentType: "text/plain", + Body: body, + Priority: messageBag.Priority, + }) + + if err != nil { + log.Printf("Can't publish text '%s', will retry in 1 sec: %s", string(body), err) + rc.Close() + rc.Connect() + time.Sleep(time.Second * 1) + continue + } + + break + } +} + +func (rc *RabbitClient) msgRoutine(f Handler) { + var msgs <-chan amqp.Delivery + var err error + + for { + err = rc.channel.Qos( + 1, + 0, + false, + ) + + if err != nil { + log.Printf("Can't set Qos, will retry in 1 sec: %s\n", err) + rc.Close() + rc.Connect() + time.Sleep(time.Second * 1) + continue + } + + msgs, err = rc.channel.Consume( + rc.queueName, + "", + false, // important to keep false, so messages will remain in RabbitMQ on app restart + false, + false, + false, + nil, + ) + + if err != nil { + log.Printf("Can't consume from channel for url %s, will retry in 1 sec: %s\n", rc.url, err) + rc.Close() + rc.Connect() + time.Sleep(time.Second * 1) + continue + } + + break + } + + rl := ratelimit.New(28) // per second + + for d := range msgs { + + messageBag := &MessageBag{} + err := json.Unmarshal(d.Body, messageBag) + + if err != nil { + log.Println("Error unmarshalling a message") + log.Println(err) + } else { + rl.Take() // IMPORTANT! Apply rate limit here, otherwise we're screwed while mass-sending + go f(messageBag) + } + + // Ack in any case, we don't want this handler to stuck because of one error + d.Ack(false) + } +} + +func (rc *RabbitClient) RegisterHandler(f Handler) { + go rc.msgRoutine(f) +} + +func (rc *RabbitClient) Close() { + if rc.channel != nil { + rc.channel.Close() + } + if rc.connection != nil { + rc.connection.Close() + } +} + +// IMPORTANT: use `defer rabbit.Close()` to close connection + +func NewRabbitClient(url string, queueName string) *RabbitClient { + rabbit := &RabbitClient{ + url: url, + queueName: queueName, + } + rabbit.Connect() + log.Println("Successfully connected to RabbitMQ") + return rabbit +} diff --git a/repository/repository.go b/repository/repository.go new file mode 100644 index 00000000..f8726428 --- /dev/null +++ b/repository/repository.go @@ -0,0 +1,140 @@ +package repository + +import ( + "database/sql" + "libretaxi/objects" + "log" +) + +type Repository struct { + db *sql.DB +} + +func (repo *Repository) FindUser(userId int64) *objects.User { + user := &objects.User{} + + err := repo.db.QueryRow(`select "userId", "menuId", "username", "firstName", "lastName", "lon", "lat", "languageCode", "reportCnt", "shadowBanned" from users where "userId" = $1 limit 1`, + userId).Scan(&user.UserId, &user.MenuId, &user.Username, &user.FirstName, &user.LastName, &user.Lon, &user.Lat, &user.LanguageCode, &user.ReportCnt, &user.ShadowBanned) + + if err != nil { + log.Println(err) + return nil + } + + return user +} + +func (repo *Repository) SaveUser(user *objects.User) { + // Upsert syntax: https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql + // Geo populate syntax: https://gis.stackexchange.com/questions/145007/creating-geometry-from-lat-lon-in-table-using-postgis/145009 + result, err := repo.db.Query(`INSERT INTO users ("userId", "menuId", "username", "firstName", "lastName", "lon", "lat", "geog", "languageCode", "reportCnt", "shadowBanned") + VALUES ($1, $2, $3, $4, $5, $6, $7, ST_SetSRID(ST_MakePoint($7, $6), 4326), $8, $9, $10) + ON CONFLICT ("userId") DO UPDATE + SET "menuId" = $2, + "username" = $3, + "firstName" = $4, + "lastName" = $5, + "lon" = $6, + "lat" = $7, + "languageCode" = $8, + "reportCnt" = $9, + "shadowBanned" = $10, + "geog" = ST_SetSRID(ST_MakePoint($6, $7), 4326) + `, user.UserId, user.MenuId, user.Username, user.FirstName, user.LastName, user.Lon, user.Lat, user.LanguageCode, user.ReportCnt, user.ShadowBanned) + defer result.Close() + + if err != nil { + log.Println(err) + } else { + log.Println("User saved") + } +} + +func (repo *Repository) FindPost(postId int64) *objects.Post { + post := &objects.Post{} + + err := repo.db.QueryRow(`select "postId", "userId", "text", "lon", "lat", "reportCnt" from posts where "postId" = $1 limit 1`, + postId).Scan(&post.PostId, &post.UserId, &post.Text, &post.Lon, &post.Lat, &post.ReportCnt) + + if err != nil { + log.Println(err) + return nil + } + + return post +} + +func (repo *Repository) SavePost(post *objects.Post) { + err := repo.db.QueryRow(`INSERT INTO posts ("userId", "text", "lon", "lat", "geog", "reportCnt") + VALUES ($1, $2, $3, $4, ST_SetSRID(ST_MakePoint($3, $4), 4326), $5) + ON CONFLICT ("postId") DO UPDATE + SET "userId" = $1, + "text" = $2, + "lon" = $3, + "lat" = $4, + "geog" = ST_SetSRID(ST_MakePoint($3, $4), 4326), + "reportCnt" = $5 + RETURNING "postId"`, + post.UserId, post.Text, post.Lat, post.Lon, post.ReportCnt).Scan(&post.PostId) + + if err != nil { + log.Println(err) + } else { + log.Println("Post saved") + } +} + +func (repo *Repository) UserIdsAround(lon float64, lat float64) (userIds []int64) { + // select "userId", ST_Distance(c.x, "geog") AS distance from users, (SELECT ST_MakePoint(-122.415561, 37.633141)::geography) as c(x) where ST_DWithin(c.x, "geog", 25000) + result, err := repo.db.Query(`select "userId" from users, (SELECT ST_MakePoint($1, $2)::geography) as c(x) where ST_DWithin(c.x, "geog", 25000)`, + lon, lat) + defer result.Close() + + if err != nil { + log.Println(err) + return nil + } + + for result.Next() { + var userId int64 + err := result.Scan(&userId) + if err != nil { + log.Println("Error getting userId") + } else { + userIds = append(userIds, userId) + } + } + log.Printf("Found %d users around\n", len(userIds)) + return userIds +} + +func (repo *Repository) UserPostedRecently(userId int64) bool { + count := 0 + err := repo.db.QueryRow(`select count("postId") from posts where "userId" = $1 and "createdAtUtc" >= (now() at time zone 'utc') - interval '5 minutes'`, userId).Scan(&count) + if err != nil { + log.Println("Error getting the number of recent posts") + } + return count != 0 +} + +func (repo *Repository) ShowCallout(userId int64, featureName string) bool { + count := 0 + err := repo.db.QueryRow(`select count("id") from dismissed_feature_callouts where "userId" = $1 and "featureName" = $2`, userId, featureName).Scan(&count) + if err != nil { + log.Println("Error while querying dismissed feature callouts") + } + return count == 0 +} + +func (repo *Repository) DismissCallout(userId int64, featureName string) { + _, err := repo.db.Exec(`insert into dismissed_feature_callouts ("userId", "featureName") values ($1, $2) on conflict ("userId", "featureName") do nothing`, userId, featureName); + if err != nil { + log.Printf("Error while dismissing feature callout %s for user %d: %s", featureName, userId) + log.Println(err) + } +} + +func NewRepository(db *sql.DB) *Repository { + repo := &Repository{db: db} + return repo +} \ No newline at end of file diff --git a/sender/sender.go b/sender/sender.go new file mode 100644 index 00000000..720e7152 --- /dev/null +++ b/sender/sender.go @@ -0,0 +1,43 @@ +package sender + +import ( + "libretaxi/context" + "libretaxi/rabbit" + "log" +) + +type Sender struct { + context *context.Context +} + +func (s *Sender) Handler(messageBag *rabbit.MessageBag) { + log.Printf("Sending message %+v\n", messageBag.Message) + + // TODO: save message id, so we can delete it later if needed + // the following table can be used: + // + // create table if not exists posted_messages + // ( + // "toUserId" bigint not null, + // "postId" bigint not null, + // "removed" boolean default(false), + // "postedAtUtc" timestamp without time zone not null default (now() at time zone 'utc') + // ); + + _, err := s.context.Bot.Send(messageBag.Message) + if err != nil { + log.Printf("Error sending Telegram message: %s\n", err) + } +} + +func (s *Sender) Start() { + log.Println("Sender started") + s.context.RabbitConsume.RegisterHandler(s.Handler) +} + +func NewSender(context *context.Context) *Sender { + sender := &Sender{ + context: context, + } + return sender +} diff --git a/util/util.go b/util/util.go new file mode 100644 index 00000000..b6308bb7 --- /dev/null +++ b/util/util.go @@ -0,0 +1,12 @@ +package util + +import "strings" + +// Escape markdown characters: +// _ * [ ] ( ) ~ > # + - = | { } . ! +func EscapeMarkdown(str string) string { + var replacer = strings.NewReplacer("_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", + "(", "\\(", ")", "\\)", "~", "\\~", ">", "\\>", "#", "\\#", "+", "\\+", "-", + "\\-", "=", "\\=", "|", "\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!") + return replacer.Replace(str) +} diff --git a/validation/validation.go b/validation/validation.go new file mode 100644 index 00000000..1669996d --- /dev/null +++ b/validation/validation.go @@ -0,0 +1,82 @@ +package validation + +import ( + "fmt" + "github.com/leonelquinteros/gotext" + "regexp" + "strings" +) + +type TextValidation struct { + emptyCnt uint32 + totalCnt uint32 +} + +func(validation *TextValidation) Validate(text string, locale *gotext.Locale) (error string) { + if len(text) > 300 { + return fmt.Sprintf(locale.Get("validation.text_too_long"), len(text)) + } + + if len(text) < 20 { + return fmt.Sprintf(locale.Get("validation.text_too_short"), len(text)) + } + + if !strings.HasPrefix(text, "🚗") && !strings.HasPrefix(text, "👋") && !strings.HasPrefix(text, "🚘") { + return locale.Get("validation.prefix") + } + + if strings.Contains(text, "@") { + return locale.Get("validation.no_at") + } + + lowerText := strings.ToLower(text) + + if strings.Contains(lowerText, "fuck") || strings.Contains(lowerText, "хуй") || strings.Contains(lowerText, "пизда") || strings.Contains(lowerText, "блядь") { + return locale.Get("validation.no_offensive_language") + } + + if strings.Contains(lowerText, locale.Get("validation.dummy_addr_lowercase")) { + return locale.Get("validation.change_from_to") + } + + if strings.Contains(lowerText, "http") || strings.Contains(lowerText, "ftp://") || strings.Contains(lowerText,"www") { + return "🚫 No links please" + } + + var re = regexp.MustCompile(`\w\.[a-z]{2,5}`) + + if len(re.FindAllString(lowerText, -1)) > 0 { + return "🚫 No domains please" + } + + lines := strings.Split(text, "\n") + + for i := range lines { + line := strings.TrimSpace(lines[i]) + + if len(line) == 0 { + validation.emptyCnt++ + } else { + validation.totalCnt++ + } + } + + if validation.emptyCnt > 2 { + return fmt.Sprintf(locale.Get("validation.empty_lines1"), validation.emptyCnt) + } + + if validation.totalCnt > 9 { + return fmt.Sprintf(locale.Get("validation.empty_lines2"), validation.totalCnt) + } + + if validation.totalCnt < 5 { + return fmt.Sprintf(locale.Get("validation.min_lines"), validation.totalCnt) + } + + return "" +} + +func NewTextValidation() (textValidation *TextValidation) { + validation := &TextValidation{} + return validation +} \ No newline at end of file