diff --git a/api/index.html b/api/index.html index 3d8a0a9e..2eb8a43e 100644 --- a/api/index.html +++ b/api/index.html @@ -1055,6 +1055,19 @@ OrganizationsDB + +
  • @@ -1720,6 +1733,19 @@ OrganizationsDB + +
  • @@ -3514,7 +3540,7 @@

    (list): The results of the query """ sql = f"SELECT * FROM {self.table} WHERE {where}" - # print(sql) + print(sql) result = self.pg.dbcursor.execute(sql) data = dict() entry = self.pg.dbcursor.fetchone() @@ -7497,10 +7523,7 @@

    Source code in tm_admin/projects/projects.py -
    42
    -43
    -44
    -45
    +                  
    45
     46
     47
     48
    @@ -7512,7 +7535,10 @@ 

    54 55 56 -57

    def __init__(self,
    +57
    +58
    +59
    +60
    def __init__(self,
                  dburi: str = "localhost/tm_admin",
                 ):
         """
    @@ -7572,10 +7598,7 @@ 

    Source code in tm_admin/projects/projects.py -
     59
    - 60
    - 61
    - 62
    +            
     62
      63
      64
      65
    @@ -7613,7 +7636,16 @@ 

    97 98 99 -100

    def main():
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    def main():
         """This main function lets this class be run standalone by a bash script."""
         parser = argparse.ArgumentParser()
         parser.add_argument("-v", "--verbose", nargs="?", const="0", help="verbose output")
    @@ -7641,6 +7673,12 @@ 

    stream=sys.stdout, ) + gen = Generator() + x = gen.readConfig("projects/projects.yaml") + for entry in gen.yaml.yaml: + print(entry) + quit() + proj = ProjectsDB(args.uri) # user.resetSequence() all = proj.getAll() @@ -7813,31 +7851,77 @@

    -

    - - +

    + getByName -
    +

    +
    getByName(name)
    +
    +
    + +

    Return the data for the name in the table. This overrides the version +in the base class.

    -

    - main +

    Parameters:

    + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    name + str + +
    +

    The name of the dataset to retrieve.

    +
    +
    + required +
    -

    -
    main()
    -
    -
    - -

    This main function lets this class be run standalone by a bash script.

    +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + list + +
    +

    The results of the query

    +
    +
    Source code in tm_admin/organizations/organizations.py @@ -7864,21 +7948,103 @@

    75 76 77 -78 -79 -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92

    def main():
    +78
    def getByName(self,
    +            name: str,
    +            ):
    +    """
    +    Return the data for the name in the table. This overrides the version
    +    in the base class.
    +
    +    Args:
    +        name (str): The name of the dataset to retrieve.
    +
    +    Returns:
    +        (list): The results of the query
    +    """
    +    sql = f"SELECT * FROM {self.table} WHERE name='{name}' LIMIT 1"
    +    self.pg.dbcursor.execute(sql)
    +    data = dict()
    +    entry = self.pg.dbcursor.fetchone()
    +    for column in self.profile.data.keys():
    +        index = 0
    +        for column in self.profile.data.keys():
    +            data[column] = entry[index]
    +            index += 1
    +
    +    return [data]
    +
    + +
    + + + + + + + + + + + + + +
    + + + + +

    + main + + +

    +
    main()
    +
    + +
    + +

    This main function lets this class be run standalone by a bash script.

    + +
    + Source code in tm_admin/organizations/organizations.py +
     80
    + 81
    + 82
    + 83
    + 84
    + 85
    + 86
    + 87
    + 88
    + 89
    + 90
    + 91
    + 92
    + 93
    + 94
    + 95
    + 96
    + 97
    + 98
    + 99
    +100
    +101
    +102
    +103
    +104
    +105
    +106
    +107
    +108
    +109
    +110
    +111
    +112
    +113
    +114
    +115
    +116
    +117
    def main():
         """This main function lets this class be run standalone by a bash script."""
         parser = argparse.ArgumentParser()
         parser.add_argument("-v", "--verbose", nargs="?", const="0", help="verbose output")
    diff --git a/objects.inv b/objects.inv
    index 94fbfab7..15090ad2 100644
    Binary files a/objects.inv and b/objects.inv differ
    diff --git a/search/search_index.json b/search/search_index.json
    index 44985b36..5f0e2b99 100644
    --- a/search/search_index.json
    +++ b/search/search_index.json
    @@ -1 +1 @@
    -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"TM Admin","text":"

    Administrative modules for Tasking Manager style projects.

    \ud83d\udcd6 Documentation: https://hotosm.github.io/tm-admin/

    \ud83d\udda5\ufe0f Source Code: https://github.com/hotosm/tm-admin

    This is a complicated project as it involves parsing and outputting multiple file formats. This project uses gRPC for the low-level communication layer, which is below the REST API. This way it can be used by multiple other project REST APIs for exchanging data without massive refactoring of an existing API.

    The database schema is based on the ones in use in the FMTM project, which were originally based on the ones used by the HOT Tasking Manager. The schemas have years of improvements on the data requirements of Tasking Manager style projects. Not every column in a database table will be needed by each project, they can be ignored. It should be entirely possible to use a custom configuration file, but this is currently unsupported. (would love a patch for this)

    This project generates multiple files at runtime, so each is organized into a sub-directory, one for each table. The program that processes each configuration file is generator.py, which is part of this project. This reads in a configuration file in YAML format, and generates the output files for this configuration file. There is also a class Generator that can be used by other projects.

    These are the current modules supported by this project.

    • users
    • projects
    • tasks
    • organizations
    • teams
    "},{"location":"#tmadmin-manage","title":"tmadmin-manage","text":"

    The tmadmin-manage program is for higher-level data management. While each class can be run standalone, that's more for testing & development. This program is also both a standalone program, and a class that can be used by other projects. This program will create the database and tables for each module.

    "},{"location":"#datatypes","title":"Datatypes","text":"

    Each database table has it's own configuration file. There is also a top level one, types.yaml that generates the type definitions that all the other files depend on. This becomes types_tm.sql, types_tm.proto, and types_tm.py, and needs to be imported before the other files.

    "},{"location":"#yaml-files","title":".yaml files","text":"

    The YAML based config files are where everything gets defined. This way a single configuration file can be used to generate multiple output formats. In the case of this projects, that's SQL files for a local postgres database, protobuf files for gRPC, and python source files for data type definitions. There is more information on the configuration files here

    "},{"location":"#proto-files","title":".proto files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. Not every column in the database tables is in a message. The fields that get send and received are defined in the configuration file by adding share: True as a setting.

    The .proto files then have to be compiled using protoc, which generates the client and server stubs.

    "},{"location":"#sql-files","title":".sql files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. These can be executed in postgres to create the tables. The tmadmin-manage program uses these to create the database tables.

    "},{"location":"CHANGELOG/","title":"Changlog","text":""},{"location":"CHANGELOG/#unreleased","title":"Unreleased","text":""},{"location":"CHANGELOG/#fix","title":"Fix","text":"
    • Fix typo in password settings
    • Oops, add colon to tag
    • Add more columns from TM
    • Add section on the new unique keyword
    • Add more content
    • Add doc on the data flow, since there are a lot of generated files used elsewhere
    • Add support for updating records, including the enums
    • Add a unique contraint
    • Add method to reset the sequence for id
    • Query by ID name, or all rows, which is what TM needs
    • update CHANGELOG
    • Support class for managing the users table
    • Make more items be shared in messages
    • Handle datetime now
    • Nre proto file for message requests
    • Now generated classes use named parameters, which also get store in a dict
    • Delete the new generated files
    • Also generate the python stubs for data structures
    • Create the tables in the database from the generated SQL files
    • Update CHANGELOG
    • Add actual content
    • Add new files to API docs
    • Major refactoring to use YAML config file for all file generation
    • Major refactoring to use YAML config file for .sql generation
    • Major refactoring to use YAML config file for .proto generation
    • Add generated files to reduce clutter
    • Refactoring to use yaml files for file generation completed
    • Add organization section
    • Add doc on the communication details
    • Add initial content for a doc on data flow between projects
    • Add default page
    • Add doc on this project
    • Add recursive targets, since tm_admin/Makefile does all the work
    • Set version number to 0.1.0
    • Start refactoring to use our messages
    • Generate the SQL files from the YAML files
    • add one sentence about python
    • The SQL files now get generated from the YAML config files
    • Drop SQL files, they're now generated from the yaml config files
    • Add config file for organizxations table
    • Add config file for tasks table
    • Add config file for projects table
    • Always generate types_tm.* files, improve handling of sequences
    • Generate all the types_tm files
    • Add config file for all typedefs and the user table
    • Remove the generated type_tm.* files too
    • Add new file documenting the yaml based config file syntax
    • Generate SQL from yaml file
    • Generate SQL and protobuf files from yaml config file
    • Add method to convert a .proto file to a python dict
    • update services to support user profiles
    • Minimal implementation sending user profile data between client & server
    • Don't display the comments in the target
    • Add config file and use it to specify host:port for the other programs
    • Build the top level services stubs
    • add grpc dependencies
    • Improve table creation
    • Update AGPL code block
    • Move protobuf creation code to it's own file and use it
    • Add realclean target to get rid of all non source files
    • Use the protoc in grpc, not protobuf
    • Add dependencies
    • Add changelog file
    • Add target to run Doxygen
    • More files to create documentation infrastructure
    • Add Doxyfile to generate API docs
    • Update the License file
    • Add more files
    • Add the generated types* files too
    • Add default docs
    • Install the module
    • sloppy merge for new code into a real git repo
    "},{"location":"LICENSE/","title":"GNU AFFERO GENERAL PUBLIC LICENSE","text":"

    Version 3, 19 November 2007

    Copyright (C) 2007 Free Software Foundation, Inc. https://fsf.org/

    Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

    "},{"location":"LICENSE/#preamble","title":"Preamble","text":"

    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.

    "},{"location":"LICENSE/#terms-and-conditions","title":"TERMS AND CONDITIONS","text":""},{"location":"LICENSE/#0-definitions","title":"0. Definitions.","text":"

    \"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.

    "},{"location":"LICENSE/#1-source-code","title":"1. Source Code.","text":"

    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.

    "},{"location":"LICENSE/#2-basic-permissions","title":"2. Basic Permissions.","text":"

    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.

    "},{"location":"LICENSE/#3-protecting-users-legal-rights-from-anti-circumvention-law","title":"3. Protecting Users' Legal Rights From Anti-Circumvention Law.","text":"

    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.

    "},{"location":"LICENSE/#4-conveying-verbatim-copies","title":"4. Conveying Verbatim Copies.","text":"

    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.

    "},{"location":"LICENSE/#5-conveying-modified-source-versions","title":"5. Conveying Modified Source Versions.","text":"

    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.

    "},{"location":"LICENSE/#6-conveying-non-source-forms","title":"6. Conveying Non-Source Forms.","text":"

    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.

    "},{"location":"LICENSE/#7-additional-terms","title":"7. Additional Terms.","text":"

    \"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.

    "},{"location":"LICENSE/#8-termination","title":"8. Termination.","text":"

    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.

    "},{"location":"LICENSE/#9-acceptance-not-required-for-having-copies","title":"9. Acceptance Not Required for Having Copies.","text":"

    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.

    "},{"location":"LICENSE/#10-automatic-licensing-of-downstream-recipients","title":"10. Automatic Licensing of Downstream Recipients.","text":"

    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.

    "},{"location":"LICENSE/#11-patents","title":"11. Patents.","text":"

    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.

    "},{"location":"LICENSE/#12-no-surrender-of-others-freedom","title":"12. No Surrender of Others' Freedom.","text":"

    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.

    "},{"location":"LICENSE/#13-remote-network-interaction-use-with-the-gnu-general-public-license","title":"13. Remote Network Interaction; Use with the GNU General Public License.","text":"

    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.

    "},{"location":"LICENSE/#14-revised-versions-of-this-license","title":"14. Revised Versions of this License.","text":"

    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.

    "},{"location":"LICENSE/#15-disclaimer-of-warranty","title":"15. Disclaimer of Warranty.","text":"

    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.

    "},{"location":"LICENSE/#16-limitation-of-liability","title":"16. Limitation of Liability.","text":"

    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.

    "},{"location":"LICENSE/#17-interpretation-of-sections-15-and-16","title":"17. Interpretation of Sections 15 and 16.","text":"

    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

    "},{"location":"LICENSE/#how-to-apply-these-terms-to-your-new-programs","title":"How to Apply These Terms to Your New Programs","text":"

    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.

        <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n

    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 https://www.gnu.org/licenses/.

    "},{"location":"about/","title":"TM-Admin","text":"

    Administrative functions for Tasking Manager style projects. There is a lot of shared functionality between Tasking Manager style projects, so rather than having duplicate implementations, the goal of this project is to provide that functionality in a way it can be shared across multiple projects.

    These are implemented as python modules, and can be used in the backend of a Tasking Manager style website. While it is possible to have multiple projects access a single database, there is also support to exchange data between projects if they are all using their own database. There is more detail on the inter-project communication.

    "},{"location":"about/#user-management","title":"User Management","text":"

    Handles user profiles. While it is recommended, it is not required for all users to have an OSM ID. With an OSM ID, AUTH2 works, so users only have to login once, but can use multipe projects.

    "},{"location":"about/#organization-management","title":"Organization Management","text":"

    Handles organization profiles. Some organizations use multiple projects, so this just shares the profile data so it doesn't have to be entered multiple times.

    "},{"location":"about/#project-management","title":"Project Management","text":"

    Handles the project. A project in it's simplest form is an area of interest as a polygon, the name, the description, and a project manager. In addition it can access the tasks table for task specific data.

    "},{"location":"about/#task-management","title":"Task Management","text":"

    Handles the tasks. A task is a polygon within the project area of interest.

    "},{"location":"about/#team-management","title":"Team Management","text":"

    Handles OSM Teams profiles.

    "},{"location":"api/","title":"API Docs for TM-Admin","text":""},{"location":"api/#tmadmin_managepy","title":"tmadmin_manage.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage","title":"TmAdminManage","text":"
    TmAdminManage(dburi='localhost/tm_admin')\n

    Bases: object

    Source code in tm_admin/tmadmin_manage.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\"\n             ):\n    # this is for processing an SQL diff\n    self.columns = {'drop': list(), 'add': list()}\n    self.dburi = dict()\n    self.pg = None\n    if dburi:\n        self.dburi = uriParser(dburi)\n        self.pg = PostgresClient(dburi)\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.applyDiff","title":"applyDiff","text":"
    applyDiff(difffile, table)\n

    Modify a postgres database table schema

    Parameters:

    Name Type Description Default difffile str

    The filespec of the SQL diff

    required

    Returns:

    Type Description bool

    The status on applying the SQL diff

    Source code in tm_admin/tmadmin_manage.py
    def applyDiff(self,\n              difffile: str,\n              table: str,\n            ):\n    \"\"\"\n    Modify a postgres database table schema\n\n    Args:\n        difffile (str): The filespec of the SQL diff\n\n    Returns:\n        (bool): The status on applying the SQL diff\n    \"\"\"\n    self.readDiff(difffile)\n    if len(self.columns['drop']) > 0 or len(self.columns['add']) > 0:\n        return True\n\n    drop = f\"ALTER TABLE {table} DROP COLUMN\"\n    add = f\"ALTER TABLE {table} ADD COLUMN\"\n    return False\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.dump","title":"dump","text":"
    dump()\n

    Dump the internal data structures, for debugging only

    Source code in tm_admin/tmadmin_manage.py
    def dump(self):\n    \"\"\"Dump the internal data structures, for debugging only\"\"\"\n    if len(self.columns['drop']) > 0 or len(self.columns['add']) > 0:\n        print(\"Changes to the table schema\")\n        for column in self.columns['drop']:\n            print(f\"\\tDropping column {column}\")\n        for column in self.columns['add']:\n            for k, v in column.items():\n                print(f\"\\tAdding column {k} as {v}\")\n    print(\"Database parameters\")\n    for k, v in self.dburi.items():\n        if v is not None:\n            print(f\"\\t{k} = {v}\")\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.createDB","title":"createDB","text":"
    createDB(dburi=None)\n

    Create a postgres database.

    Args:

    Returns:

    Source code in tm_admin/tmadmin_manage.py
    def createDB(self,\n            dburi: str = None,\n            ):\n    \"\"\"\n    Create a postgres database.\n\n    Args:\n\n    Returns:\n\n    \"\"\"\n    # sql = \"CREATE EXTENSION IF NOT EXISTS postgis; CREATE EXTENSION IF NOT EXISTS hstore\"\n    if dburi:\n        self.dburi = uriParser(dburi)\n    # FIXME: CREATE DATABASE cannot run inside a transaction block\n    # self.pg.createDB(self.dburi)\n    with open(f\"{rootdir}/types_tm.sql\", 'r') as file:\n        self.pg.dbcursor.execute(file.read())\n        file.close()\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.createTable","title":"createTable","text":"
    createTable(sqlfile)\n

    Create a table in the database.

    Parameters:

    Name Type Description Default sqlfile str

    The SQL schema for this table

    required dburi str

    The URI string for the database connection.

    required

    Returns:

    Type Description bool

    The table creation status

    Source code in tm_admin/tmadmin_manage.py
    def createTable(self,\n                sqlfile: str,\n                ):\n    \"\"\"\n    Create a table in the database.\n\n    Args:\n        sqlfile (str): The SQL schema for this table\n        dburi (str): The URI string for the database connection.\n\n    Returns:\n        (bool): The table creation status\n    \"\"\"\n    sql = \"\"\n    with open(sqlfile, 'r') as file:\n        # cleanup the file before submitting\n        for line in file.readlines():\n            if line[:2] != '--' and len(line) > 0:\n                sql += line\n        file.close()\n        return self.pg.createTable(sql)\n\n    path = Path(sqlfile)\n    version = f\"INSERT INTO schemas(schema, version) VALUES('{sqlfile.stem}', 1.0)\"\n    result = self.pg.dbcursor.execute(version)\n\n    return sql\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.readDiff","title":"readDiff","text":"
    readDiff(diff)\n

    Read in a diff produced by git diff into a data structure that can be used to updgrade a table's schema.

    Parameters:

    Name Type Description Default diff str

    the name of the SQL diff file

    required

    Returns:

    Type Description dict

    The columns to drop or add from a table

    Source code in tm_admin/tmadmin_manage.py
    def readDiff(self,\n             diff: str,\n             ):\n    \"\"\"\n    Read in a diff produced by git diff into a data structure\n    that can be used to updgrade a table's schema.\n\n    Args:\n        diff (str): the name of the SQL diff file\n\n    Returns:\n        (dict): The columns to drop or add from a table\n    \"\"\"\n    with open(diff, 'r') as file:\n        for line in file.readlines():\n            # it's the header\n            if line[:3] == '---' or line[:3] == '+++' or  line[:2] == '@@':\n                continue\n            # Ignore code block\n            if line[0] == ' ':\n                continue\n            tmp = ' '.join(line.split()).split()\n            if tmp[0] == '-':\n                self.columns['drop'].append(tmp[1])\n            if tmp[0] == '+':\n                if tmp[1] in self.columns['drop']:\n                    self.columns['drop'].remove(tmp[1])\n                    continue\n                if len(tmp) == 3:\n                    self.columns['add'].append({tmp[1]: tmp[2][:-1]})\n                elif len(tmp) == 4:\n                    self.columns['add'].append({tmp[1]: f\"{tmp[2]} {tmp[3][:-1]}\"})\n    return self.columns\n
    "},{"location":"api/#tm_admin.tmadmin_manage.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tmadmin_manage.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"config\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Manage the postgres database for the tm-admin project\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    choices = ['create', 'migrate']\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    # parser.add_argument(\"-d\", \"--diff\", help=\"SQL file diff for migrations\")\n    # parser.add_argument(\"-p\", \"--proto\", help=\"Generate the .proto file from the YAML file\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    parser.add_argument(\"-c\", \"--cmd\", choices=choices, default='create',\n                            help=\"Command\")\n    args, known = parser.parse_known_args()\n\n    if len(argv) <= 1:\n        parser.print_help()\n        quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    # The base class that does all the work\n    tm = TmAdminManage(args.uri)\n    tm.createDB()\n\n    # This database tables stores the versions of the table schemas,\n    # and is only used for updating the table schemas.\n    result = tm.createTable(f\"{rootdir}/schemas.sql\")\n\n    # This class generates all the output files.\n    gen = Generator()\n\n    for yamlfile in known:\n        gen.readConfig(yamlfile)\n        out = gen.createSQLTable()\n        name = yamlfile.replace('.yaml', '.sql')\n        with open(name, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {name} to disk\")\n            file.close()\n        tm.createTable(name)\n        name = yamlfile.replace('.yaml', '.proto')\n        out = gen.createProtoMessage()\n        with open(name, 'w') as file:\n            file.writelines([str(i)+'\\n' for i in out])\n            log.info(f\"Wrote {name} to disk\")\n            file.close()\n        out = gen.createPyClass()\n        py = yamlfile.replace('.yaml', '_class.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n        out = gen.createPyMessage()\n        py = yamlfile.replace('.yaml', '_proto.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n
    "},{"location":"api/#dbsupportpy","title":"dbsupport.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.dbsupport.DBSupport","title":"DBSupport","text":"
    DBSupport(table, dburi='localhost/tm_admin')\n

    Bases: object

    Parameters:

    Name Type Description Default table str

    The table to use for this connection.

    required dburi str

    The URI string for the database connection.

    'localhost/tm_admin'

    Returns:

    Type Description DBSupport

    An instance of this class

    Source code in tm_admin/dbsupport.py
    def __init__(self,\n             table: str,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A base class since all tables have the same structure for queries.\n\n    Args:\n        table (str): The table to use for this connection.\n        dburi (str): The URI string for the database connection.\n\n    Returns:\n        (DBSupport): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.table = table\n    profile = f\"{table.capitalize()}Table()\"\n    self.profile = eval(profile)\n    if dburi:\n        self.pg = PostgresClient(dburi)\n    self.types = dir(tm_admin.types_tm)\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.createTable","title":"createTable","text":"
    createTable(obj)\n

    Create a table in a postgres database.

    Parameters:

    Name Type Description Default obj

    The config data for the table.

    required Source code in tm_admin/dbsupport.py
    def createTable(self,\n                obj,\n                ):\n    \"\"\"\n    Create a table in a postgres database.\n\n    Args:\n        obj: The config data for the table.\n    \"\"\"\n    sql = f\"INSERT INTO {self.table}(id, \"\n    for column,value in obj.data.items():\n        # print(f\"{column} is {type(value)}\")\n        if type(value) == str:\n            # FIXME: for now ignore timestamps, as they're meaningless\n            # between projects\n            try:\n                if parse(value):\n                    continue\n            except:\n                # it's a string, but not a date\n                pass\n        if value is not None:\n            sql += f\"{column},\"\n    sql = sql[:-1]\n    sql += f\") VALUES(\"\n    for column,value in obj.data.items():\n        try:\n            if parse(value):\n                continue\n        except:\n            pass\n        if column == 'id':\n            sql += f\"nextval('public.{self.table}_id_seq'),\"\n            continue\n        if value is None:\n            continue\n        elif type(value) == datetime:\n            continue\n        elif type(value) == int:\n            sql += f\"{value},\"\n        elif type(value) == bool:\n            if value:\n                sql += f\"true,\"\n            else:\n                sql += f\"false,\"\n        elif type(value) == str:\n            sql += f\"'{value}',\"\n\n    #print(sql[:-1])\n    result = self.pg.dbcursor.execute(f\"{sql[:-1]});\")\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.updateTable","title":"updateTable","text":"
    updateTable(id=None)\n

    Updates an existing table in the database

    Parameters:

    Name Type Description Default id int

    The ID of the dataset to update

    None Source code in tm_admin/dbsupport.py
    def updateTable(self,\n                id: int = None,\n                ):\n    \"\"\"\n    Updates an existing table in the database\n\n    Args:\n        id (int): The ID of the dataset to update\n    \"\"\"\n    sql = f\"UPDATE {self.table} SET\"\n    if not id:\n        id = profile.data['id']\n    for column,value in self.profile.data.items():\n        name = column.replace('_', '').capitalize()\n        if name in self.types:\n            # FIXME: this needs to not be hardcoded!\n            tmp = tm_admin.types_tm.Mappinglevel._member_names_\n            if type(value) == str:\n                level = value\n            else:\n                level = tmp[value-1]\n            sql += f\" {column}='{level}'\"\n            continue\n        if value:\n            try:\n                # FIXME: for now ignore timestamps, as they're meaningless\n                # between projects\n                if parse(value):\n                    continue\n            except:\n                # it's a string, but not a date\n                pass\n            sql += f\" {column}='{value}',\"\n    sql += f\" WHERE id='{id}'\"\n    # print(sql)\n    result = self.pg.dbcursor.execute(f\"{sql[:-1]}';\")\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.resetSequence","title":"resetSequence","text":"
    resetSequence()\n

    Reset the postgres sequence to zero.

    Source code in tm_admin/dbsupport.py
    def resetSequence(self):\n    \"\"\"\n    Reset the postgres sequence to zero.\n    \"\"\"\n    sql = f\"ALTER SEQUENCE public.{self.table}_id_seq RESTART;\"\n    self.pg.dbcursor.execute(sql)\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByID","title":"getByID","text":"
    getByID(id)\n

    Return the data for the ID in the table.

    Parameters:

    Name Type Description Default id int

    The ID of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByID(self,\n            id: int,\n            ):\n    \"\"\"\n    Return the data for the ID in the table.\n\n    Args:\n        id (int): The ID of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE id='{id}'\"\n    result = self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    if entry:\n        for column in self.profile.data.keys():\n            index = 0\n            for column in self.profile.data.keys():\n                data[column] = entry[index]\n                index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByName","title":"getByName","text":"
    getByName(name)\n

    Return the data for the name in the table.

    Parameters:

    Name Type Description Default name str

    The name of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByName(self,\n            name: str,\n            ):\n    \"\"\"\n    Return the data for the name in the table.\n\n    Args:\n        name (str): The name of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE username='{name}' LIMIT 1\"\n    self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    for column in self.profile.data.keys():\n        index = 0\n        for column in self.profile.data.keys():\n            data[column] = entry[index]\n            index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getAll","title":"getAll","text":"
    getAll()\n

    Return all the data in the table.

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getAll(self):\n    \"\"\"\n    Return all the data in the table.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table};\"\n    self.pg.dbcursor.execute(sql)\n    result = self.pg.dbcursor.fetchall()\n    out = list()\n    if result:\n        for entry in result:\n            data = dict()\n            for column in self.profile.data.keys():\n                index = 0\n                for column in self.profile.data.keys():\n                    data[column] = entry[index]\n                    index += 1\n            out.append(data)\n    else:\n        log.debug(f\"No data returned from query\")\n\n    return out\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByWhere","title":"getByWhere","text":"
    getByWhere(where)\n

    Return the data for the where clause in the table.

    Parameters:

    Name Type Description Default where str

    The where clzuse of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByWhere(self,\n            where: str,\n            ):\n    \"\"\"\n    Return the data for the where clause in the table.\n\n    Args:\n        where (str): The where clzuse of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE {where}\"\n    # print(sql)\n    result = self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    if entry:\n        for column in self.profile.data.keys():\n            index = 0\n            for column in self.profile.data.keys():\n                data[column] = entry[index]\n                index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByLocation","title":"getByLocation","text":"
    getByLocation(location, table='projects')\n

    Return the database records in a table using GPS coordinates.

    Parameters:

    Name Type Description Default location Point

    The location to use to find the project or task.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByLocation(self,\n            location: Point,\n            table: str = 'projects',\n            ):\n    \"\"\"\n    Return the database records in a table using GPS coordinates.\n\n    Args:\n        location (Point): The location to use to find the project or task.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    data = dict()\n    ewkt = shape(location)\n    sql = f\"SELECT * FROM {table} WHERE ST_CONTAINS(ST_GeomFromEWKT('SRID=4326;{ewkt}') geom)\"\n    self.pg.dbcursor.execute(sql)\n    entry = self.pg.dbcursor.fetchall()\n    for column in self.profile.data.keys():\n        index = 0\n        for column in self.profile.data.keys():\n            data[column] = entry[index]\n            index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.deleteByID","title":"deleteByID","text":"
    deleteByID(id)\n

    Delete the record for the ID in the table.

    Parameters:

    Name Type Description Default id int

    The ID of the dataset to delete.

    required Source code in tm_admin/dbsupport.py
    def deleteByID(self,\n            id: int,\n            ):\n    \"\"\"\n    Delete the record for the ID in the table.\n\n    Args:\n        id (int): The ID of the dataset to delete.\n    \"\"\"\n    sql = f\"DELETE FROM {self.table} WHERE id='{id}'\"\n    result = self.pg.dbcursor.execute(sql)\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.updateColumn","title":"updateColumn","text":"
    updateColumn(id, data)\n

    This updates a single column in the database. If you want to update multiple columns, use self.updateTable() instead.

    Parameters:

    Name Type Description Default id int

    The ID of the user to update

    required data dict

    The column and new value

    required Source code in tm_admin/dbsupport.py
    def updateColumn(self,\n                id: int,\n                data: dict,\n                ):\n    \"\"\"\n    This updates a single column in the database. If you want to update multiple columns,\n    use self.updateTable() instead.\n\n    Args:\n        id (int): The ID of the user to update\n        data (dict): The column and new value\n    \"\"\"\n    [[column, value]] = data.items()\n    sql = f\"UPDATE {self.table} SET {column}='{value}' WHERE id='{id}'\"\n    # print(sql)\n    try:\n        result = self.pg.dbcursor.execute(f\"{sql};\")\n        return True\n    except:\n        return False\n
    "},{"location":"api/#tm_admin.dbsupport.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/dbsupport.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    org = DBSupport('organizations', args.uri)\n    # organization.resetSequence()\n    all = org.getAll()\n\n    # Don't pass id, let postgres auto increment\n    ut = OrganizationsTable(name='test org', slug=\"slug\", orgtype=1)\n#                            orgtype=tm_admin.types_tm.Organizationtype.FREE)\n    org.createTable(ut)\n    # print(all)\n\n    all = org.getByID(1)\n    print(all)\n\n    all = org.getByName('fixme')\n    print(all)\n
    "},{"location":"api/#generatorpy","title":"generator.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.generator.Generator","title":"Generator","text":"
    Generator(filespec=None)\n

    Bases: object

    Parameters:

    Name Type Description Default filespec str

    The config file to use as source.

    None

    Returns:

    Type Description Generator

    An instance of this class

    Source code in tm_admin/generator.py
    def __init__(self,\n            filespec: str = None,\n            ):\n    \"\"\"\n    A class that generates the output files from the config data.\n\n    Args:\n        filespec (str): The config file to use as source.\n\n    Returns:\n        (Generator): An instance of this class\n    \"\"\"\n    self.filespec = None\n    self.yaml = None\n    if filespec:\n        self.filespec = Path(filespec)\n        self.yaml = YamlFile(filespec)\n    self.createTypes()\n    self.yaml2py = {'int32': 'int',\n                'int64': 'int',\n                'bool': 'bool',\n                'string': 'str',\n                'bytes': 'bytes',\n                'timestamp': 'timestamp without time zone',\n                'polygon': 'Polygon',\n                'point': 'Point',\n                }\n\n    self.yaml2sql = {'int32': 'int',\n                'int64': 'bigint',\n                'bool': 'bool',\n                'string': 'character varying',\n                'bytes': 'bytea',\n                'timestamp': 'timestamp without time zone',\n                'polygon': 'polygon',\n                'point': 'point',\n                }\n
    "},{"location":"api/#tm_admin.generator.Generator.readConfig","title":"readConfig","text":"
    readConfig(filespec)\n

    Reads in the YAML config file.

    Parameters:

    Name Type Description Default filespec str

    The config file to use as source.

    required Source code in tm_admin/generator.py
    def readConfig(self,\n                filespec: str,\n                ):\n    \"\"\"\n    Reads in the YAML config file.\n\n    Args:\n        filespec (str): The config file to use as source.\n    \"\"\"\n    self.filespec = Path(filespec)\n    self.yaml = YamlFile(filespec)\n
    "},{"location":"api/#tm_admin.generator.Generator.createTypes","title":"createTypes","text":"
    createTypes()\n

    Creates the enum files, which need to be done first, since the other generated files reference these.

    Source code in tm_admin/generator.py
    def createTypes(self):\n    \"\"\"\n    Creates the enum files, which need to be done first, since the\n    other generated files reference these.\n    \"\"\"\n    gen = self.readConfig(f'{rootdir}/types.yaml')\n    out = self.createSQLEnums()\n    with open('types_tm.sql', 'w') as file:\n        file.write(out)\n        file.close()\n    out = self.createProtoEnums()\n    with open('types_tm.proto', 'w') as file:\n        file.write(out)\n        file.close()\n    out = self.createPyEnums()\n    with open('types_tm.py', 'w') as file:\n        file.write(out)\n        file.close()\n
    "},{"location":"api/#tm_admin.generator.Generator.createSQLEnums","title":"createSQLEnums","text":"
    createSQLEnums()\n

    Create an input file for postgres of the custom types.

    Returns:

    Type Description str

    The source for postgres to create the SQL types.

    Source code in tm_admin/generator.py
    def createSQLEnums(self):\n    \"\"\"\n    Create an input file for postgres of the custom types.\n\n    Returns:\n        (str): The source for postgres to create the SQL types.\n    \"\"\"\n    out = \"\"\n    for entry in self.yaml.yaml:\n        [[table, values]] = entry.items()\n        out += f\"DROP TYPE IF EXISTS public.{table} CASCADE;\\n\"\n        out += f\"CREATE TYPE public.{table} AS ENUM (\\n\"\n        for line in values:\n            out += f\"\\t'{line}',\\n\"\n        out = out[:-2]\n        out += \"\\n);\\n\"\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createProtoEnums","title":"createProtoEnums","text":"
    createProtoEnums()\n

    Create an input file for postgres of the custom types.

    Returns:

    Type Description str

    The source for protoc to create the Protobuf types.

    Source code in tm_admin/generator.py
    def createProtoEnums(self):\n    \"\"\"\n    Create an input file for postgres of the custom types.\n\n    Returns:\n        (str): The source for protoc to create the Protobuf types.\n    \"\"\"\n    out = \"syntax = 'proto3';\\n\\n\"\n    for entry in self.yaml.yaml:\n        index = 0\n        [[table, values]] = entry.items()\n        out += f\"enum {table.capitalize()} {{\\n\"\n        for line in values:\n            out += f\"\\t{line} = {index};\\n\"\n            index += 1\n        out += \"};\\n\\n\"\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createPyEnums","title":"createPyEnums","text":"
    createPyEnums()\n

    Create an input file for python of the custom types.

    Returns:

    Type Description str

    The source for python to create the enums.

    Source code in tm_admin/generator.py
    def createPyEnums(self):\n    \"\"\"\n    Create an input file for python of the custom types.\n\n    Returns:\n        (str): The source for python to create the enums.\n    \"\"\"\n    out = f\"import logging\\n\"\n    out += f\"from enum import IntEnum\\n\"\n    for entry in self.yaml.yaml:\n        index = 1\n        [[table, values]] = entry.items()\n        out += f\"class {table.capitalize()}(IntEnum):\\n\"\n        for line in values:\n            out += f\"\\t{line} = {index}\\n\"\n            index += 1\n        out += '\\n'\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createPyMessage","title":"createPyMessage","text":"
    createPyMessage()\n

    Creates a python class wrapper for protobuf.

    Returns:

    Type Description str

    The source for python to create the class stubs.

    Source code in tm_admin/generator.py
        def createPyMessage(self):\n        \"\"\"\n        Creates a python class wrapper for protobuf.\n\n        Returns:\n            (str): The source for python to create the class stubs.\n        \"\"\"\n        out = f\"\"\"\nimport logging\nfrom datetime import timedelta\nfrom shapely.geometry import Polygon, Point, shape\n\nlog = logging.getLogger(__name__)\n        \"\"\"\n        for entry in self.yaml.yaml:\n            [[table, settings]] = entry.items()\n            out += f\"\"\"\nclass {table.capitalize()}Message(object):\n    def __init__(self, \n            \"\"\"\n            # print(table, settings)\n            share = False\n            datatype = None\n            data = \"        self.data = {\"\n            for item in settings:\n                if type(item) == dict:\n                    [[k, v]] = item.items()\n                    for k1 in v:\n                        if type(k1) == dict:\n                            [[k2, v2]] = k1.items()\n                            if k2 == 'share' and v2:\n                                share = True\n                                # out += f\"\\nshare {k1}\"\n                        elif type(k1) == str:\n                            if k1 in self.yaml2py:\n                                datatype = self.yaml2py[k1]\n                            else:\n                                datatype = item\n                                continue\n                    if share:\n                        share = False\n                        out += f\"{k}: {datatype} = None, \"\n                        data += f\"'{k}': {k}, \"\n        out += \"):\\n\"\n        out += f\"{data[:-2]}}}\\n\"\n\n        return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createPyClass","title":"createPyClass","text":"
    createPyClass()\n

    Creates a python class wrapper for the protobuf messages.

    Returns:

    Type Description str

    The source for python to create the class stubs.

    Source code in tm_admin/generator.py
        def createPyClass(self):\n        \"\"\"\n        Creates a python class wrapper for the protobuf messages.\n\n        Returns:\n            (str): The source for python to create the class stubs.\n        \"\"\"\n        out = f\"\"\"\nimport logging\nfrom datetime import datetime\nimport tm_admin.types_tm\nfrom shapely.geometry import Point, LineString, Polygon\n\nlog = logging.getLogger(__name__)\n\n        \"\"\"\n        for entry in self.yaml.yaml:\n            [[table, settings]] = entry.items()\n            out += f\"\"\"\nclass {table.capitalize()}Table(object):\n    def __init__(self, \n            \"\"\"\n            datatype = None\n            now = datetime.now()\n            data = \"            self.data = {\"\n            for item in settings:\n                if type(item) == dict:\n                    [[k, v]] = item.items()\n                    for k1 in v:\n                        if type(k1) == dict:\n                            continue\n                        elif type(k1) == str:\n                            if k1[:15] == 'public.geometry':\n                                datatype = k1[16:-1].split(',')[0]\n                                log.warning(f\"GEOMETRY: {datatype}\")\n                            elif k1[:7] == 'public.':\n                                # FIXME: It's in the SQL types\n                                # log.warning(f\"SQL ENUM {k1}!\")\n                                datatype = f\"tm_admin.types_tm.{k1[7:].capitalize()}\"\n                            elif k1 in self.yaml2py:\n                                datatype = self.yaml2py[k1]\n                            else:\n                                datatype = item\n                                continue\n                        if k1 == 'bool':\n                            out += f\"{k}: {datatype} = False, \"\n                        elif k1 == 'timestamp':\n                            out += f\"{k}: datetime = '{datetime.now()}', \"\n                        elif k1[:7] == 'public.':\n                            # defined = f\"tm_admin.types_tm.{k1[7:].capitalize()}()\"\n                            # out += f\"{k}: {defined} =  1, \"\n                            out += f\"{k}: int =  1, \"\n                        else:\n                            out += f\"{k}: {datatype} = None, \"\n                        # print(k)\n                        data += f\"'{k}': {k}, \"\n        out = out[:-2]\n        out += \"):\\n\"\n        out += f\"{data[:-2]}}}\\n\"\n\n        return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createProtoMessage","title":"createProtoMessage","text":"
    createProtoMessage()\n

    Create the source for a protobuf message

    Returns:

    Type Description list

    The protobuf message source.

    Source code in tm_admin/generator.py
    def createProtoMessage(self):\n    \"\"\"\n    Create the source for a protobuf message\n\n    Returns:\n        (list): The protobuf message source.\n    \"\"\"\n    pb = ProtoBuf()\n    out = pb.createTableProto(self.yaml.yaml)\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createSQLTable","title":"createSQLTable","text":"
    createSQLTable()\n

    Create the source for an SQL table.

    Returns:

    Type Description str

    The protobuf message source.

    Source code in tm_admin/generator.py
        def createSQLTable(self):\n        \"\"\"\n        Create the source for an SQL table.\n\n        Returns:\n            (str): The protobuf message source.\n        \"\"\"\n        out = \"-- Do not edit this file, it's generated from the yaml file\\n\\n\"\n        sequence = list()\n        for entry in self.yaml.yaml:\n            [[table, values]] = entry.items()\n            out += f\"DROP TABLE IF EXISTS public.{table} CASCADE;\\n\"\n            out += f\"CREATE TABLE public.{table} (\\n\"\n            unique = \"\"\n            typedef = \"\"\n            for line in values:\n                # these are usually from the types.yaml file, which have no\n                # settings beyond the enum value.\n                # if type(line) == str:\n                #     print(f\"SQL TABLE: {typedef} {line}\")\n                #     typedef = table\n                #     continue\n                [[k, v]] = line.items()\n                required = \"\"\n                array = \"\"\n                public = False\n                primary = \"\"\n                for item in v:\n                    if type(item) == dict:\n                        if 'sequence' in item and item['sequence']:\n                            sequence.append(k)\n                            primary = k\n                        if 'required' in item and item['required']:\n                            required = ' NOT NULL'\n                        if 'array' in item and item['array']:\n                            array = \"[]\"\n                        if 'unique' in item and item['unique']:\n                            unique = k\n                    if len(v) >= 2:\n                        if 'required' in v[1] and v[1]['required']:\n                            required = ' NOT NULL'\n                    if type(item) == str:\n                        if item[:7] == 'public.' and item[15:8] != 'geometry':\n                            public = True\n                        # elif item[15:8] == 'geometry':\n                        #     out += f\"\\t{k} {self.yaml2py[v[0]]}{array}{required},\\n\"\n                if public:\n                    out += f\"\\t{k} {v[0]}{array}{required},\\n\"\n                else:\n                    # print(v)\n                    # FIXME: if this produces an error, check the yaml file as this\n                    # usually means the type field isn't first in the list.\n                    out += f\"\\t{k} {self.yaml2sql[v[0]]}{array}{required},\\n\"\n            if len(unique) > 0:\n                out += f\"\\tUNIQUE({unique})\\n);\\n\"\n\n            if len(sequence) > 0:\n                for key in sequence:\n                    out += f\"\"\"\nDROP SEQUENCE IF EXISTS public.{table}_{key}_seq CASCADE;\nCREATE SEQUENCE public.{table}_{key}_seq\n        START WITH 1\n        INCREMENT BY 1\n        NO MINVALUE\n        NO MAXVALUE\n        CACHE 1;\n\"\"\"\n        return out\n
    "},{"location":"api/#tm_admin.generator.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/generator.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"generator\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Generate SQL, Protobuf, and Python data structures\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    args, known = parser.parse_known_args()\n\n    if len(argv) <= 1:\n        parser.print_help()\n        quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    gen = Generator()\n    for config in known:\n        gen.readConfig(config)\n        out = gen.createSQLTable()\n        sqlfile = config.replace('.yaml', '.sql')\n        path = Path(sqlfile)\n        #if path.exists():\n        #    path.rename(file.replace('.sql', '_bak.sql'))\n        with open(sqlfile, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {sqlfile} to disk\")\n            file.close()\n        proto = config.replace('.yaml', '.proto')\n        out = gen.createProtoMessage()\n        with open(proto, 'w') as file:\n            file.writelines([str(i)+'\\n' for i in out])\n            log.info(f\"Wrote {proto} to disk\")\n            file.close()\n\n        out = gen.createPyClass()\n        py = config.replace('.yaml', '_class.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n        # print(out)\n        out = gen.createPyMessage()\n        py = config.replace('.yaml', '_proto.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n
    "},{"location":"api/#protopy","title":"proto.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.proto.ProtoBuf","title":"ProtoBuf","text":"
    ProtoBuf(sqlfile=None)\n

    Bases: object

    Returns:

    Type Description ProtoBuf

    An instance of this class

    Source code in tm_admin/proto.py
    def __init__(self,\n            sqlfile: str = None,\n            ):\n    \"\"\"\n    A class that generates protobuf files from the config data.\n\n    Returns:\n        (ProtoBuf): An instance of this class\n    \"\"\"\n    self.sqlfile = sqlfile\n
    "},{"location":"api/#tm_admin.proto.ProtoBuf.createEnumProto","title":"createEnumProto","text":"
    createEnumProto(enums)\n

    Process a list of enums into the protobuf version.

    Parameters:

    Name Type Description Default enums dict

    The list of tables to generate a protobuf for.

    required

    Returns:

    Type Description list

    The list of enums in protobuf format

    Source code in tm_admin/proto.py
    def createEnumProto(self,\n                enums: dict,\n                ):\n    \"\"\"\n    Process a list of enums into the protobuf version.\n\n    Args:\n        enums (dict): The list of tables to generate a protobuf for.\n\n    Returns:\n        (list): The list of enums in protobuf format\n    \"\"\"\n    out = list()\n    out.append(f\"syntax = 'proto3';\")\n    for name, value in enums.items():\n        index = 0\n        out.append(f\"enum {name.capitalize()} {{\")\n        for entry in value:\n            out.append(f\"\\t{entry} = {index};\")\n            index += 1\n        out.append('};')\n\n    return out\n
    "},{"location":"api/#tm_admin.proto.ProtoBuf.createTableProto","title":"createTableProto","text":"
    createTableProto(tables)\n

    Process a list of tables into the protobuf version.

    Parameters:

    Name Type Description Default tables list

    The list of tables to generate a protobuf for.

    required

    Returns:

    Type Description list

    The list of tables in protobuf format

    Source code in tm_admin/proto.py
    def createTableProto(self,\n                tables: list,\n                ):\n    \"\"\"\n    Process a list of tables into the protobuf version.\n\n    Args:\n        tables (list): The list of tables to generate a protobuf for.\n\n    Returns:\n        (list): The list of tables in protobuf format\n    \"\"\"\n    out = list()\n    out.append(f\"syntax = 'proto3';\")\n    # types.proto is generated from the types.yaml file.\n    # out.append(\"import 'types_tm.proto';\")\n    out.append(\"package tmadmin;\")\n    out.append(\"import 'types_tm.proto';\")\n    out.append(\"import 'google/protobuf/timestamp.proto';\")\n\n    convert = {'timestamp': \"google.protobuf.Timestamp\",\n               'polygon': 'bytes', 'point': 'bytes'}\n    for table in tables:\n        index = 1\n        for key, value in table.items():\n            out.append(f\"message {key} {{\")\n            optional = \"\"\n            repeated = \"\"\n            for data in value:\n                # print(f\"DATA: {data}\")\n                for entry, settings in data.items():\n                    # print(f\"DATA: {entry} = {settings}\")\n                    #    datatype = settings[0][7:].capitalize()\n                    share = False\n                    array = \"\"\n                    datatype = None\n                    required = \"\"\n                    optional = \"\"\n                    for item in settings:\n                        if type(item) == str:\n                            # print(f\"DATA: {item}\")\n                            if item[:15] == 'public.geometry':\n                                datatype = \"bytes\"\n                            elif item[:7] == 'public.':\n                                datatype = item[7:].capitalize()\n                            elif item in convert:\n                                datatype = convert[item]\n                            else:\n                                datatype = item\n                            continue\n                        if type(item) == dict:\n                            [[k, v]] = item.items()\n                            if k == 'required' and v:\n                                required = k\n                            if k == 'optional' and v:\n                                optional = k\n                            if k == 'share':\n                                share = True\n                            if k == 'array':\n                                array = \"repeated\"\n                    if not share:\n                        continue\n                    # out.append(f\"\\t{required} {optional} {datatype} {entry} = {index};\")\n                    out.append(f\"\\t {array} {optional} {datatype} {entry} = {index};\")\n                    index += 1\n        out.append(f\"}}\")\n\n    return out\n
    "},{"location":"api/#tm_admin.proto.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/proto.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"config\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Manage the postgres database for the tm-admin project\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    args, known = parser.parse_known_args()\n\n    if len(argv) <= 1:\n        parser.print_help()\n        # quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    tm = ProtoBuf()\n    for table in known:\n        out1, out2 = tm.createProtoFromSQL(table)\n        name = table.replace('.sql', '.proto')\n        # pyfile = table.replace('.sql', '.py')\n        # xx = tm.protoToDict(name)\n        # name = table.replace('.yaml', '.proto')\n        out = tm.createTableProto()\n        if len(out1) > 0:\n            with open(name, 'w') as file:\n                file.writelines([str(i)+'\\n' for i in out1])\n                file.close()\n        if len(out2) > 0:\n            with open(name, 'w') as file:\n                file.writelines([str(i)+'\\n' for i in out2])\n                file.close()\n        log.info(f\"Wrote {name} to disk\")\n
    "},{"location":"api/#tmserverpy","title":"tmserver.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tmserver.TMServer","title":"TMServer","text":"
    TMServer(target)\n

    Bases: object

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description TMServer

    An instance of this class

    Source code in tm_admin/tmserver.py
    def __init__(self,\n             target: str,\n             ):\n    \"\"\"\n    Instantiate a server\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (TMServer): An instance of this class\n    \"\"\"\n    self.hosts = YamlFile(f\"{rootdir}/services.yaml\")\n    log.debug(\"Starting server\")\n    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n    tm_admin.services_pb2_grpc.add_TMAdminServicer_to_server(\n        RequestServicer(), server\n    )\n    # Enable reflection for grpc_cli\n    SERVICE_NAMES = (\n        tm_admin.services_pb2.DESCRIPTOR.services_by_name['TMAdmin'].full_name,\n        reflection.SERVICE_NAME,\n    )\n    reflection.enable_server_reflection(SERVICE_NAMES, server)\n\n    target = self.getTarget(target)\n    [[host, port]] = target.items()\n    # FIXME: this needs to use SSL for a secure connection\n    server.add_insecure_port(f\"[::]:{port}\")\n    server.start()\n    server.wait_for_termination()\n
    "},{"location":"api/#tm_admin.tmserver.TMServer.getTarget","title":"getTarget","text":"
    getTarget(target)\n

    Get the target hostname and IP port number

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description dict

    the hostname and IP port for this target program

    Source code in tm_admin/tmserver.py
    def getTarget(self,\n            target: str,\n            ):\n    \"\"\"\n    Get the target hostname and IP port number\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (dict): the hostname and IP port for this target program\n    \"\"\"\n    return self.hosts.yaml[0][target][0]\n
    "},{"location":"api/#tm_admin.tmserver.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tmserver.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"tmserver\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Server for gRPC communication\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    # This blocks till  this process is killed\n    tm = TMServer('test')\n
    "},{"location":"api/#tmclientpy","title":"tmclient.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tmclient.TMClient","title":"TMClient","text":"
    TMClient(target)\n

    Bases: object

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description TMClient

    An instance of this class

    Source code in tm_admin/tmclient.py
    def __init__(self,\n            target: str,\n            ):\n    \"\"\"\n    Instantiate a client\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (TMClient): An instance of this class\n    \"\"\"\n    # the services.yaml file defines the hostname and ports for all programs.\n    self.hosts = YamlFile(f\"{rootdir}/services.yaml\")\n    target = self.getTarget(target)\n    [[host, port]] = target.items()\n    # FIXME: this needs to use SSL for a secure connection\n    self.channel = grpc.insecure_channel(f\"{host}:{port}\")\n    # self.stub = tm_admin.services_pb2_grpc.TMClientStub(channel)\n    # self.stub = tm_admin.services_pb2_grpc.testStub(self.channel)\n    self.stub = tm_admin.services_pb2_grpc.TMAdminStub(self.channel)\n
    "},{"location":"api/#tm_admin.tmclient.TMClient.sendUserProfile","title":"sendUserProfile","text":"
    sendUserProfile(msg)\n

    Send data to the target program

    Parameters:

    Name Type Description Default msg str

    The message to send

    required

    Returns:

    Type Description dict

    The response from the server

    Source code in tm_admin/tmclient.py
    def sendUserProfile(self,\n            msg: str,\n            ):\n    \"\"\"\n    Send data to the target program\n\n    Args:\n        msg (str): The message to send\n\n    Returns:\n       (dict): The response from the server\n    \"\"\"\n    foo = UsersMessage(id=1, username=msg, name=msg)\n\n    bar = serialize_to_protobuf(foo.data, tm_admin.users.users_pb2.users)\n\n    response = self.stub.GetUser(bar)\n    #print(f\"TMAdmin client received: {response}\")\n    return response\n
    "},{"location":"api/#tm_admin.tmclient.TMClient.getTarget","title":"getTarget","text":"
    getTarget(target)\n

    Get the target hostname and IP port number

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description dict

    the hostname and IP port for this target program

    Source code in tm_admin/tmclient.py
    def getTarget(self,\n            target: str,\n            ):\n    \"\"\"\n    Get the target hostname and IP port number\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (dict): the hostname and IP port for this target program\n    \"\"\"\n    return self.hosts.yaml[0][target][0]\n
    "},{"location":"api/#tm_admin.tmclient.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tmclient.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"tmclient\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"gRPC Client\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-m\", \"--msg\", default='who', help=\"string to send\")\n    args, known = parser.parse_known_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    tm = TMClient('test')\n\n    cmd = {'cmd': Command.GET_USER, 'id': 2}\n    response = tm.sendRequest(cmd)\n    print(f\"TMAdmin user received: {response}\")\n\n    cmd = {'cmd': Command.GET_TEAM, 'id': 20}\n    response = tm.sendRequest(cmd)\n    print(f\"TMAdmin team received: {response}\")\n\n    cmd = {'cmd': Command.GET_ORG, 'id': 10}\n    response = tm.sendRequest(cmd)\n    print(f\"TMAdmin organization received: {response}\")\n
    "},{"location":"api/#userspy","title":"users.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.users.users.UsersDB","title":"UsersDB","text":"
    UsersDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection

    'localhost/tm_admin'

    Returns:

    Type Description UsersDB

    An instance of this class

    Source code in tm_admin/users/users.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the users table.\n\n    Args:\n        dburi (str): The URI string for the database connection\n\n    Returns:\n        (UsersDB): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.profile = UsersTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('users', dburi)\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.updateRole","title":"updateRole","text":"
    updateRole(id, role)\n

    Update the role for a user.

    Parameters:

    Name Type Description Default id int

    The users ID

    required role Userrole

    The new role.

    required Source code in tm_admin/users/users.py
    def updateRole(self,\n               id: int,\n               role: Userrole,\n               ):\n    \"\"\"\n    Update the role for a user.\n\n    Args:\n        id (int): The users ID\n        role (Userrole): The new role.\n    \"\"\"\n    role = Userrole(role)\n    return self.updateColumn(id, {'role': role.name})\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.updateMappingLevel","title":"updateMappingLevel","text":"
    updateMappingLevel(id, level)\n

    Update the mapping level for a user.

    Parameters:

    Name Type Description Default id int

    The users ID.

    required level Mappinglevel

    The new level.

    required Source code in tm_admin/users/users.py
    def updateMappingLevel(self,\n               id: int,\n               level: Mappinglevel,\n               ):\n    \"\"\"\n    Update the mapping level for a user.\n\n    Args:\n        id (int): The users ID.\n        level (Mappinglevel): The new level.\n    \"\"\"\n    mlevel = Mappinglevel(level)\n    return self.updateColumn(id, {'mapping_level': mlevel.name})\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.updateExpert","title":"updateExpert","text":"
    updateExpert(id, mode)\n

    Toggle the expert mode for a user.

    Parameters:

    Name Type Description Default id int

    The users ID.

    required mode bool

    The new mode..

    required Source code in tm_admin/users/users.py
    def updateExpert(self,\n               id: int,\n               mode: bool,\n               ):\n    \"\"\"\n    Toggle the expert mode for a user.\n\n    Args:\n        id (int): The users ID.\n        mode (bool): The new mode..\n    \"\"\"\n    return self.updateColumn(id, {'expert_mode': mode})\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.getRegistered","title":"getRegistered","text":"
    getRegistered(start, end)\n

    Get all users registered in this timeframe.

    Parameters:

    Name Type Description Default start datetime

    The starting timestamp

    required end datetime

    The starting timestamp

    required

    Returns:

    Type Description list

    The users registered in this timeframe.

    Source code in tm_admin/users/users.py
    def getRegistered(self,\n                  start: datetime,\n                  end: datetime,\n                  ):\n    \"\"\"\n    Get all users registered in this timeframe.\n\n    Args:\n        start (datetime): The starting timestamp\n        end (datetime): The starting timestamp\n\n    Returns:\n        (list): The users registered in this timeframe.\n    \"\"\"\n\n    where = f\" date_registered > '{start}' and date_registered < '{end}'\"\n    return self.getByWhere(where)\n
    "},{"location":"api/#tm_admin.users.users.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/users/users.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin', help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    user = UsersDB(args.uri)\n    # user.resetSequence()\n    all = user.getAll()\n    # Don't pass id, let postgres auto increment\n    ut = UsersTable(name='test', mapping_level='BEGINNER',\n                    email_address='foo@bar.com')\n    user.createTable(ut)\n    # print(all)\n\n    all = user.getByID(1)\n    print(all)\n\n    all = user.getByName('test')\n    print(all)\n\n    ut = UsersTable(name='foobar', email_address=\"bar@foo.com\", mapping_level='INTERMEDIATE')\n
    "},{"location":"api/#projectspy","title":"projects.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.projects.projects.ProjectsDB","title":"ProjectsDB","text":"
    ProjectsDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection

    'localhost/tm_admin'

    Returns:

    Type Description ProjectsDB

    An instance of this class

    Source code in tm_admin/projects/projects.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the projects table.\n\n    Args:\n        dburi (str): The URI string for the database connection\n\n    Returns:\n        (ProjectsDB): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.profile = ProjectsTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('projects', dburi)\n
    "},{"location":"api/#tm_admin.projects.projects.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/projects/projects.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    parser.add_argument(\"-b\", \"--boundary\", required=True,\n                        help=\"The project AOI\")\n\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    proj = ProjectsDB(args.uri)\n    # user.resetSequence()\n    all = proj.getAll()\n\n    file = open(args.boundary, 'r')\n    boundary = geojson.load(file)\n    geom = shape(boundary[0]['geometry'])\n    center = centroid(geom)\n    # Don't pass id, let postgres auto increment\n    ut = ProjectsTable(author_id=1, outline=geom, centroid=center,\n                       created='2021-12-15 09:58:02.672236',\n                       task_creation_mode='GRID', status='DRAFT',\n                       mapper_level='BEGINNER')\n    proj.createTable(ut)\n
    "},{"location":"api/#organizationspy","title":"organizations.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.organizations.organizations.OrganizationsDB","title":"OrganizationsDB","text":"
    OrganizationsDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection

    'localhost/tm_admin'

    Returns:

    Type Description OrganizationsDB

    An instance of this class

    Source code in tm_admin/organizations/organizations.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the organizations table.\n\n    Args:\n        dburi (str): The URI string for the database connection\n\n    Returns:\n        (OrganizationsDB): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.profile = OrganizationsTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('organizations', dburi)\n
    "},{"location":"api/#tm_admin.organizations.organizations.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/organizations/organizations.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    organization = OrganizationsDB(args.uri)\n    # organization.resetSequence()\n    all = organization.getAll()\n    # Don't pass id, let postgres auto increment\n    ut = OrganizationsTable(name='fixme', slug='slug', orgtype='FREE')\n    organization.createTable(ut)\n    # print(all)\n\n    all = organization.getByID(1)\n    print(all)\n\n    all = organization.getByName('fixme')\n    print(all)\n
    "},{"location":"api/#taskspy","title":"tasks.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tasks.tasks.TasksDB","title":"TasksDB","text":"
    TasksDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection.

    'localhost/tm_admin'

    Returns:

    Type Description TasksDB

    An instance of this class.

    Source code in tm_admin/tasks/tasks.py
    def __init__(self,\n            dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the tasks table.\n\n    Args:\n        dburi (str): The URI string for the database connection.\n\n    Returns:\n        (TasksDB): An instance of this class.\n    \"\"\"\n    self.profile = TasksTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('tasks', dburi)\n
    "},{"location":"api/#tm_admin.tasks.tasks.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tasks/tasks.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    task = TasksDB(args.uri)\n    # user.resetSequence()\n    all = task.getAll()\n    # Don't pass id, let postgres auto increment\n    ut = TasksTable(project_id=1)\n    task.createTable(ut)\n    # print(all)\n\n    all = task.getByID(1)\n    print(all)\n\n    all = task.getByName('test')\n    print(all)\n
    "},{"location":"build/","title":"Building TM-Admin","text":"

    This is a complicated project as it involves parsing and outputting multiple file formats. This project uses gRPC for the low-level communication layer, which is below the REST API. This way it can be used by multiple other project REST APIs for exchanging data without massive refactoring of an existing API.

    The database schema is based on the ones in use in the FMTM project, which were originally based on the ones used by the HOT Tasking Manager. The schemas have years of improvements on the data requirements of Tasking Manager style projects. Not every column in a database table will be needed by each project, they can be ignored. It should be entirely possible to use a custom configuration file, but this is currently unsupported. (would love a patch for this)

    This project generates multiple files at runtime, so each is organized into a sub-directory, one for each table. The program that processes each configuration file is generator.py, which is part of this project. This reads in a configuration file in YAML format, and generates the output files for this configuration file. There is also a class Generator that can be used by other projects.

    These are the current modules supported by this project.

    • users
    • projects
    • tasks
    • organizations
    • teams
    "},{"location":"build/#tmadmin-manage","title":"tmadmin-manage","text":"

    The tmadmin-manage program is for higher-level data management. While each class can be run standalone, that's more for testing & development. This program is also both a standalone program, and a class that can be used by other projects. This program will create the database and tables for each module.

    "},{"location":"build/#datatypes","title":"Datatypes","text":"

    Each database table has it's own configuration file. There is also a top level one, types.yaml that generates the type definitions that all the other files depend on. This becomes types_tm.sql, types_tm.proto, and types_tm.py, and needs to be imported before the other files.

    "},{"location":"build/#yaml-files","title":".yaml files","text":"

    The YAML based config files are where everything gets defined. This way a single configuration file can be used to generate multiple output formats. In the case of this projects, that's SQL files for a local postgres database, protobuf files for gRPC, and python source files for data type definitions. There is more information on the configuration files here

    "},{"location":"build/#proto-files","title":".proto files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. Not every column in the database tables is in a message. The fields that get send and received are defined in the configuration file by adding share: True as a setting.

    The .proto files then have to be compiled using protoc, which generates the client and server stubs.

    "},{"location":"build/#sql-files","title":".sql files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. These can be executed in postgres to create the tables. The tmadmin-manage program uses these to create the database tables.

    "},{"location":"communication/","title":"Inter Project Communication","text":"

    While there are data structures for all the columns in the database, not all of the data fields need to be used for inter project communication. Some field data is project specific, for example, tasks in the HOT Tasking Manager(TM) are not the same as tasks in the nHOT Field Mapping Tasking Manager(FMTM), but most of the fields are used for tasks in both.

    With any project that is designed to be embedded into other projects, there is a risk of duplicate data structures that can become a maintainance nightmare in the future, since any changes will need to be in multiple places. Each data structure is represented in the database schemas, python, and gRPC. To reduce future maintainance headaches, a single configuration file is used to generate multiple output formats. More information on that process is documented here.

    All communication is bi-directional. Projects can send data, or handle a request for data. For any data that is sent, the response is a simple SUCCESS/FAILURE message. FAILURE message also return an error message and error code.

    It seems that most of the projects start with TM. After critical tasks are mapped, they then could be migrated to FMTM for field data collection. The FMTM mappers would also be ground truthing the remote mapping. It's entirely possible that FMTM field mappers would find issues with the data extract of OSM buildings, and want to notify the TM project manager to invalidate some tasks and remap them.

    "},{"location":"communication/#notifications","title":"Notifications","text":"

    Some messages have nothing to do with the database, they're for communicating other types of requests. Other than just doing database updates, this is the core of an end to end data flow.

    Examples of some notifications are:

    • Underpass would notify TM or fAIr of a data quality issue
    • An FMTM project manager would notify TM to invalidate a task
    • fAIr would notify an FMTM project manager that the imagery has been processed so a data extract could be made
    • fAIr would notify OAM that drone imagery is needed for an AOI
    • OAM would notify fAIr when drone imagery is ready to be processed
    "},{"location":"communication/#projects-exchange-user-profiles","title":"Projects exchange user profiles","text":"

    Since a user may be contributing to multiple projects, it should be possible to clone a users profile between projects. For example, when a Tasking Manager (TM) is being worked on, some users may also be using the Field Mapping Tasking Manager (FMTM) to ground-truth the data. Or they may want to use fAIr to process the drone imagery they just collected.

    "},{"location":"communication/#user-profiles","title":"User profiles","text":"

    These are the data fields that need to be in this message to create a user profile in the database. The user ID in TM or FMTM won't be the same, since each project will have different teams of mappers. Instead of the ID, the username will be used to refer to a mapper.

    • username
    • name
    • city
    • country
    • email_address
    • is_email_verified
    • is_expert
    • mapping_level
    • password
    "},{"location":"communication/#receiving-project-decides-update-or-create","title":"Receiving project decides, update or create ?","text":"

    When this message is received, it should update the database for this user unless the username already exists, and send the response acknowledgment.

    "},{"location":"communication/#tm-sends-project-profile","title":"TM sends project profile","text":"

    It is entirely likely that for disaster response, an area may be remotely mapped with TM, and then will be field mapped with FMTM as a follow-up. The instructions would be very different, so aren't needed. The tasks won't be sent either, as a TM task is much largerr than an FMTM task. FMTM mappers are walking when mapping. The project ID is also not transmitted, as it'll be different in different projects. There may also be occassions where a project would be sent to fAIr, Export Tool, or Underpass.

    • name
    • outline
    • description
    • location_str
    • organisation_id (spelling depends on country)
    • priority
    • centroid

    A project transferred to FMTM has no project manager, so these are initially only an AOI and draft project description. FMTM would need the ability to search for an unassigned project, ie... no manager. Then when there is a project manager it would be assigned to them.

    "},{"location":"communication/#receiving-project-decides-update-or-create_1","title":"Receiving project decides, update or create ?","text":"

    When this message is received, it should update the database for this project, and send the response acknowledgment.

    "},{"location":"communication/#tm-sends-organization-profile","title":"TM sends organization profile","text":"

    Organizations may be using multiple HOT projects, so this would sync organization data between projects so it wouldn't have to be manually edited for each poroject like it is now.

    • name
    • description
    • url
    • logo
    • type
    "},{"location":"communication/#receiving-project-decides-update-or-create_2","title":"Receiving project decides, update or create ?","text":"

    When this message is received, it should update the database for this organization, and send the response acknowledgment.

    "},{"location":"configuring/","title":"Configuring The Data Structures","text":"

    For any project that needs to transmit data between multiple projects, there needs to be a single source of data structures and type definitions. Otherwise there winds up being a lot of code duplication which becomes hard to maintain.

    This project also needs to manage the database tables, as well as allow to transmit data between projects. Python enums and classes are also generated.

    "},{"location":"configuring/#the-yaml-files","title":"The YAML files","text":"

    This file is used to generate the full SQL to create database tables, as well as the protobuf files. The first field becomes the name of the tables in postgres, or the message in the .proto file. Each table is then followed by a list of fields. Each field has a few settings, the data type, and a few settings.

    For example:

    - users:\n    - id:\n        - int64\n        - required: True\n        - share: True\n        - sequence: True\n ...\n
    "},{"location":"configuring/#required","title":"required","text":"

    If this is True, then for the database table, this becomes NOT NULL in the SQL schema. This is ignored when generating the protobuf file.

    "},{"location":"configuring/#sequence","title":"sequence","text":"

    If this is True, then this becomes an auto incrementing sequence in SQL. This is ignored when generating the protobuf file.

    "},{"location":"configuring/#share","title":"share","text":"

    Not every field needs to be transfered to other projects, as some are project specific, like how many tasks have been mapped. If this is True, then it will have an entry in the protobuf message. The default is True. To have a field not appear in the protobuf message, this needs to be set to False.

    "},{"location":"configuring/#array","title":"array","text":"

    If this is True, then in the database schema this becomes an array. In the protobuf file, this adds the repeated keyword in the message to define this field as an array.

    "},{"location":"configuring/#unique","title":"unique","text":"

    if this is True, in postgres a unique constraint is generated for this, which is used for upserts.

    "},{"location":"dataexchange/","title":"Exchanging Data","text":"

    Exchanging data between projects has a few issues, namely the ID of the user, the project, and the organization are different in the different projects. Not all fields are useful cross-project, so some but not all of the columns in a database table are exchanged w ith other projects. There are other issues to handle, a projet manager/admin in Tasking Manager (TM) may only be a a mapper in the Field Mapping Tasking Manager (FMTM) project, so the roles change, but the rest of the user profile stays the same.

    Currently all the database tables have every column used by FMTM or TM. Since there are many application specific columns, these are simply ignored by the application. While this does make the database slightly larger having multiple empty columns, it's a tradeoff between database size and simplifying the code base. A future enhancement to the YAML config file subsystem will support using a subset of all the database columns.

    Some of the data to be exchanged is currently supported by the REST API for FMTM and TM. The plan is for these modules in the TM-Admin project work under those REST APIs for database access. This lets the REST API stay focused on supporting the web frontend for each application.

    "},{"location":"dataexchange/#identifying-records","title":"Identifying Records","text":"

    Since the ID can't be used between projects, the name or address is the only unique field that can be used to identify a user or an organization, etc... For users, the best ID is their OpenStreetMap (ODM) ID, as that is unique globally. While some support can be added to track unique IDs across multiple projects, this can be cumbersome.

    Another way to identify a record is through location. Since both projects and tasks have an polygon area of interest, a point within a project in one application, can be used to query a remote project to find the project or task. For example, if a field mapper finds bad data, the location of that data can be used to find the TM project and task, so the task can be invalidated.

    "},{"location":"dataexchange/#filtering-data","title":"Filtering Data","text":"

    Since not all data fields are needed in each project, the YAML configuration file supports a flag for each item in a data structure as to whether it should be shared or not. For example, a database query might return many columns, but only a few are usefully portable across multiple projects.

    For instance, Tasking Manager has task boundaries, in FMTM, tasks are smaller, because it involves mappers walking. So transferrihng exact task boundaries would be meaningless. In this usage case, the tasks transfer from TM to FMTM would be a multi-polygon. FMTM would create a project AOI based on the outer boundary of all the of the tasks, and then recalulate FMTM specific tasks boundaries.

    "},{"location":"dataexchange/#data-exchange-schemas","title":"Data Exchange Schemas","text":"

    Some fields need to be in any data packet that is intended for database queries, since the there needs to be a way to refer to an existing record, if it exists. While it is possible to identify remote database records by comparing multiple columns, to keep things simple, it is prefered to use the name or location.

    "},{"location":"dataexchange/#project-data","title":"Project Data","text":"

    A project has a wide definition depending on the type of application. Since this module is focused on Tasking Manager style applications, all version will have at least a project name and an Area of Interest (AOI). In addition, each tracks task usage, so the number of tasks mapped, validated, or invalidated exists in all tables, but has different data.

    "},{"location":"dataexchange/#field-mapping-tasking-manager","title":"Field Mapping Tasking Manager","text":"

    For FMTM, it uses an odkid column, which is used to communicate with ODK Central. This is an example of needing to store the ID of a remote application to exchange data for specific items. How the ID of a remote project is stored may change in the future to handle multiple remote applications, but for now, it's only the one for ODK Central.

    FMTM also uses several columns for working with OpenDataKit(ODK). These are the login credentials for an ODK Central server, and an XLSForm for the project.

    "},{"location":"dataexchange/#tasking-manager","title":"Tasking Manager","text":"

    TM uses a series of columns that are used for editing OSM data. This includes presets for several editors.

    "},{"location":"dataexchange/#user-data","title":"User Data","text":"

    Most all the columns in the user profiles is the same across all applications. The are a few columns for tracking tasks mapped, etc... but the data for those will vary between applications.

    "},{"location":"dataexchange/#organization-data","title":"Organization Data","text":"

    Organization data is easy, all columns are used by all applications. This this table is simple, organization name, logo, URL, and a description.

    "},{"location":"dataexchange/#task-data","title":"Task Data","text":"

    A task AOI is not usually useful between projects, as a TM task is much larger than an FMTM task. For a Drone Tasking Manager (DTM), the task size will also be different. Since tasks are not portable across projects, each project maintains it's own data, the creation date, tasks mapped, validated, invalidated, etc...

    "},{"location":"dataflow/","title":"TM-Admin Data Flow","text":""},{"location":"dataflow/#generated-files","title":"Generated files","text":"

    This project attempts to minimise code duplication. It is designed to be a module for use in other projects. Because this project works with both gRPC messages and a postgres database, any changes to any of the data structures would require making changes in multiple places. Instead a single file in YAML format is used to generate all the other formats. This way changes only have to be made in one place.

    It does make the code more complicated, lots of layers of generated code stubs to dig through when debugging. I've also tried to avoid hacks in the code, and make it flexible to changes. That often involves lots of looping through various data, but it's still pretty fast.

    "},{"location":"dataflow/#generating-the-files","title":"Generating the files","text":"

    To generate the files, there is a standalone python class, which also has a simple command line interface and can be run offline. The generate.py file reads in the YAML config files, and creates an internal data structure for that file. More information on the config file is here.

    The actual database schemas are created from the generated SQL files. The tmadmin_manage.py file has a class that also runs standalone and generates all the SQL, python, and protobuf files using the Generate class. Once it generates the SQL files, it creates the database and tables.

    The protobuf files need to be compiled using protoc. This is easiest done using the Makefile. since it has to include the types for the complication to succeed.

    Since there are a lot of generated files, they are all in a subdirectory. Each directory is for each table in the database, and all generated files go there.

    "},{"location":"dataflow/#datatypes","title":"Datatypes","text":"

    There are multiple shared enums, and are defined in the types.yaml file. These become enums for postgres, python, and protobuf. After generating the files, there is types_tm.sql, types_tm.py, and a types_tm.proto for the protobuf files gRPC uses. These can be included in any of the other classes that create data types. Having portable data strucures that can be shared is critical. Otherwise any changes would require editing multiple places. Having a single definition reduces maintaince.

    "},{"location":"dataflow/#the-python-files","title":"The Python files","text":"

    There are python source files generated for each database table. These define all the data structures so they are easily accessible. The enums are in the types_tm.py file.

    The other two files are classes that define the full data for SQL queries, as well as the reduced dataset used in inter-project data exchange using gRPC. Using the table name, these become tableTable or tableMessage. The class files are for storing the data for a table. The tableMessage classes are the reduced datasets for exchanging data. Not all data in a database is useful in multiple projects, so this uses a setting in the YAML config file to not have all columns in the gRPC message.

    Each table also has a class designed for accessing the database. This file is not generated. This uses the other generated python files for the data structures. This handles creating the entries for the tables, and also has a few common queries, like search by ID. Most of the higher level processing will be handled by the project importing this module since it's possible to get the full data for furthur processing. This is to make it a less painful refactoring of an existing project backend. Many projects have existing tests of the values in the database columns, so this is still possible.

    "},{"location":"dataflow/#instantiating-an-object","title":"Instantiating an object","text":"

    The generated python files allow for default values for all the database tables, and conditional parameters in python. With each top level class for a tables,

    For example: ut = UsersTable(name='fixme', mapping_level='BEGINNER')

    Creates a dictionary in the class with all of the keywords from the YAML file. but will set these two columns to these values. This is used for both creating entries in the database, but also for updating them. This handles multiple optional parameters allowing this data object to be used for data exchange in a consistent fashion.

    "},{"location":"dataflow/#sql-files","title":"SQL files","text":"

    The SQL files are designed to work with postgres for creating the database, and it's tables and data types. The config file format allows for setting each column as an auto incrementing column (good for IDs), setting that are required, so become 'NOT NULL'. And also a unique column, which is used for an INSERT that may trigger a conflict. This is useful to update existing data.

    "},{"location":"dataflow/#protobuf-files","title":"Protobuf files","text":"

    The protobuf files are used by gRPC to exchange data. The protoc compiler produces other wrappers as python code for the data structures. These also use the table name as the prefix, and creates table_pb2.py or table_pb2_grpc.py. These are used with gRPC. The other generated python class are designed to interface with these, since they need data structures to exchange.

    "},{"location":"endpoints/","title":"REST API Endpoints","text":"

    This is a comparison between the endpoint of Tasking Manager and the Field Mapping Tasking Manager. The goal of the TM Admin project is to support these endpoints. There is also not an obvious 1-1 relationship between endpoints the support class in TM Adamin. Endpoints are higher level than the code in TM Admin.

    For the common functions like querying the database by ID or name, these are in a base class, so shared.

    "},{"location":"endpoints/#users","title":"Users","text":"

    Endpoints for managing User profiles.

    Tasking Manager FMTM TM Admin Get paged list of all usernames Get Users UsersDB.getAll() Registers users without OpenStreetMap account UsersDB.createTable() Updates user info UsersDB.updateTable() Get user information by OpenStreetMap username UsersDB.getByName() Get stats about users registered within a period of time UsersDB.getByWhere() Get user information by id Get User by ID UsersDB.getByID() Allows user to enable or disable expert mode UsersDB.updateExpert() Allows PMs to set a user's mapping level UsersDB.updateMappingLevel() Allows PMs to set a user's role UsersDB.updateRole() Get a list of tasks a user has interacted with UsersDB.getByWhere() Resends the verification email token to the logged in user Get recommended projects for a user Get details from OpenStreetMap for a specified username Get detailed stats about a user by OpenStreetMap username Get paged lists of users matching OpenStreetMap username filter Get User Roles"},{"location":"endpoints/#organizations","title":"Organizations","text":"

    Endpoints for managing Organization profiles.

    Tasking Manager FMTM TM Admin List all organisations Get Organization OrganizationsDB.getAll() Creates a new organisation Create Organization OrganizationsDB.createTable() Deletes an organisation Delete Organizations OrganizationsDB.deleteByID Retrieves an organisation Get Organization Detail OrganizationsDB.getByID() Updates an organisation Update Organization OrganizationsDB.updateTable() Return statistics about projects and active tasks of an organisation"},{"location":"endpoints/#projects","title":"Projects","text":"

    Endpoints for managing projects.

    Tasking Manager FMTM TM Admin List and search for projects Read Projects projectsDB.getAll() Creates a tasking-manager project Create Project projectsDB.createTable() List and search projects by bounding box projectsDB.getByLocation() Get featured projects projectsDB.updateTable() Get all projects for logged in admin projectsDB.getByWhere() Get popular projects projectsDB.getByWhere() Get similar projects projectsDB.getByWhere() Gets projects user has mapped projectsDB.getByWhere() Deletes a Tasking-Manager project Delete Project projectsDB.deleteByID() Get a specified project including it's area Get Project Details projectsDB.getByID() Updates a Tasking-Manager project Update Project projectsDB.updataTable() Set a project as featured projectsDB.updateColumn() Send message to all contributors of a project Unset a project as featured projectsDB.updateColumn() Transfers a project to a new user projectsDB.updateColumn() Get all user activity on a project projectsDB.getByWhere() Get latest user activity on all of project task projectsDB.getByWhere() Get all user contributions on a project projectsDB.getByWhere() Get contributions by day for a project projectsDB.getByWhere() Get AOI of Project projectsDB.getByID() Upload Custom XLSForm Project Partial Update Upload Multi Project Boundary Task Split Upload Project Boundary Edit Project Boundary Update Odk Credentials Validate Form Generate Files Get Data Extracts Update Project Form Get Project Features Generate Log Get Categories Preview Tasks Add Features Download Form Update Project Category Download Template Download Project Boundary Download Task Boundaries Download Features Generate Project Tiles Tiles List Download Tiles Download Task Boundary Osm Project Centroid"},{"location":"endpoints/#tasks","title":"Tasks","text":"

    Endpoints for managing tasks in a project.

    Tasking Manager FMTM TM Admin Delete a list of tasks from a project Get all tasks for a project as JSON Read Tasks tasksDB.getAll() Extends duration of locked tasks tasksDB.getByWhere() Invalidate all validated tasks on a project Locks a task for mapping tasksDB.updateColumn() Lock tasks for validation tasksDB.updateColumn() Map all tasks on a project Set all bad imagery tasks as ready for mapping tasksDB.updateTable() Reset all tasks on project back to ready, preserving history Revert tasks by a specific user in a project Split a task Unlock a task that is locked for mapping resetting it to its last status tasksDB.updateTable() Unlock tasks that are locked for validation resetting them to their last status tasksDB.updateTable() Undo a task's mapping status Update Task Status tasksDB.updateTable() Set a task as mapped Update Task Status tasksDB.updateTable() Set tasks as validated Update Task Status tasksDB.updateTable() Validate all mapped tasks on a project Update Task Status tasksDB.updateTable() Get task tiles intersecting with the aoi provided tasksDB.getByLocation() Get all tasks for a project as GPX tasks.getAll() Get all mapped tasks for a project grouped by username Get all tasks for a project as OSM XML Get a task's metadata Get Task Get invalidated tasks either mapped by user or invalidated by user Get Task Stats Get Qr Code List Edit Task Boundary Task Features Count"},{"location":"protos-api/","title":"Protocol Documentation","text":""},{"location":"protos-api/#table-of-contents","title":"Table of Contents","text":"
    • services.proto

      • notification
      • tmrequest
      • tmresponse
      • tmresponse.DataEntry

      • TMAdmin

    • types_tm.proto

      • Bannertype
      • Command
      • Editors
      • Encouragingemailtype
      • Mappinglevel
      • Mappingnotallowed
      • Mappingtypes
      • Notification
      • Organizationtype
      • Permissions
      • Projectdifficulty
      • Projectpriority
      • Projectstatus
      • Taskaction
      • Taskcreationmode
      • Taskstatus
      • Teamjoinmethod
      • Teammemberfunctions
      • Teamroles
      • Teamvisibility
      • Usergender
      • Userrole
      • Validatingnotallowed
    • organizations/organizations.proto

      • organizations
    • projects/projects.proto

      • projects
    • tasks/tasks.proto

      • tasks
    • teams/teams.proto

      • teams
    • users/users.proto

      • users
    • Scalar Value Types

    Top

    "},{"location":"protos-api/#servicesproto","title":"services.proto","text":""},{"location":"protos-api/#notification","title":"notification","text":"Field Type Label Description note Notification"},{"location":"protos-api/#tmrequest","title":"tmrequest","text":"Field Type Label Description cmd Command id int64 name string"},{"location":"protos-api/#tmresponse","title":"tmresponse","text":"Field Type Label Description error_code int32 error_msg string data tmresponse.DataEntry repeated message Data { map<string, string> pairs = 3; } repeated Data data = 4;"},{"location":"protos-api/#tmresponsedataentry","title":"tmresponse.DataEntry","text":"Field Type Label Description key string value string"},{"location":"protos-api/#tmadmin","title":"TMAdmin","text":"

    The greeting service definition.

    Method Name Request Type Response Type Description doRequest tmrequest tmresponse These are for handling tmrequest for profile data from the database doNotification notification tmresponse updateUserProfile users users updateProjectProfile projects projects updateTeamProfile teams teams updateTask tasks tasks updateOrganizationProfile organizations organizations

    Top

    "},{"location":"protos-api/#types_tmproto","title":"types_tm.proto","text":""},{"location":"protos-api/#bannertype","title":"Bannertype","text":"Name Number Description INFO 0 WARNING 1"},{"location":"protos-api/#command","title":"Command","text":"Name Number Description GET_USER 0 GET_ORG 1 GET_PROJECT 2 GET_TEAM 3"},{"location":"protos-api/#editors","title":"Editors","text":"Name Number Description ID 0 JOSM 1 POTLATCH_2 2 FIELD_PAPERS 3 CUSTOM 4 RAPID 5"},{"location":"protos-api/#encouragingemailtype","title":"Encouragingemailtype","text":"Name Number Description PROJECT_PROGRESS 0 PROJECT_COMPLETE 1 BEEN_SOME_TIME 2"},{"location":"protos-api/#mappinglevel","title":"Mappinglevel","text":"Name Number Description BEGINNER 0 INTERMEDIATE 1 ADVANCED 2"},{"location":"protos-api/#mappingnotallowed","title":"Mappingnotallowed","text":"Name Number Description USER_ALREADY_HAS_TASK_LOCKED 0 USER_NOT_CORRECT_MAPPING_LEVEL 1 USER_NOT_ACCEPTED_LICENSE 2 USER_NOT_ALLOWED 3 PROJECT_NOT_PUBLISHED 4 USER_NOT_TEAM_MEMBER 5 PROJECT_HAS_NO_OSM_TEAM 6 NOT_A_MAPPING_TEAM 7"},{"location":"protos-api/#mappingtypes","title":"Mappingtypes","text":"Name Number Description ROADS 0 BUILDINGS 1 WATERWAYS 2 LAND_USE 3 OTHER 4"},{"location":"protos-api/#notification_1","title":"Notification","text":"Name Number Description BAD_DATA 0 BLOCKED_USER 1 PROJECT_FINISHED 2"},{"location":"protos-api/#organizationtype","title":"Organizationtype","text":"Name Number Description FREE 0 DISCOUNTED 1 FULL_FEE 2"},{"location":"protos-api/#permissions","title":"Permissions","text":"Name Number Description ANY_PERMISSIONS 0 LEVEL 1 TEAMS 2 TEAMS_LEVEL 3"},{"location":"protos-api/#projectdifficulty","title":"Projectdifficulty","text":"Name Number Description EASY 0 MODERATE 1 CHALLENGING 2"},{"location":"protos-api/#projectpriority","title":"Projectpriority","text":"Name Number Description URGENT 0 HIGH 1 MEDIUM 2 LOW 3"},{"location":"protos-api/#projectstatus","title":"Projectstatus","text":"Name Number Description ARCHIVED 0 PUBLISHED 1 DRAFT 2"},{"location":"protos-api/#taskaction","title":"Taskaction","text":"Name Number Description RELEASED_FOR_MAPPING 0 LOCKED_FOR_MAPPING 1 MARKED_MAPPED 2 LOCKED_FOR_VALIDATION 3 VALIDATED 4 MARKED_INVALID 5 MARKED_BAD 6 SPLIT_NEEDED 7 RECREATED 8 COMMENT 9"},{"location":"protos-api/#taskcreationmode","title":"Taskcreationmode","text":"Name Number Description GRID 0 CREATE_ROADS 1 UPLOAD 2"},{"location":"protos-api/#taskstatus","title":"Taskstatus","text":"Name Number Description READY 0 TASK_LOCKED_FOR_MAPPING 1 TASK_STATUS_MAPPED 2 TASK_LOCKED_FOR_VALIDATION 3 TASK_VALIDATED 4 TASK_INVALIDATED 5 BAD 6 SPLIT 7 TASK_ARCHIVED 8"},{"location":"protos-api/#teamjoinmethod","title":"Teamjoinmethod","text":"Name Number Description ANY_METHOD 0 BY_REQUEST 1 BY_INVITE 2"},{"location":"protos-api/#teammemberfunctions","title":"Teammemberfunctions","text":"Name Number Description MANAGER 0 MEMBER 1"},{"location":"protos-api/#teamroles","title":"Teamroles","text":"Name Number Description TEAM_READ_ONLY 0 TEAM_MAPPER 1 VALIDATOR 2 PROJECT_MANAGER 3"},{"location":"protos-api/#teamvisibility","title":"Teamvisibility","text":"Name Number Description PUBLIC 0 PRIVATE 1"},{"location":"protos-api/#usergender","title":"Usergender","text":"Name Number Description MALE 0 FEMALE 1 SELF_DESCRIBE 2 PREFER_NOT 3"},{"location":"protos-api/#userrole","title":"Userrole","text":"Name Number Description USER_READ_ONLY 0 USER_MAPPER 1 ADMIN 2"},{"location":"protos-api/#validatingnotallowed","title":"Validatingnotallowed","text":"Name Number Description USER_NOT_VALIDATOR 0 USER_LICENSE_NOT_ACCEPTED 1 USER_NOT_ON_ALLOWED_LIST 2 PROJECT_NOT_YET_PUBLISHED 3 USER_IS_BEGINNER 4 NOT_A_VALIDATION_TEAM 5 USER_NOT_IN_TEAM 6 PROJECT_HAS_NO_TEAM 7 USER_ALREADY_LOCKED_TASK 8

    Top

    "},{"location":"protos-api/#organizationsorganizationsproto","title":"organizations/organizations.proto","text":""},{"location":"protos-api/#organizations","title":"organizations","text":"Field Type Label Description id int64 name string slug string logo string description string url string orgtype Organizationtype

    Top

    "},{"location":"protos-api/#projectsprojectsproto","title":"projects/projects.proto","text":""},{"location":"protos-api/#projects","title":"projects","text":"Field Type Label Description id int64 odkid int64 author_id int64 created google.protobuf.Timestamp project_name_prefix string task_type_prefix string location_str string outline bytes status Projectstatus private bool mapper_level Mappinglevel priority Projectpriority centroid bytes hashtags string repeated

    Top

    "},{"location":"protos-api/#taskstasksproto","title":"tasks/tasks.proto","text":""},{"location":"protos-api/#tasks","title":"tasks","text":"Field Type Label Description id int64 project_task_name string outline bytes geometry_geojson string

    Top

    "},{"location":"protos-api/#teamsteamsproto","title":"teams/teams.proto","text":""},{"location":"protos-api/#teams","title":"teams","text":"Field Type Label Description id int64 name string logo string description string invite_only bool visibility Teamvisibility

    Top

    "},{"location":"protos-api/#usersusersproto","title":"users/users.proto","text":""},{"location":"protos-api/#users","title":"users","text":"Field Type Label Description id int64 username string name string city string country string tasks_mapped int32 tasks_invalidated int32 projects_mapped int32 repeated date_registered google.protobuf.Timestamp last_validation_date google.protobuf.Timestamp password string osm_id int64 facebook_id int64 irc_id int64 skype_id int64 slack_id int64 linkedin_id int64 twitter_id int64 picture_url string gender int32"},{"location":"protos-api/#scalar-value-types","title":"Scalar Value Types","text":".proto Type Notes C++ Java Python Go C# PHP Ruby double double double float float64 double float Float float float float float float32 float float Float int32 Uses variable-length encoding. Inefficient for encoding negative numbers \u2013 if your field is likely to have negative values, use sint32 instead. int32 int int int32 int integer Bignum or Fixnum (as required) int64 Uses variable-length encoding. Inefficient for encoding negative numbers \u2013 if your field is likely to have negative values, use sint64 instead. int64 long int/long int64 long integer/string Bignum uint32 Uses variable-length encoding. uint32 int int/long uint32 uint integer Bignum or Fixnum (as required) uint64 Uses variable-length encoding. uint64 long int/long uint64 ulong integer/string Bignum or Fixnum (as required) sint32 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. int32 int int int32 int integer Bignum or Fixnum (as required) sint64 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. int64 long int/long int64 long integer/string Bignum fixed32 Always four bytes. More efficient than uint32 if values are often greater than 2^28. uint32 int int uint32 uint integer Bignum or Fixnum (as required) fixed64 Always eight bytes. More efficient than uint64 if values are often greater than 2^56. uint64 long int/long uint64 ulong integer/string Bignum sfixed32 Always four bytes. int32 int int int32 int integer Bignum or Fixnum (as required) sfixed64 Always eight bytes. int64 long int/long int64 long integer/string Bignum bool bool boolean boolean bool bool boolean TrueClass/FalseClass string A string must always contain UTF-8 encoded or 7-bit ASCII text. string String str/unicode string string string String (UTF-8) bytes May contain any arbitrary sequence of bytes. string ByteString str []byte ByteString string String (ASCII-8BIT)"},{"location":"tmadmin-manage/","title":"TM Admin Manage Util","text":"

    This utility program is the standalone interface to the tm-admin project. It is responsible for creating the database and the tables, and generating the protobuf files for gRPC.

    Initially it is used to generate the SQL files for creating the database and it's tables. These are created from a YAML based config file. That file is described in more detail in this document. This same YAML file is also used to generate all the protobuf files that define each gRPC message, and the python wrappers.

    Once the SQL files have been generated, this program imports them into the database. It can also handle database schema migrations.

    usage: config [-h] -v -d DIFF -u URI YAML files\noptions:\n-h, --help            show this help message and exit\n-v [VERBOSE], --verbose [VERBOSE] verbose output\n-d DIFF, --diff DIFF  SQL file diff for migrations\n-u URI, --uri URI     Database URI\n

    The Database URI defaults to localhost/tm_admin.

    "},{"location":"wiki_redirect/","title":"TM Admin","text":"

    Please see the docs page at: https://hotosm.github.io/tm-admin/

    "}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"TM Admin","text":"

    Administrative modules for Tasking Manager style projects.

    \ud83d\udcd6 Documentation: https://hotosm.github.io/tm-admin/

    \ud83d\udda5\ufe0f Source Code: https://github.com/hotosm/tm-admin

    This is a complicated project as it involves parsing and outputting multiple file formats. This project uses gRPC for the low-level communication layer, which is below the REST API. This way it can be used by multiple other project REST APIs for exchanging data without massive refactoring of an existing API.

    The database schema is based on the ones in use in the FMTM project, which were originally based on the ones used by the HOT Tasking Manager. The schemas have years of improvements on the data requirements of Tasking Manager style projects. Not every column in a database table will be needed by each project, they can be ignored. It should be entirely possible to use a custom configuration file, but this is currently unsupported. (would love a patch for this)

    This project generates multiple files at runtime, so each is organized into a sub-directory, one for each table. The program that processes each configuration file is generator.py, which is part of this project. This reads in a configuration file in YAML format, and generates the output files for this configuration file. There is also a class Generator that can be used by other projects.

    These are the current modules supported by this project.

    • users
    • projects
    • tasks
    • organizations
    • teams
    "},{"location":"#tmadmin-manage","title":"tmadmin-manage","text":"

    The tmadmin-manage program is for higher-level data management. While each class can be run standalone, that's more for testing & development. This program is also both a standalone program, and a class that can be used by other projects. This program will create the database and tables for each module.

    "},{"location":"#datatypes","title":"Datatypes","text":"

    Each database table has it's own configuration file. There is also a top level one, types.yaml that generates the type definitions that all the other files depend on. This becomes types_tm.sql, types_tm.proto, and types_tm.py, and needs to be imported before the other files.

    "},{"location":"#yaml-files","title":".yaml files","text":"

    The YAML based config files are where everything gets defined. This way a single configuration file can be used to generate multiple output formats. In the case of this projects, that's SQL files for a local postgres database, protobuf files for gRPC, and python source files for data type definitions. There is more information on the configuration files here

    "},{"location":"#proto-files","title":".proto files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. Not every column in the database tables is in a message. The fields that get send and received are defined in the configuration file by adding share: True as a setting.

    The .proto files then have to be compiled using protoc, which generates the client and server stubs.

    "},{"location":"#sql-files","title":".sql files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. These can be executed in postgres to create the tables. The tmadmin-manage program uses these to create the database tables.

    "},{"location":"CHANGELOG/","title":"Changlog","text":""},{"location":"CHANGELOG/#unreleased","title":"Unreleased","text":""},{"location":"CHANGELOG/#fix","title":"Fix","text":"
    • Fix typo in password settings
    • Oops, add colon to tag
    • Add more columns from TM
    • Add section on the new unique keyword
    • Add more content
    • Add doc on the data flow, since there are a lot of generated files used elsewhere
    • Add support for updating records, including the enums
    • Add a unique contraint
    • Add method to reset the sequence for id
    • Query by ID name, or all rows, which is what TM needs
    • update CHANGELOG
    • Support class for managing the users table
    • Make more items be shared in messages
    • Handle datetime now
    • Nre proto file for message requests
    • Now generated classes use named parameters, which also get store in a dict
    • Delete the new generated files
    • Also generate the python stubs for data structures
    • Create the tables in the database from the generated SQL files
    • Update CHANGELOG
    • Add actual content
    • Add new files to API docs
    • Major refactoring to use YAML config file for all file generation
    • Major refactoring to use YAML config file for .sql generation
    • Major refactoring to use YAML config file for .proto generation
    • Add generated files to reduce clutter
    • Refactoring to use yaml files for file generation completed
    • Add organization section
    • Add doc on the communication details
    • Add initial content for a doc on data flow between projects
    • Add default page
    • Add doc on this project
    • Add recursive targets, since tm_admin/Makefile does all the work
    • Set version number to 0.1.0
    • Start refactoring to use our messages
    • Generate the SQL files from the YAML files
    • add one sentence about python
    • The SQL files now get generated from the YAML config files
    • Drop SQL files, they're now generated from the yaml config files
    • Add config file for organizxations table
    • Add config file for tasks table
    • Add config file for projects table
    • Always generate types_tm.* files, improve handling of sequences
    • Generate all the types_tm files
    • Add config file for all typedefs and the user table
    • Remove the generated type_tm.* files too
    • Add new file documenting the yaml based config file syntax
    • Generate SQL from yaml file
    • Generate SQL and protobuf files from yaml config file
    • Add method to convert a .proto file to a python dict
    • update services to support user profiles
    • Minimal implementation sending user profile data between client & server
    • Don't display the comments in the target
    • Add config file and use it to specify host:port for the other programs
    • Build the top level services stubs
    • add grpc dependencies
    • Improve table creation
    • Update AGPL code block
    • Move protobuf creation code to it's own file and use it
    • Add realclean target to get rid of all non source files
    • Use the protoc in grpc, not protobuf
    • Add dependencies
    • Add changelog file
    • Add target to run Doxygen
    • More files to create documentation infrastructure
    • Add Doxyfile to generate API docs
    • Update the License file
    • Add more files
    • Add the generated types* files too
    • Add default docs
    • Install the module
    • sloppy merge for new code into a real git repo
    "},{"location":"LICENSE/","title":"GNU AFFERO GENERAL PUBLIC LICENSE","text":"

    Version 3, 19 November 2007

    Copyright (C) 2007 Free Software Foundation, Inc. https://fsf.org/

    Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

    "},{"location":"LICENSE/#preamble","title":"Preamble","text":"

    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.

    "},{"location":"LICENSE/#terms-and-conditions","title":"TERMS AND CONDITIONS","text":""},{"location":"LICENSE/#0-definitions","title":"0. Definitions.","text":"

    \"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.

    "},{"location":"LICENSE/#1-source-code","title":"1. Source Code.","text":"

    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.

    "},{"location":"LICENSE/#2-basic-permissions","title":"2. Basic Permissions.","text":"

    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.

    "},{"location":"LICENSE/#3-protecting-users-legal-rights-from-anti-circumvention-law","title":"3. Protecting Users' Legal Rights From Anti-Circumvention Law.","text":"

    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.

    "},{"location":"LICENSE/#4-conveying-verbatim-copies","title":"4. Conveying Verbatim Copies.","text":"

    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.

    "},{"location":"LICENSE/#5-conveying-modified-source-versions","title":"5. Conveying Modified Source Versions.","text":"

    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.

    "},{"location":"LICENSE/#6-conveying-non-source-forms","title":"6. Conveying Non-Source Forms.","text":"

    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.

    "},{"location":"LICENSE/#7-additional-terms","title":"7. Additional Terms.","text":"

    \"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.

    "},{"location":"LICENSE/#8-termination","title":"8. Termination.","text":"

    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.

    "},{"location":"LICENSE/#9-acceptance-not-required-for-having-copies","title":"9. Acceptance Not Required for Having Copies.","text":"

    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.

    "},{"location":"LICENSE/#10-automatic-licensing-of-downstream-recipients","title":"10. Automatic Licensing of Downstream Recipients.","text":"

    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.

    "},{"location":"LICENSE/#11-patents","title":"11. Patents.","text":"

    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.

    "},{"location":"LICENSE/#12-no-surrender-of-others-freedom","title":"12. No Surrender of Others' Freedom.","text":"

    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.

    "},{"location":"LICENSE/#13-remote-network-interaction-use-with-the-gnu-general-public-license","title":"13. Remote Network Interaction; Use with the GNU General Public License.","text":"

    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.

    "},{"location":"LICENSE/#14-revised-versions-of-this-license","title":"14. Revised Versions of this License.","text":"

    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.

    "},{"location":"LICENSE/#15-disclaimer-of-warranty","title":"15. Disclaimer of Warranty.","text":"

    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.

    "},{"location":"LICENSE/#16-limitation-of-liability","title":"16. Limitation of Liability.","text":"

    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.

    "},{"location":"LICENSE/#17-interpretation-of-sections-15-and-16","title":"17. Interpretation of Sections 15 and 16.","text":"

    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

    "},{"location":"LICENSE/#how-to-apply-these-terms-to-your-new-programs","title":"How to Apply These Terms to Your New Programs","text":"

    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.

        <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n

    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 https://www.gnu.org/licenses/.

    "},{"location":"about/","title":"TM-Admin","text":"

    Administrative functions for Tasking Manager style projects. There is a lot of shared functionality between Tasking Manager style projects, so rather than having duplicate implementations, the goal of this project is to provide that functionality in a way it can be shared across multiple projects.

    These are implemented as python modules, and can be used in the backend of a Tasking Manager style website. While it is possible to have multiple projects access a single database, there is also support to exchange data between projects if they are all using their own database. There is more detail on the inter-project communication.

    "},{"location":"about/#user-management","title":"User Management","text":"

    Handles user profiles. While it is recommended, it is not required for all users to have an OSM ID. With an OSM ID, AUTH2 works, so users only have to login once, but can use multipe projects.

    "},{"location":"about/#organization-management","title":"Organization Management","text":"

    Handles organization profiles. Some organizations use multiple projects, so this just shares the profile data so it doesn't have to be entered multiple times.

    "},{"location":"about/#project-management","title":"Project Management","text":"

    Handles the project. A project in it's simplest form is an area of interest as a polygon, the name, the description, and a project manager. In addition it can access the tasks table for task specific data.

    "},{"location":"about/#task-management","title":"Task Management","text":"

    Handles the tasks. A task is a polygon within the project area of interest.

    "},{"location":"about/#team-management","title":"Team Management","text":"

    Handles OSM Teams profiles.

    "},{"location":"api/","title":"API Docs for TM-Admin","text":""},{"location":"api/#tmadmin_managepy","title":"tmadmin_manage.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage","title":"TmAdminManage","text":"
    TmAdminManage(dburi='localhost/tm_admin')\n

    Bases: object

    Source code in tm_admin/tmadmin_manage.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\"\n             ):\n    # this is for processing an SQL diff\n    self.columns = {'drop': list(), 'add': list()}\n    self.dburi = dict()\n    self.pg = None\n    if dburi:\n        self.dburi = uriParser(dburi)\n        self.pg = PostgresClient(dburi)\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.applyDiff","title":"applyDiff","text":"
    applyDiff(difffile, table)\n

    Modify a postgres database table schema

    Parameters:

    Name Type Description Default difffile str

    The filespec of the SQL diff

    required

    Returns:

    Type Description bool

    The status on applying the SQL diff

    Source code in tm_admin/tmadmin_manage.py
    def applyDiff(self,\n              difffile: str,\n              table: str,\n            ):\n    \"\"\"\n    Modify a postgres database table schema\n\n    Args:\n        difffile (str): The filespec of the SQL diff\n\n    Returns:\n        (bool): The status on applying the SQL diff\n    \"\"\"\n    self.readDiff(difffile)\n    if len(self.columns['drop']) > 0 or len(self.columns['add']) > 0:\n        return True\n\n    drop = f\"ALTER TABLE {table} DROP COLUMN\"\n    add = f\"ALTER TABLE {table} ADD COLUMN\"\n    return False\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.dump","title":"dump","text":"
    dump()\n

    Dump the internal data structures, for debugging only

    Source code in tm_admin/tmadmin_manage.py
    def dump(self):\n    \"\"\"Dump the internal data structures, for debugging only\"\"\"\n    if len(self.columns['drop']) > 0 or len(self.columns['add']) > 0:\n        print(\"Changes to the table schema\")\n        for column in self.columns['drop']:\n            print(f\"\\tDropping column {column}\")\n        for column in self.columns['add']:\n            for k, v in column.items():\n                print(f\"\\tAdding column {k} as {v}\")\n    print(\"Database parameters\")\n    for k, v in self.dburi.items():\n        if v is not None:\n            print(f\"\\t{k} = {v}\")\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.createDB","title":"createDB","text":"
    createDB(dburi=None)\n

    Create a postgres database.

    Args:

    Returns:

    Source code in tm_admin/tmadmin_manage.py
    def createDB(self,\n            dburi: str = None,\n            ):\n    \"\"\"\n    Create a postgres database.\n\n    Args:\n\n    Returns:\n\n    \"\"\"\n    # sql = \"CREATE EXTENSION IF NOT EXISTS postgis; CREATE EXTENSION IF NOT EXISTS hstore\"\n    if dburi:\n        self.dburi = uriParser(dburi)\n    # FIXME: CREATE DATABASE cannot run inside a transaction block\n    # self.pg.createDB(self.dburi)\n    with open(f\"{rootdir}/types_tm.sql\", 'r') as file:\n        self.pg.dbcursor.execute(file.read())\n        file.close()\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.createTable","title":"createTable","text":"
    createTable(sqlfile)\n

    Create a table in the database.

    Parameters:

    Name Type Description Default sqlfile str

    The SQL schema for this table

    required dburi str

    The URI string for the database connection.

    required

    Returns:

    Type Description bool

    The table creation status

    Source code in tm_admin/tmadmin_manage.py
    def createTable(self,\n                sqlfile: str,\n                ):\n    \"\"\"\n    Create a table in the database.\n\n    Args:\n        sqlfile (str): The SQL schema for this table\n        dburi (str): The URI string for the database connection.\n\n    Returns:\n        (bool): The table creation status\n    \"\"\"\n    sql = \"\"\n    with open(sqlfile, 'r') as file:\n        # cleanup the file before submitting\n        for line in file.readlines():\n            if line[:2] != '--' and len(line) > 0:\n                sql += line\n        file.close()\n        return self.pg.createTable(sql)\n\n    path = Path(sqlfile)\n    version = f\"INSERT INTO schemas(schema, version) VALUES('{sqlfile.stem}', 1.0)\"\n    result = self.pg.dbcursor.execute(version)\n\n    return sql\n
    "},{"location":"api/#tm_admin.tmadmin_manage.TmAdminManage.readDiff","title":"readDiff","text":"
    readDiff(diff)\n

    Read in a diff produced by git diff into a data structure that can be used to updgrade a table's schema.

    Parameters:

    Name Type Description Default diff str

    the name of the SQL diff file

    required

    Returns:

    Type Description dict

    The columns to drop or add from a table

    Source code in tm_admin/tmadmin_manage.py
    def readDiff(self,\n             diff: str,\n             ):\n    \"\"\"\n    Read in a diff produced by git diff into a data structure\n    that can be used to updgrade a table's schema.\n\n    Args:\n        diff (str): the name of the SQL diff file\n\n    Returns:\n        (dict): The columns to drop or add from a table\n    \"\"\"\n    with open(diff, 'r') as file:\n        for line in file.readlines():\n            # it's the header\n            if line[:3] == '---' or line[:3] == '+++' or  line[:2] == '@@':\n                continue\n            # Ignore code block\n            if line[0] == ' ':\n                continue\n            tmp = ' '.join(line.split()).split()\n            if tmp[0] == '-':\n                self.columns['drop'].append(tmp[1])\n            if tmp[0] == '+':\n                if tmp[1] in self.columns['drop']:\n                    self.columns['drop'].remove(tmp[1])\n                    continue\n                if len(tmp) == 3:\n                    self.columns['add'].append({tmp[1]: tmp[2][:-1]})\n                elif len(tmp) == 4:\n                    self.columns['add'].append({tmp[1]: f\"{tmp[2]} {tmp[3][:-1]}\"})\n    return self.columns\n
    "},{"location":"api/#tm_admin.tmadmin_manage.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tmadmin_manage.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"config\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Manage the postgres database for the tm-admin project\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    choices = ['create', 'migrate']\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    # parser.add_argument(\"-d\", \"--diff\", help=\"SQL file diff for migrations\")\n    # parser.add_argument(\"-p\", \"--proto\", help=\"Generate the .proto file from the YAML file\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    parser.add_argument(\"-c\", \"--cmd\", choices=choices, default='create',\n                            help=\"Command\")\n    args, known = parser.parse_known_args()\n\n    if len(argv) <= 1:\n        parser.print_help()\n        quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    # The base class that does all the work\n    tm = TmAdminManage(args.uri)\n    tm.createDB()\n\n    # This database tables stores the versions of the table schemas,\n    # and is only used for updating the table schemas.\n    result = tm.createTable(f\"{rootdir}/schemas.sql\")\n\n    # This class generates all the output files.\n    gen = Generator()\n\n    for yamlfile in known:\n        gen.readConfig(yamlfile)\n        out = gen.createSQLTable()\n        name = yamlfile.replace('.yaml', '.sql')\n        with open(name, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {name} to disk\")\n            file.close()\n        tm.createTable(name)\n        name = yamlfile.replace('.yaml', '.proto')\n        out = gen.createProtoMessage()\n        with open(name, 'w') as file:\n            file.writelines([str(i)+'\\n' for i in out])\n            log.info(f\"Wrote {name} to disk\")\n            file.close()\n        out = gen.createPyClass()\n        py = yamlfile.replace('.yaml', '_class.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n        out = gen.createPyMessage()\n        py = yamlfile.replace('.yaml', '_proto.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n
    "},{"location":"api/#dbsupportpy","title":"dbsupport.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.dbsupport.DBSupport","title":"DBSupport","text":"
    DBSupport(table, dburi='localhost/tm_admin')\n

    Bases: object

    Parameters:

    Name Type Description Default table str

    The table to use for this connection.

    required dburi str

    The URI string for the database connection.

    'localhost/tm_admin'

    Returns:

    Type Description DBSupport

    An instance of this class

    Source code in tm_admin/dbsupport.py
    def __init__(self,\n             table: str,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A base class since all tables have the same structure for queries.\n\n    Args:\n        table (str): The table to use for this connection.\n        dburi (str): The URI string for the database connection.\n\n    Returns:\n        (DBSupport): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.table = table\n    profile = f\"{table.capitalize()}Table()\"\n    self.profile = eval(profile)\n    if dburi:\n        self.pg = PostgresClient(dburi)\n    self.types = dir(tm_admin.types_tm)\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.createTable","title":"createTable","text":"
    createTable(obj)\n

    Create a table in a postgres database.

    Parameters:

    Name Type Description Default obj

    The config data for the table.

    required Source code in tm_admin/dbsupport.py
    def createTable(self,\n                obj,\n                ):\n    \"\"\"\n    Create a table in a postgres database.\n\n    Args:\n        obj: The config data for the table.\n    \"\"\"\n    sql = f\"INSERT INTO {self.table}(id, \"\n    for column,value in obj.data.items():\n        # print(f\"{column} is {type(value)}\")\n        if type(value) == str:\n            # FIXME: for now ignore timestamps, as they're meaningless\n            # between projects\n            try:\n                if parse(value):\n                    continue\n            except:\n                # it's a string, but not a date\n                pass\n        if value is not None:\n            sql += f\"{column},\"\n    sql = sql[:-1]\n    sql += f\") VALUES(\"\n    for column,value in obj.data.items():\n        try:\n            if parse(value):\n                continue\n        except:\n            pass\n        if column == 'id':\n            sql += f\"nextval('public.{self.table}_id_seq'),\"\n            continue\n        if value is None:\n            continue\n        elif type(value) == datetime:\n            continue\n        elif type(value) == int:\n            sql += f\"{value},\"\n        elif type(value) == bool:\n            if value:\n                sql += f\"true,\"\n            else:\n                sql += f\"false,\"\n        elif type(value) == str:\n            sql += f\"'{value}',\"\n\n    #print(sql[:-1])\n    result = self.pg.dbcursor.execute(f\"{sql[:-1]});\")\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.updateTable","title":"updateTable","text":"
    updateTable(id=None)\n

    Updates an existing table in the database

    Parameters:

    Name Type Description Default id int

    The ID of the dataset to update

    None Source code in tm_admin/dbsupport.py
    def updateTable(self,\n                id: int = None,\n                ):\n    \"\"\"\n    Updates an existing table in the database\n\n    Args:\n        id (int): The ID of the dataset to update\n    \"\"\"\n    sql = f\"UPDATE {self.table} SET\"\n    if not id:\n        id = profile.data['id']\n    for column,value in self.profile.data.items():\n        name = column.replace('_', '').capitalize()\n        if name in self.types:\n            # FIXME: this needs to not be hardcoded!\n            tmp = tm_admin.types_tm.Mappinglevel._member_names_\n            if type(value) == str:\n                level = value\n            else:\n                level = tmp[value-1]\n            sql += f\" {column}='{level}'\"\n            continue\n        if value:\n            try:\n                # FIXME: for now ignore timestamps, as they're meaningless\n                # between projects\n                if parse(value):\n                    continue\n            except:\n                # it's a string, but not a date\n                pass\n            sql += f\" {column}='{value}',\"\n    sql += f\" WHERE id='{id}'\"\n    # print(sql)\n    result = self.pg.dbcursor.execute(f\"{sql[:-1]}';\")\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.resetSequence","title":"resetSequence","text":"
    resetSequence()\n

    Reset the postgres sequence to zero.

    Source code in tm_admin/dbsupport.py
    def resetSequence(self):\n    \"\"\"\n    Reset the postgres sequence to zero.\n    \"\"\"\n    sql = f\"ALTER SEQUENCE public.{self.table}_id_seq RESTART;\"\n    self.pg.dbcursor.execute(sql)\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByID","title":"getByID","text":"
    getByID(id)\n

    Return the data for the ID in the table.

    Parameters:

    Name Type Description Default id int

    The ID of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByID(self,\n            id: int,\n            ):\n    \"\"\"\n    Return the data for the ID in the table.\n\n    Args:\n        id (int): The ID of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE id='{id}'\"\n    result = self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    if entry:\n        for column in self.profile.data.keys():\n            index = 0\n            for column in self.profile.data.keys():\n                data[column] = entry[index]\n                index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByName","title":"getByName","text":"
    getByName(name)\n

    Return the data for the name in the table.

    Parameters:

    Name Type Description Default name str

    The name of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByName(self,\n            name: str,\n            ):\n    \"\"\"\n    Return the data for the name in the table.\n\n    Args:\n        name (str): The name of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE username='{name}' LIMIT 1\"\n    self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    for column in self.profile.data.keys():\n        index = 0\n        for column in self.profile.data.keys():\n            data[column] = entry[index]\n            index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getAll","title":"getAll","text":"
    getAll()\n

    Return all the data in the table.

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getAll(self):\n    \"\"\"\n    Return all the data in the table.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table};\"\n    self.pg.dbcursor.execute(sql)\n    result = self.pg.dbcursor.fetchall()\n    out = list()\n    if result:\n        for entry in result:\n            data = dict()\n            for column in self.profile.data.keys():\n                index = 0\n                for column in self.profile.data.keys():\n                    data[column] = entry[index]\n                    index += 1\n            out.append(data)\n    else:\n        log.debug(f\"No data returned from query\")\n\n    return out\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByWhere","title":"getByWhere","text":"
    getByWhere(where)\n

    Return the data for the where clause in the table.

    Parameters:

    Name Type Description Default where str

    The where clzuse of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByWhere(self,\n            where: str,\n            ):\n    \"\"\"\n    Return the data for the where clause in the table.\n\n    Args:\n        where (str): The where clzuse of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE {where}\"\n    print(sql)\n    result = self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    if entry:\n        for column in self.profile.data.keys():\n            index = 0\n            for column in self.profile.data.keys():\n                data[column] = entry[index]\n                index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.getByLocation","title":"getByLocation","text":"
    getByLocation(location, table='projects')\n

    Return the database records in a table using GPS coordinates.

    Parameters:

    Name Type Description Default location Point

    The location to use to find the project or task.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/dbsupport.py
    def getByLocation(self,\n            location: Point,\n            table: str = 'projects',\n            ):\n    \"\"\"\n    Return the database records in a table using GPS coordinates.\n\n    Args:\n        location (Point): The location to use to find the project or task.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    data = dict()\n    ewkt = shape(location)\n    sql = f\"SELECT * FROM {table} WHERE ST_CONTAINS(ST_GeomFromEWKT('SRID=4326;{ewkt}') geom)\"\n    self.pg.dbcursor.execute(sql)\n    entry = self.pg.dbcursor.fetchall()\n    for column in self.profile.data.keys():\n        index = 0\n        for column in self.profile.data.keys():\n            data[column] = entry[index]\n            index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.deleteByID","title":"deleteByID","text":"
    deleteByID(id)\n

    Delete the record for the ID in the table.

    Parameters:

    Name Type Description Default id int

    The ID of the dataset to delete.

    required Source code in tm_admin/dbsupport.py
    def deleteByID(self,\n            id: int,\n            ):\n    \"\"\"\n    Delete the record for the ID in the table.\n\n    Args:\n        id (int): The ID of the dataset to delete.\n    \"\"\"\n    sql = f\"DELETE FROM {self.table} WHERE id='{id}'\"\n    result = self.pg.dbcursor.execute(sql)\n
    "},{"location":"api/#tm_admin.dbsupport.DBSupport.updateColumn","title":"updateColumn","text":"
    updateColumn(id, data)\n

    This updates a single column in the database. If you want to update multiple columns, use self.updateTable() instead.

    Parameters:

    Name Type Description Default id int

    The ID of the user to update

    required data dict

    The column and new value

    required Source code in tm_admin/dbsupport.py
    def updateColumn(self,\n                id: int,\n                data: dict,\n                ):\n    \"\"\"\n    This updates a single column in the database. If you want to update multiple columns,\n    use self.updateTable() instead.\n\n    Args:\n        id (int): The ID of the user to update\n        data (dict): The column and new value\n    \"\"\"\n    [[column, value]] = data.items()\n    sql = f\"UPDATE {self.table} SET {column}='{value}' WHERE id='{id}'\"\n    # print(sql)\n    try:\n        result = self.pg.dbcursor.execute(f\"{sql};\")\n        return True\n    except:\n        return False\n
    "},{"location":"api/#tm_admin.dbsupport.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/dbsupport.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    org = DBSupport('organizations', args.uri)\n    # organization.resetSequence()\n    all = org.getAll()\n\n    # Don't pass id, let postgres auto increment\n    ut = OrganizationsTable(name='test org', slug=\"slug\", orgtype=1)\n#                            orgtype=tm_admin.types_tm.Organizationtype.FREE)\n    org.createTable(ut)\n    # print(all)\n\n    all = org.getByID(1)\n    print(all)\n\n    all = org.getByName('fixme')\n    print(all)\n
    "},{"location":"api/#generatorpy","title":"generator.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.generator.Generator","title":"Generator","text":"
    Generator(filespec=None)\n

    Bases: object

    Parameters:

    Name Type Description Default filespec str

    The config file to use as source.

    None

    Returns:

    Type Description Generator

    An instance of this class

    Source code in tm_admin/generator.py
    def __init__(self,\n            filespec: str = None,\n            ):\n    \"\"\"\n    A class that generates the output files from the config data.\n\n    Args:\n        filespec (str): The config file to use as source.\n\n    Returns:\n        (Generator): An instance of this class\n    \"\"\"\n    self.filespec = None\n    self.yaml = None\n    if filespec:\n        self.filespec = Path(filespec)\n        self.yaml = YamlFile(filespec)\n    self.createTypes()\n    self.yaml2py = {'int32': 'int',\n                'int64': 'int',\n                'bool': 'bool',\n                'string': 'str',\n                'bytes': 'bytes',\n                'timestamp': 'timestamp without time zone',\n                'polygon': 'Polygon',\n                'point': 'Point',\n                }\n\n    self.yaml2sql = {'int32': 'int',\n                'int64': 'bigint',\n                'bool': 'bool',\n                'string': 'character varying',\n                'bytes': 'bytea',\n                'timestamp': 'timestamp without time zone',\n                'polygon': 'polygon',\n                'point': 'point',\n                }\n
    "},{"location":"api/#tm_admin.generator.Generator.readConfig","title":"readConfig","text":"
    readConfig(filespec)\n

    Reads in the YAML config file.

    Parameters:

    Name Type Description Default filespec str

    The config file to use as source.

    required Source code in tm_admin/generator.py
    def readConfig(self,\n                filespec: str,\n                ):\n    \"\"\"\n    Reads in the YAML config file.\n\n    Args:\n        filespec (str): The config file to use as source.\n    \"\"\"\n    self.filespec = Path(filespec)\n    self.yaml = YamlFile(filespec)\n
    "},{"location":"api/#tm_admin.generator.Generator.createTypes","title":"createTypes","text":"
    createTypes()\n

    Creates the enum files, which need to be done first, since the other generated files reference these.

    Source code in tm_admin/generator.py
    def createTypes(self):\n    \"\"\"\n    Creates the enum files, which need to be done first, since the\n    other generated files reference these.\n    \"\"\"\n    gen = self.readConfig(f'{rootdir}/types.yaml')\n    out = self.createSQLEnums()\n    with open('types_tm.sql', 'w') as file:\n        file.write(out)\n        file.close()\n    out = self.createProtoEnums()\n    with open('types_tm.proto', 'w') as file:\n        file.write(out)\n        file.close()\n    out = self.createPyEnums()\n    with open('types_tm.py', 'w') as file:\n        file.write(out)\n        file.close()\n
    "},{"location":"api/#tm_admin.generator.Generator.createSQLEnums","title":"createSQLEnums","text":"
    createSQLEnums()\n

    Create an input file for postgres of the custom types.

    Returns:

    Type Description str

    The source for postgres to create the SQL types.

    Source code in tm_admin/generator.py
    def createSQLEnums(self):\n    \"\"\"\n    Create an input file for postgres of the custom types.\n\n    Returns:\n        (str): The source for postgres to create the SQL types.\n    \"\"\"\n    out = \"\"\n    for entry in self.yaml.yaml:\n        [[table, values]] = entry.items()\n        out += f\"DROP TYPE IF EXISTS public.{table} CASCADE;\\n\"\n        out += f\"CREATE TYPE public.{table} AS ENUM (\\n\"\n        for line in values:\n            out += f\"\\t'{line}',\\n\"\n        out = out[:-2]\n        out += \"\\n);\\n\"\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createProtoEnums","title":"createProtoEnums","text":"
    createProtoEnums()\n

    Create an input file for postgres of the custom types.

    Returns:

    Type Description str

    The source for protoc to create the Protobuf types.

    Source code in tm_admin/generator.py
    def createProtoEnums(self):\n    \"\"\"\n    Create an input file for postgres of the custom types.\n\n    Returns:\n        (str): The source for protoc to create the Protobuf types.\n    \"\"\"\n    out = \"syntax = 'proto3';\\n\\n\"\n    for entry in self.yaml.yaml:\n        index = 0\n        [[table, values]] = entry.items()\n        out += f\"enum {table.capitalize()} {{\\n\"\n        for line in values:\n            out += f\"\\t{line} = {index};\\n\"\n            index += 1\n        out += \"};\\n\\n\"\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createPyEnums","title":"createPyEnums","text":"
    createPyEnums()\n

    Create an input file for python of the custom types.

    Returns:

    Type Description str

    The source for python to create the enums.

    Source code in tm_admin/generator.py
    def createPyEnums(self):\n    \"\"\"\n    Create an input file for python of the custom types.\n\n    Returns:\n        (str): The source for python to create the enums.\n    \"\"\"\n    out = f\"import logging\\n\"\n    out += f\"from enum import IntEnum\\n\"\n    for entry in self.yaml.yaml:\n        index = 1\n        [[table, values]] = entry.items()\n        out += f\"class {table.capitalize()}(IntEnum):\\n\"\n        for line in values:\n            out += f\"\\t{line} = {index}\\n\"\n            index += 1\n        out += '\\n'\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createPyMessage","title":"createPyMessage","text":"
    createPyMessage()\n

    Creates a python class wrapper for protobuf.

    Returns:

    Type Description str

    The source for python to create the class stubs.

    Source code in tm_admin/generator.py
        def createPyMessage(self):\n        \"\"\"\n        Creates a python class wrapper for protobuf.\n\n        Returns:\n            (str): The source for python to create the class stubs.\n        \"\"\"\n        out = f\"\"\"\nimport logging\nfrom datetime import timedelta\nfrom shapely.geometry import Polygon, Point, shape\n\nlog = logging.getLogger(__name__)\n        \"\"\"\n        for entry in self.yaml.yaml:\n            [[table, settings]] = entry.items()\n            out += f\"\"\"\nclass {table.capitalize()}Message(object):\n    def __init__(self, \n            \"\"\"\n            # print(table, settings)\n            share = False\n            datatype = None\n            data = \"        self.data = {\"\n            for item in settings:\n                if type(item) == dict:\n                    [[k, v]] = item.items()\n                    for k1 in v:\n                        if type(k1) == dict:\n                            [[k2, v2]] = k1.items()\n                            if k2 == 'share' and v2:\n                                share = True\n                                # out += f\"\\nshare {k1}\"\n                        elif type(k1) == str:\n                            if k1 in self.yaml2py:\n                                datatype = self.yaml2py[k1]\n                            else:\n                                datatype = item\n                                continue\n                    if share:\n                        share = False\n                        out += f\"{k}: {datatype} = None, \"\n                        data += f\"'{k}': {k}, \"\n        out += \"):\\n\"\n        out += f\"{data[:-2]}}}\\n\"\n\n        return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createPyClass","title":"createPyClass","text":"
    createPyClass()\n

    Creates a python class wrapper for the protobuf messages.

    Returns:

    Type Description str

    The source for python to create the class stubs.

    Source code in tm_admin/generator.py
        def createPyClass(self):\n        \"\"\"\n        Creates a python class wrapper for the protobuf messages.\n\n        Returns:\n            (str): The source for python to create the class stubs.\n        \"\"\"\n        out = f\"\"\"\nimport logging\nfrom datetime import datetime\nimport tm_admin.types_tm\nfrom shapely.geometry import Point, LineString, Polygon\n\nlog = logging.getLogger(__name__)\n\n        \"\"\"\n        for entry in self.yaml.yaml:\n            [[table, settings]] = entry.items()\n            out += f\"\"\"\nclass {table.capitalize()}Table(object):\n    def __init__(self, \n            \"\"\"\n            datatype = None\n            now = datetime.now()\n            data = \"            self.data = {\"\n            for item in settings:\n                if type(item) == dict:\n                    [[k, v]] = item.items()\n                    for k1 in v:\n                        if type(k1) == dict:\n                            continue\n                        elif type(k1) == str:\n                            if k1[:15] == 'public.geometry':\n                                datatype = k1[16:-1].split(',')[0]\n                                log.warning(f\"GEOMETRY: {datatype}\")\n                            elif k1[:7] == 'public.':\n                                # FIXME: It's in the SQL types\n                                # log.warning(f\"SQL ENUM {k1}!\")\n                                datatype = f\"tm_admin.types_tm.{k1[7:].capitalize()}\"\n                            elif k1 in self.yaml2py:\n                                datatype = self.yaml2py[k1]\n                            else:\n                                datatype = item\n                                continue\n                        if k1 == 'bool':\n                            out += f\"{k}: {datatype} = False, \"\n                        elif k1 == 'timestamp':\n                            out += f\"{k}: datetime = '{datetime.now()}', \"\n                        elif k1[:7] == 'public.':\n                            # defined = f\"tm_admin.types_tm.{k1[7:].capitalize()}()\"\n                            # out += f\"{k}: {defined} =  1, \"\n                            out += f\"{k}: int =  1, \"\n                        else:\n                            out += f\"{k}: {datatype} = None, \"\n                        # print(k)\n                        data += f\"'{k}': {k}, \"\n        out = out[:-2]\n        out += \"):\\n\"\n        out += f\"{data[:-2]}}}\\n\"\n\n        return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createProtoMessage","title":"createProtoMessage","text":"
    createProtoMessage()\n

    Create the source for a protobuf message

    Returns:

    Type Description list

    The protobuf message source.

    Source code in tm_admin/generator.py
    def createProtoMessage(self):\n    \"\"\"\n    Create the source for a protobuf message\n\n    Returns:\n        (list): The protobuf message source.\n    \"\"\"\n    pb = ProtoBuf()\n    out = pb.createTableProto(self.yaml.yaml)\n    return out\n
    "},{"location":"api/#tm_admin.generator.Generator.createSQLTable","title":"createSQLTable","text":"
    createSQLTable()\n

    Create the source for an SQL table.

    Returns:

    Type Description str

    The protobuf message source.

    Source code in tm_admin/generator.py
        def createSQLTable(self):\n        \"\"\"\n        Create the source for an SQL table.\n\n        Returns:\n            (str): The protobuf message source.\n        \"\"\"\n        out = \"-- Do not edit this file, it's generated from the yaml file\\n\\n\"\n        sequence = list()\n        for entry in self.yaml.yaml:\n            [[table, values]] = entry.items()\n            out += f\"DROP TABLE IF EXISTS public.{table} CASCADE;\\n\"\n            out += f\"CREATE TABLE public.{table} (\\n\"\n            unique = \"\"\n            typedef = \"\"\n            for line in values:\n                # these are usually from the types.yaml file, which have no\n                # settings beyond the enum value.\n                # if type(line) == str:\n                #     print(f\"SQL TABLE: {typedef} {line}\")\n                #     typedef = table\n                #     continue\n                [[k, v]] = line.items()\n                required = \"\"\n                array = \"\"\n                public = False\n                primary = \"\"\n                for item in v:\n                    if type(item) == dict:\n                        if 'sequence' in item and item['sequence']:\n                            sequence.append(k)\n                            primary = k\n                        if 'required' in item and item['required']:\n                            required = ' NOT NULL'\n                        if 'array' in item and item['array']:\n                            array = \"[]\"\n                        if 'unique' in item and item['unique']:\n                            unique = k\n                    if len(v) >= 2:\n                        if 'required' in v[1] and v[1]['required']:\n                            required = ' NOT NULL'\n                    if type(item) == str:\n                        if item[:7] == 'public.' and item[15:8] != 'geometry':\n                            public = True\n                        # elif item[15:8] == 'geometry':\n                        #     out += f\"\\t{k} {self.yaml2py[v[0]]}{array}{required},\\n\"\n                if public:\n                    out += f\"\\t{k} {v[0]}{array}{required},\\n\"\n                else:\n                    # print(v)\n                    # FIXME: if this produces an error, check the yaml file as this\n                    # usually means the type field isn't first in the list.\n                    out += f\"\\t{k} {self.yaml2sql[v[0]]}{array}{required},\\n\"\n            if len(unique) > 0:\n                out += f\"\\tUNIQUE({unique})\\n);\\n\"\n\n            if len(sequence) > 0:\n                for key in sequence:\n                    out += f\"\"\"\nDROP SEQUENCE IF EXISTS public.{table}_{key}_seq CASCADE;\nCREATE SEQUENCE public.{table}_{key}_seq\n        START WITH 1\n        INCREMENT BY 1\n        NO MINVALUE\n        NO MAXVALUE\n        CACHE 1;\n\"\"\"\n        return out\n
    "},{"location":"api/#tm_admin.generator.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/generator.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"generator\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Generate SQL, Protobuf, and Python data structures\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    args, known = parser.parse_known_args()\n\n    if len(argv) <= 1:\n        parser.print_help()\n        quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    gen = Generator()\n    for config in known:\n        gen.readConfig(config)\n        out = gen.createSQLTable()\n        sqlfile = config.replace('.yaml', '.sql')\n        path = Path(sqlfile)\n        #if path.exists():\n        #    path.rename(file.replace('.sql', '_bak.sql'))\n        with open(sqlfile, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {sqlfile} to disk\")\n            file.close()\n        proto = config.replace('.yaml', '.proto')\n        out = gen.createProtoMessage()\n        with open(proto, 'w') as file:\n            file.writelines([str(i)+'\\n' for i in out])\n            log.info(f\"Wrote {proto} to disk\")\n            file.close()\n\n        out = gen.createPyClass()\n        py = config.replace('.yaml', '_class.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n        # print(out)\n        out = gen.createPyMessage()\n        py = config.replace('.yaml', '_proto.py')\n        with open(py, 'w') as file:\n            file.write(out)\n            log.info(f\"Wrote {py} to disk\")\n            file.close()\n
    "},{"location":"api/#protopy","title":"proto.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.proto.ProtoBuf","title":"ProtoBuf","text":"
    ProtoBuf(sqlfile=None)\n

    Bases: object

    Returns:

    Type Description ProtoBuf

    An instance of this class

    Source code in tm_admin/proto.py
    def __init__(self,\n            sqlfile: str = None,\n            ):\n    \"\"\"\n    A class that generates protobuf files from the config data.\n\n    Returns:\n        (ProtoBuf): An instance of this class\n    \"\"\"\n    self.sqlfile = sqlfile\n
    "},{"location":"api/#tm_admin.proto.ProtoBuf.createEnumProto","title":"createEnumProto","text":"
    createEnumProto(enums)\n

    Process a list of enums into the protobuf version.

    Parameters:

    Name Type Description Default enums dict

    The list of tables to generate a protobuf for.

    required

    Returns:

    Type Description list

    The list of enums in protobuf format

    Source code in tm_admin/proto.py
    def createEnumProto(self,\n                enums: dict,\n                ):\n    \"\"\"\n    Process a list of enums into the protobuf version.\n\n    Args:\n        enums (dict): The list of tables to generate a protobuf for.\n\n    Returns:\n        (list): The list of enums in protobuf format\n    \"\"\"\n    out = list()\n    out.append(f\"syntax = 'proto3';\")\n    for name, value in enums.items():\n        index = 0\n        out.append(f\"enum {name.capitalize()} {{\")\n        for entry in value:\n            out.append(f\"\\t{entry} = {index};\")\n            index += 1\n        out.append('};')\n\n    return out\n
    "},{"location":"api/#tm_admin.proto.ProtoBuf.createTableProto","title":"createTableProto","text":"
    createTableProto(tables)\n

    Process a list of tables into the protobuf version.

    Parameters:

    Name Type Description Default tables list

    The list of tables to generate a protobuf for.

    required

    Returns:

    Type Description list

    The list of tables in protobuf format

    Source code in tm_admin/proto.py
    def createTableProto(self,\n                tables: list,\n                ):\n    \"\"\"\n    Process a list of tables into the protobuf version.\n\n    Args:\n        tables (list): The list of tables to generate a protobuf for.\n\n    Returns:\n        (list): The list of tables in protobuf format\n    \"\"\"\n    out = list()\n    out.append(f\"syntax = 'proto3';\")\n    # types.proto is generated from the types.yaml file.\n    # out.append(\"import 'types_tm.proto';\")\n    out.append(\"package tmadmin;\")\n    out.append(\"import 'types_tm.proto';\")\n    out.append(\"import 'google/protobuf/timestamp.proto';\")\n\n    convert = {'timestamp': \"google.protobuf.Timestamp\",\n               'polygon': 'bytes', 'point': 'bytes'}\n    for table in tables:\n        index = 1\n        for key, value in table.items():\n            out.append(f\"message {key} {{\")\n            optional = \"\"\n            repeated = \"\"\n            for data in value:\n                # print(f\"DATA: {data}\")\n                for entry, settings in data.items():\n                    # print(f\"DATA: {entry} = {settings}\")\n                    #    datatype = settings[0][7:].capitalize()\n                    share = False\n                    array = \"\"\n                    datatype = None\n                    required = \"\"\n                    optional = \"\"\n                    for item in settings:\n                        if type(item) == str:\n                            # print(f\"DATA: {item}\")\n                            if item[:15] == 'public.geometry':\n                                datatype = \"bytes\"\n                            elif item[:7] == 'public.':\n                                datatype = item[7:].capitalize()\n                            elif item in convert:\n                                datatype = convert[item]\n                            else:\n                                datatype = item\n                            continue\n                        if type(item) == dict:\n                            [[k, v]] = item.items()\n                            if k == 'required' and v:\n                                required = k\n                            if k == 'optional' and v:\n                                optional = k\n                            if k == 'share':\n                                share = True\n                            if k == 'array':\n                                array = \"repeated\"\n                    if not share:\n                        continue\n                    # out.append(f\"\\t{required} {optional} {datatype} {entry} = {index};\")\n                    out.append(f\"\\t {array} {optional} {datatype} {entry} = {index};\")\n                    index += 1\n        out.append(f\"}}\")\n\n    return out\n
    "},{"location":"api/#tm_admin.proto.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/proto.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"config\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Manage the postgres database for the tm-admin project\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    args, known = parser.parse_known_args()\n\n    if len(argv) <= 1:\n        parser.print_help()\n        # quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    tm = ProtoBuf()\n    for table in known:\n        out1, out2 = tm.createProtoFromSQL(table)\n        name = table.replace('.sql', '.proto')\n        # pyfile = table.replace('.sql', '.py')\n        # xx = tm.protoToDict(name)\n        # name = table.replace('.yaml', '.proto')\n        out = tm.createTableProto()\n        if len(out1) > 0:\n            with open(name, 'w') as file:\n                file.writelines([str(i)+'\\n' for i in out1])\n                file.close()\n        if len(out2) > 0:\n            with open(name, 'w') as file:\n                file.writelines([str(i)+'\\n' for i in out2])\n                file.close()\n        log.info(f\"Wrote {name} to disk\")\n
    "},{"location":"api/#tmserverpy","title":"tmserver.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tmserver.TMServer","title":"TMServer","text":"
    TMServer(target)\n

    Bases: object

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description TMServer

    An instance of this class

    Source code in tm_admin/tmserver.py
    def __init__(self,\n             target: str,\n             ):\n    \"\"\"\n    Instantiate a server\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (TMServer): An instance of this class\n    \"\"\"\n    self.hosts = YamlFile(f\"{rootdir}/services.yaml\")\n    log.debug(\"Starting server\")\n    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n    tm_admin.services_pb2_grpc.add_TMAdminServicer_to_server(\n        RequestServicer(), server\n    )\n    # Enable reflection for grpc_cli\n    SERVICE_NAMES = (\n        tm_admin.services_pb2.DESCRIPTOR.services_by_name['TMAdmin'].full_name,\n        reflection.SERVICE_NAME,\n    )\n    reflection.enable_server_reflection(SERVICE_NAMES, server)\n\n    target = self.getTarget(target)\n    [[host, port]] = target.items()\n    # FIXME: this needs to use SSL for a secure connection\n    server.add_insecure_port(f\"[::]:{port}\")\n    server.start()\n    server.wait_for_termination()\n
    "},{"location":"api/#tm_admin.tmserver.TMServer.getTarget","title":"getTarget","text":"
    getTarget(target)\n

    Get the target hostname and IP port number

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description dict

    the hostname and IP port for this target program

    Source code in tm_admin/tmserver.py
    def getTarget(self,\n            target: str,\n            ):\n    \"\"\"\n    Get the target hostname and IP port number\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (dict): the hostname and IP port for this target program\n    \"\"\"\n    return self.hosts.yaml[0][target][0]\n
    "},{"location":"api/#tm_admin.tmserver.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tmserver.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"tmserver\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"Server for gRPC communication\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    # This blocks till  this process is killed\n    tm = TMServer('test')\n
    "},{"location":"api/#tmclientpy","title":"tmclient.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tmclient.TMClient","title":"TMClient","text":"
    TMClient(target)\n

    Bases: object

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description TMClient

    An instance of this class

    Source code in tm_admin/tmclient.py
    def __init__(self,\n            target: str,\n            ):\n    \"\"\"\n    Instantiate a client\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (TMClient): An instance of this class\n    \"\"\"\n    # the services.yaml file defines the hostname and ports for all programs.\n    self.hosts = YamlFile(f\"{rootdir}/services.yaml\")\n    target = self.getTarget(target)\n    [[host, port]] = target.items()\n    # FIXME: this needs to use SSL for a secure connection\n    self.channel = grpc.insecure_channel(f\"{host}:{port}\")\n    # self.stub = tm_admin.services_pb2_grpc.TMClientStub(channel)\n    # self.stub = tm_admin.services_pb2_grpc.testStub(self.channel)\n    self.stub = tm_admin.services_pb2_grpc.TMAdminStub(self.channel)\n
    "},{"location":"api/#tm_admin.tmclient.TMClient.sendUserProfile","title":"sendUserProfile","text":"
    sendUserProfile(msg)\n

    Send data to the target program

    Parameters:

    Name Type Description Default msg str

    The message to send

    required

    Returns:

    Type Description dict

    The response from the server

    Source code in tm_admin/tmclient.py
    def sendUserProfile(self,\n            msg: str,\n            ):\n    \"\"\"\n    Send data to the target program\n\n    Args:\n        msg (str): The message to send\n\n    Returns:\n       (dict): The response from the server\n    \"\"\"\n    foo = UsersMessage(id=1, username=msg, name=msg)\n\n    bar = serialize_to_protobuf(foo.data, tm_admin.users.users_pb2.users)\n\n    response = self.stub.GetUser(bar)\n    #print(f\"TMAdmin client received: {response}\")\n    return response\n
    "},{"location":"api/#tm_admin.tmclient.TMClient.getTarget","title":"getTarget","text":"
    getTarget(target)\n

    Get the target hostname and IP port number

    Parameters:

    Name Type Description Default target str

    The name of the target program

    required

    Returns:

    Type Description dict

    the hostname and IP port for this target program

    Source code in tm_admin/tmclient.py
    def getTarget(self,\n            target: str,\n            ):\n    \"\"\"\n    Get the target hostname and IP port number\n\n    Args:\n        target (str): The name of the target program\n\n    Returns:\n        (dict): the hostname and IP port for this target program\n    \"\"\"\n    return self.hosts.yaml[0][target][0]\n
    "},{"location":"api/#tm_admin.tmclient.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tmclient.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=\"tmclient\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"gRPC Client\",\n        epilog=\"\"\"\n        This should only be run standalone for debugging purposes.\n        \"\"\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-m\", \"--msg\", default='who', help=\"string to send\")\n    args, known = parser.parse_known_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    tm = TMClient('test')\n\n    cmd = {'cmd': Command.GET_USER, 'id': 2}\n    response = tm.sendRequest(cmd)\n    print(f\"TMAdmin user received: {response}\")\n\n    cmd = {'cmd': Command.GET_TEAM, 'id': 20}\n    response = tm.sendRequest(cmd)\n    print(f\"TMAdmin team received: {response}\")\n\n    cmd = {'cmd': Command.GET_ORG, 'id': 10}\n    response = tm.sendRequest(cmd)\n    print(f\"TMAdmin organization received: {response}\")\n
    "},{"location":"api/#userspy","title":"users.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.users.users.UsersDB","title":"UsersDB","text":"
    UsersDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection

    'localhost/tm_admin'

    Returns:

    Type Description UsersDB

    An instance of this class

    Source code in tm_admin/users/users.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the users table.\n\n    Args:\n        dburi (str): The URI string for the database connection\n\n    Returns:\n        (UsersDB): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.profile = UsersTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('users', dburi)\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.updateRole","title":"updateRole","text":"
    updateRole(id, role)\n

    Update the role for a user.

    Parameters:

    Name Type Description Default id int

    The users ID

    required role Userrole

    The new role.

    required Source code in tm_admin/users/users.py
    def updateRole(self,\n               id: int,\n               role: Userrole,\n               ):\n    \"\"\"\n    Update the role for a user.\n\n    Args:\n        id (int): The users ID\n        role (Userrole): The new role.\n    \"\"\"\n    role = Userrole(role)\n    return self.updateColumn(id, {'role': role.name})\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.updateMappingLevel","title":"updateMappingLevel","text":"
    updateMappingLevel(id, level)\n

    Update the mapping level for a user.

    Parameters:

    Name Type Description Default id int

    The users ID.

    required level Mappinglevel

    The new level.

    required Source code in tm_admin/users/users.py
    def updateMappingLevel(self,\n               id: int,\n               level: Mappinglevel,\n               ):\n    \"\"\"\n    Update the mapping level for a user.\n\n    Args:\n        id (int): The users ID.\n        level (Mappinglevel): The new level.\n    \"\"\"\n    mlevel = Mappinglevel(level)\n    return self.updateColumn(id, {'mapping_level': mlevel.name})\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.updateExpert","title":"updateExpert","text":"
    updateExpert(id, mode)\n

    Toggle the expert mode for a user.

    Parameters:

    Name Type Description Default id int

    The users ID.

    required mode bool

    The new mode..

    required Source code in tm_admin/users/users.py
    def updateExpert(self,\n               id: int,\n               mode: bool,\n               ):\n    \"\"\"\n    Toggle the expert mode for a user.\n\n    Args:\n        id (int): The users ID.\n        mode (bool): The new mode..\n    \"\"\"\n    return self.updateColumn(id, {'expert_mode': mode})\n
    "},{"location":"api/#tm_admin.users.users.UsersDB.getRegistered","title":"getRegistered","text":"
    getRegistered(start, end)\n

    Get all users registered in this timeframe.

    Parameters:

    Name Type Description Default start datetime

    The starting timestamp

    required end datetime

    The starting timestamp

    required

    Returns:

    Type Description list

    The users registered in this timeframe.

    Source code in tm_admin/users/users.py
    def getRegistered(self,\n                  start: datetime,\n                  end: datetime,\n                  ):\n    \"\"\"\n    Get all users registered in this timeframe.\n\n    Args:\n        start (datetime): The starting timestamp\n        end (datetime): The starting timestamp\n\n    Returns:\n        (list): The users registered in this timeframe.\n    \"\"\"\n\n    where = f\" date_registered > '{start}' and date_registered < '{end}'\"\n    return self.getByWhere(where)\n
    "},{"location":"api/#tm_admin.users.users.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/users/users.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin', help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    user = UsersDB(args.uri)\n    # user.resetSequence()\n    all = user.getAll()\n    # Don't pass id, let postgres auto increment\n    ut = UsersTable(name='test', mapping_level='BEGINNER',\n                    email_address='foo@bar.com')\n    user.createTable(ut)\n    # print(all)\n\n    all = user.getByID(1)\n    print(all)\n\n    all = user.getByName('test')\n    print(all)\n\n    ut = UsersTable(name='foobar', email_address=\"bar@foo.com\", mapping_level='INTERMEDIATE')\n
    "},{"location":"api/#projectspy","title":"projects.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.projects.projects.ProjectsDB","title":"ProjectsDB","text":"
    ProjectsDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection

    'localhost/tm_admin'

    Returns:

    Type Description ProjectsDB

    An instance of this class

    Source code in tm_admin/projects/projects.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the projects table.\n\n    Args:\n        dburi (str): The URI string for the database connection\n\n    Returns:\n        (ProjectsDB): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.profile = ProjectsTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('projects', dburi)\n
    "},{"location":"api/#tm_admin.projects.projects.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/projects/projects.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    parser.add_argument(\"-b\", \"--boundary\", required=True,\n                        help=\"The project AOI\")\n\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    gen = Generator()\n    x = gen.readConfig(\"projects/projects.yaml\")\n    for entry in gen.yaml.yaml:\n        print(entry)\n    quit()\n\n    proj = ProjectsDB(args.uri)\n    # user.resetSequence()\n    all = proj.getAll()\n\n    file = open(args.boundary, 'r')\n    boundary = geojson.load(file)\n    geom = shape(boundary[0]['geometry'])\n    center = centroid(geom)\n    # Don't pass id, let postgres auto increment\n    ut = ProjectsTable(author_id=1, outline=geom, centroid=center,\n                       created='2021-12-15 09:58:02.672236',\n                       task_creation_mode='GRID', status='DRAFT',\n                       mapper_level='BEGINNER')\n    proj.createTable(ut)\n
    "},{"location":"api/#organizationspy","title":"organizations.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.organizations.organizations.OrganizationsDB","title":"OrganizationsDB","text":"
    OrganizationsDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection

    'localhost/tm_admin'

    Returns:

    Type Description OrganizationsDB

    An instance of this class

    Source code in tm_admin/organizations/organizations.py
    def __init__(self,\n             dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the organizations table.\n\n    Args:\n        dburi (str): The URI string for the database connection\n\n    Returns:\n        (OrganizationsDB): An instance of this class\n    \"\"\"\n    self.pg = None\n    self.profile = OrganizationsTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('organizations', dburi)\n
    "},{"location":"api/#tm_admin.organizations.organizations.OrganizationsDB.getByName","title":"getByName","text":"
    getByName(name)\n

    Return the data for the name in the table. This overrides the version in the base class.

    Parameters:

    Name Type Description Default name str

    The name of the dataset to retrieve.

    required

    Returns:

    Type Description list

    The results of the query

    Source code in tm_admin/organizations/organizations.py
    def getByName(self,\n            name: str,\n            ):\n    \"\"\"\n    Return the data for the name in the table. This overrides the version\n    in the base class.\n\n    Args:\n        name (str): The name of the dataset to retrieve.\n\n    Returns:\n        (list): The results of the query\n    \"\"\"\n    sql = f\"SELECT * FROM {self.table} WHERE name='{name}' LIMIT 1\"\n    self.pg.dbcursor.execute(sql)\n    data = dict()\n    entry = self.pg.dbcursor.fetchone()\n    for column in self.profile.data.keys():\n        index = 0\n        for column in self.profile.data.keys():\n            data[column] = entry[index]\n            index += 1\n\n    return [data]\n
    "},{"location":"api/#tm_admin.organizations.organizations.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/organizations/organizations.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    organization = OrganizationsDB(args.uri)\n    # organization.resetSequence()\n    all = organization.getAll()\n    # Don't pass id, let postgres auto increment\n    ut = OrganizationsTable(name='fixme', slug='slug', orgtype='FREE')\n    organization.createTable(ut)\n    # print(all)\n\n    all = organization.getByID(1)\n    print(all)\n\n    all = organization.getByName('fixme')\n    print(all)\n
    "},{"location":"api/#taskspy","title":"tasks.py","text":"

    options: show_source: false heading_level: 3

    "},{"location":"api/#tm_admin.tasks.tasks.TasksDB","title":"TasksDB","text":"
    TasksDB(dburi='localhost/tm_admin')\n

    Bases: DBSupport

    Parameters:

    Name Type Description Default dburi str

    The URI string for the database connection.

    'localhost/tm_admin'

    Returns:

    Type Description TasksDB

    An instance of this class.

    Source code in tm_admin/tasks/tasks.py
    def __init__(self,\n            dburi: str = \"localhost/tm_admin\",\n            ):\n    \"\"\"\n    A class to access the tasks table.\n\n    Args:\n        dburi (str): The URI string for the database connection.\n\n    Returns:\n        (TasksDB): An instance of this class.\n    \"\"\"\n    self.profile = TasksTable()\n    self.types = dir(tm_admin.types_tm)\n    super().__init__('tasks', dburi)\n
    "},{"location":"api/#tm_admin.tasks.tasks.main","title":"main","text":"
    main()\n

    This main function lets this class be run standalone by a bash script.

    Source code in tm_admin/tasks/tasks.py
    def main():\n    \"\"\"This main function lets this class be run standalone by a bash script.\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-v\", \"--verbose\", nargs=\"?\", const=\"0\", help=\"verbose output\")\n    parser.add_argument(\"-u\", \"--uri\", default='localhost/tm_admin',\n                            help=\"Database URI\")\n    # parser.add_argument(\"-r\", \"--reset\", help=\"Reset Sequences\")\n    args = parser.parse_args()\n\n    # if len(argv) <= 1:\n    #     parser.print_help()\n    #     quit()\n\n    # if verbose, dump to the terminal.\n    log_level = os.getenv(\"LOG_LEVEL\", default=\"INFO\")\n    if args.verbose is not None:\n        log_level = logging.DEBUG\n\n    logging.basicConfig(\n        level=log_level,\n        format=(\"%(asctime)s.%(msecs)03d [%(levelname)s] \" \"%(name)s | %(funcName)s:%(lineno)d | %(message)s\"),\n        datefmt=\"%y-%m-%d %H:%M:%S\",\n        stream=sys.stdout,\n    )\n\n    task = TasksDB(args.uri)\n    # user.resetSequence()\n    all = task.getAll()\n    # Don't pass id, let postgres auto increment\n    ut = TasksTable(project_id=1)\n    task.createTable(ut)\n    # print(all)\n\n    all = task.getByID(1)\n    print(all)\n\n    all = task.getByName('test')\n    print(all)\n
    "},{"location":"build/","title":"Building TM-Admin","text":"

    This is a complicated project as it involves parsing and outputting multiple file formats. This project uses gRPC for the low-level communication layer, which is below the REST API. This way it can be used by multiple other project REST APIs for exchanging data without massive refactoring of an existing API.

    The database schema is based on the ones in use in the FMTM project, which were originally based on the ones used by the HOT Tasking Manager. The schemas have years of improvements on the data requirements of Tasking Manager style projects. Not every column in a database table will be needed by each project, they can be ignored. It should be entirely possible to use a custom configuration file, but this is currently unsupported. (would love a patch for this)

    This project generates multiple files at runtime, so each is organized into a sub-directory, one for each table. The program that processes each configuration file is generator.py, which is part of this project. This reads in a configuration file in YAML format, and generates the output files for this configuration file. There is also a class Generator that can be used by other projects.

    These are the current modules supported by this project.

    • users
    • projects
    • tasks
    • organizations
    • teams
    "},{"location":"build/#tmadmin-manage","title":"tmadmin-manage","text":"

    The tmadmin-manage program is for higher-level data management. While each class can be run standalone, that's more for testing & development. This program is also both a standalone program, and a class that can be used by other projects. This program will create the database and tables for each module.

    "},{"location":"build/#datatypes","title":"Datatypes","text":"

    Each database table has it's own configuration file. There is also a top level one, types.yaml that generates the type definitions that all the other files depend on. This becomes types_tm.sql, types_tm.proto, and types_tm.py, and needs to be imported before the other files.

    "},{"location":"build/#yaml-files","title":".yaml files","text":"

    The YAML based config files are where everything gets defined. This way a single configuration file can be used to generate multiple output formats. In the case of this projects, that's SQL files for a local postgres database, protobuf files for gRPC, and python source files for data type definitions. There is more information on the configuration files here

    "},{"location":"build/#proto-files","title":".proto files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. Not every column in the database tables is in a message. The fields that get send and received are defined in the configuration file by adding share: True as a setting.

    The .proto files then have to be compiled using protoc, which generates the client and server stubs.

    "},{"location":"build/#sql-files","title":".sql files","text":"

    These define the messages used by gRPC, and are also generated from the configuration files. These can be executed in postgres to create the tables. The tmadmin-manage program uses these to create the database tables.

    "},{"location":"communication/","title":"Inter Project Communication","text":"

    While there are data structures for all the columns in the database, not all of the data fields need to be used for inter project communication. Some field data is project specific, for example, tasks in the HOT Tasking Manager(TM) are not the same as tasks in the nHOT Field Mapping Tasking Manager(FMTM), but most of the fields are used for tasks in both.

    With any project that is designed to be embedded into other projects, there is a risk of duplicate data structures that can become a maintainance nightmare in the future, since any changes will need to be in multiple places. Each data structure is represented in the database schemas, python, and gRPC. To reduce future maintainance headaches, a single configuration file is used to generate multiple output formats. More information on that process is documented here.

    All communication is bi-directional. Projects can send data, or handle a request for data. For any data that is sent, the response is a simple SUCCESS/FAILURE message. FAILURE message also return an error message and error code.

    It seems that most of the projects start with TM. After critical tasks are mapped, they then could be migrated to FMTM for field data collection. The FMTM mappers would also be ground truthing the remote mapping. It's entirely possible that FMTM field mappers would find issues with the data extract of OSM buildings, and want to notify the TM project manager to invalidate some tasks and remap them.

    "},{"location":"communication/#notifications","title":"Notifications","text":"

    Some messages have nothing to do with the database, they're for communicating other types of requests. Other than just doing database updates, this is the core of an end to end data flow.

    Examples of some notifications are:

    • Underpass would notify TM or fAIr of a data quality issue
    • An FMTM project manager would notify TM to invalidate a task
    • fAIr would notify an FMTM project manager that the imagery has been processed so a data extract could be made
    • fAIr would notify OAM that drone imagery is needed for an AOI
    • OAM would notify fAIr when drone imagery is ready to be processed
    "},{"location":"communication/#projects-exchange-user-profiles","title":"Projects exchange user profiles","text":"

    Since a user may be contributing to multiple projects, it should be possible to clone a users profile between projects. For example, when a Tasking Manager (TM) is being worked on, some users may also be using the Field Mapping Tasking Manager (FMTM) to ground-truth the data. Or they may want to use fAIr to process the drone imagery they just collected.

    "},{"location":"communication/#user-profiles","title":"User profiles","text":"

    These are the data fields that need to be in this message to create a user profile in the database. The user ID in TM or FMTM won't be the same, since each project will have different teams of mappers. Instead of the ID, the username will be used to refer to a mapper.

    • username
    • name
    • city
    • country
    • email_address
    • is_email_verified
    • is_expert
    • mapping_level
    • password
    "},{"location":"communication/#receiving-project-decides-update-or-create","title":"Receiving project decides, update or create ?","text":"

    When this message is received, it should update the database for this user unless the username already exists, and send the response acknowledgment.

    "},{"location":"communication/#tm-sends-project-profile","title":"TM sends project profile","text":"

    It is entirely likely that for disaster response, an area may be remotely mapped with TM, and then will be field mapped with FMTM as a follow-up. The instructions would be very different, so aren't needed. The tasks won't be sent either, as a TM task is much largerr than an FMTM task. FMTM mappers are walking when mapping. The project ID is also not transmitted, as it'll be different in different projects. There may also be occassions where a project would be sent to fAIr, Export Tool, or Underpass.

    • name
    • outline
    • description
    • location_str
    • organisation_id (spelling depends on country)
    • priority
    • centroid

    A project transferred to FMTM has no project manager, so these are initially only an AOI and draft project description. FMTM would need the ability to search for an unassigned project, ie... no manager. Then when there is a project manager it would be assigned to them.

    "},{"location":"communication/#receiving-project-decides-update-or-create_1","title":"Receiving project decides, update or create ?","text":"

    When this message is received, it should update the database for this project, and send the response acknowledgment.

    "},{"location":"communication/#tm-sends-organization-profile","title":"TM sends organization profile","text":"

    Organizations may be using multiple HOT projects, so this would sync organization data between projects so it wouldn't have to be manually edited for each poroject like it is now.

    • name
    • description
    • url
    • logo
    • type
    "},{"location":"communication/#receiving-project-decides-update-or-create_2","title":"Receiving project decides, update or create ?","text":"

    When this message is received, it should update the database for this organization, and send the response acknowledgment.

    "},{"location":"configuring/","title":"Configuring The Data Structures","text":"

    For any project that needs to transmit data between multiple projects, there needs to be a single source of data structures and type definitions. Otherwise there winds up being a lot of code duplication which becomes hard to maintain.

    This project also needs to manage the database tables, as well as allow to transmit data between projects. Python enums and classes are also generated.

    "},{"location":"configuring/#the-yaml-files","title":"The YAML files","text":"

    This file is used to generate the full SQL to create database tables, as well as the protobuf files. The first field becomes the name of the tables in postgres, or the message in the .proto file. Each table is then followed by a list of fields. Each field has a few settings, the data type, and a few settings.

    For example:

    - users:\n    - id:\n        - int64\n        - required: True\n        - share: True\n        - sequence: True\n ...\n
    "},{"location":"configuring/#required","title":"required","text":"

    If this is True, then for the database table, this becomes NOT NULL in the SQL schema. This is ignored when generating the protobuf file.

    "},{"location":"configuring/#sequence","title":"sequence","text":"

    If this is True, then this becomes an auto incrementing sequence in SQL. This is ignored when generating the protobuf file.

    "},{"location":"configuring/#share","title":"share","text":"

    Not every field needs to be transfered to other projects, as some are project specific, like how many tasks have been mapped. If this is True, then it will have an entry in the protobuf message. The default is True. To have a field not appear in the protobuf message, this needs to be set to False.

    "},{"location":"configuring/#array","title":"array","text":"

    If this is True, then in the database schema this becomes an array. In the protobuf file, this adds the repeated keyword in the message to define this field as an array.

    "},{"location":"configuring/#unique","title":"unique","text":"

    if this is True, in postgres a unique constraint is generated for this, which is used for upserts.

    "},{"location":"dataexchange/","title":"Exchanging Data","text":"

    Exchanging data between projects has a few issues, namely the ID of the user, the project, and the organization are different in the different projects. Not all fields are useful cross-project, so some but not all of the columns in a database table are exchanged w ith other projects. There are other issues to handle, a projet manager/admin in Tasking Manager (TM) may only be a a mapper in the Field Mapping Tasking Manager (FMTM) project, so the roles change, but the rest of the user profile stays the same.

    Currently all the database tables have every column used by FMTM or TM. Since there are many application specific columns, these are simply ignored by the application. While this does make the database slightly larger having multiple empty columns, it's a tradeoff between database size and simplifying the code base. A future enhancement to the YAML config file subsystem will support using a subset of all the database columns.

    Some of the data to be exchanged is currently supported by the REST API for FMTM and TM. The plan is for these modules in the TM-Admin project work under those REST APIs for database access. This lets the REST API stay focused on supporting the web frontend for each application.

    "},{"location":"dataexchange/#identifying-records","title":"Identifying Records","text":"

    Since the ID can't be used between projects, the name or address is the only unique field that can be used to identify a user or an organization, etc... For users, the best ID is their OpenStreetMap (ODM) ID, as that is unique globally. While some support can be added to track unique IDs across multiple projects, this can be cumbersome.

    Another way to identify a record is through location. Since both projects and tasks have an polygon area of interest, a point within a project in one application, can be used to query a remote project to find the project or task. For example, if a field mapper finds bad data, the location of that data can be used to find the TM project and task, so the task can be invalidated.

    "},{"location":"dataexchange/#filtering-data","title":"Filtering Data","text":"

    Since not all data fields are needed in each project, the YAML configuration file supports a flag for each item in a data structure as to whether it should be shared or not. For example, a database query might return many columns, but only a few are usefully portable across multiple projects.

    For instance, Tasking Manager has task boundaries, in FMTM, tasks are smaller, because it involves mappers walking. So transferrihng exact task boundaries would be meaningless. In this usage case, the tasks transfer from TM to FMTM would be a multi-polygon. FMTM would create a project AOI based on the outer boundary of all the of the tasks, and then recalulate FMTM specific tasks boundaries.

    "},{"location":"dataexchange/#data-exchange-schemas","title":"Data Exchange Schemas","text":"

    Some fields need to be in any data packet that is intended for database queries, since the there needs to be a way to refer to an existing record, if it exists. While it is possible to identify remote database records by comparing multiple columns, to keep things simple, it is prefered to use the name or location.

    "},{"location":"dataexchange/#project-data","title":"Project Data","text":"

    A project has a wide definition depending on the type of application. Since this module is focused on Tasking Manager style applications, all version will have at least a project name and an Area of Interest (AOI). In addition, each tracks task usage, so the number of tasks mapped, validated, or invalidated exists in all tables, but has different data.

    "},{"location":"dataexchange/#field-mapping-tasking-manager","title":"Field Mapping Tasking Manager","text":"

    For FMTM, it uses an odkid column, which is used to communicate with ODK Central. This is an example of needing to store the ID of a remote application to exchange data for specific items. How the ID of a remote project is stored may change in the future to handle multiple remote applications, but for now, it's only the one for ODK Central.

    FMTM also uses several columns for working with OpenDataKit(ODK). These are the login credentials for an ODK Central server, and an XLSForm for the project.

    "},{"location":"dataexchange/#tasking-manager","title":"Tasking Manager","text":"

    TM uses a series of columns that are used for editing OSM data. This includes presets for several editors.

    "},{"location":"dataexchange/#user-data","title":"User Data","text":"

    Most all the columns in the user profiles is the same across all applications. The are a few columns for tracking tasks mapped, etc... but the data for those will vary between applications.

    "},{"location":"dataexchange/#organization-data","title":"Organization Data","text":"

    Organization data is easy, all columns are used by all applications. This this table is simple, organization name, logo, URL, and a description.

    "},{"location":"dataexchange/#task-data","title":"Task Data","text":"

    A task AOI is not usually useful between projects, as a TM task is much larger than an FMTM task. For a Drone Tasking Manager (DTM), the task size will also be different. Since tasks are not portable across projects, each project maintains it's own data, the creation date, tasks mapped, validated, invalidated, etc...

    "},{"location":"dataflow/","title":"TM-Admin Data Flow","text":""},{"location":"dataflow/#generated-files","title":"Generated files","text":"

    This project attempts to minimise code duplication. It is designed to be a module for use in other projects. Because this project works with both gRPC messages and a postgres database, any changes to any of the data structures would require making changes in multiple places. Instead a single file in YAML format is used to generate all the other formats. This way changes only have to be made in one place.

    It does make the code more complicated, lots of layers of generated code stubs to dig through when debugging. I've also tried to avoid hacks in the code, and make it flexible to changes. That often involves lots of looping through various data, but it's still pretty fast.

    "},{"location":"dataflow/#generating-the-files","title":"Generating the files","text":"

    To generate the files, there is a standalone python class, which also has a simple command line interface and can be run offline. The generate.py file reads in the YAML config files, and creates an internal data structure for that file. More information on the config file is here.

    The actual database schemas are created from the generated SQL files. The tmadmin_manage.py file has a class that also runs standalone and generates all the SQL, python, and protobuf files using the Generate class. Once it generates the SQL files, it creates the database and tables.

    The protobuf files need to be compiled using protoc. This is easiest done using the Makefile. since it has to include the types for the complication to succeed.

    Since there are a lot of generated files, they are all in a subdirectory. Each directory is for each table in the database, and all generated files go there.

    "},{"location":"dataflow/#datatypes","title":"Datatypes","text":"

    There are multiple shared enums, and are defined in the types.yaml file. These become enums for postgres, python, and protobuf. After generating the files, there is types_tm.sql, types_tm.py, and a types_tm.proto for the protobuf files gRPC uses. These can be included in any of the other classes that create data types. Having portable data strucures that can be shared is critical. Otherwise any changes would require editing multiple places. Having a single definition reduces maintaince.

    "},{"location":"dataflow/#the-python-files","title":"The Python files","text":"

    There are python source files generated for each database table. These define all the data structures so they are easily accessible. The enums are in the types_tm.py file.

    The other two files are classes that define the full data for SQL queries, as well as the reduced dataset used in inter-project data exchange using gRPC. Using the table name, these become tableTable or tableMessage. The class files are for storing the data for a table. The tableMessage classes are the reduced datasets for exchanging data. Not all data in a database is useful in multiple projects, so this uses a setting in the YAML config file to not have all columns in the gRPC message.

    Each table also has a class designed for accessing the database. This file is not generated. This uses the other generated python files for the data structures. This handles creating the entries for the tables, and also has a few common queries, like search by ID. Most of the higher level processing will be handled by the project importing this module since it's possible to get the full data for furthur processing. This is to make it a less painful refactoring of an existing project backend. Many projects have existing tests of the values in the database columns, so this is still possible.

    "},{"location":"dataflow/#instantiating-an-object","title":"Instantiating an object","text":"

    The generated python files allow for default values for all the database tables, and conditional parameters in python. With each top level class for a tables,

    For example: ut = UsersTable(name='fixme', mapping_level='BEGINNER')

    Creates a dictionary in the class with all of the keywords from the YAML file. but will set these two columns to these values. This is used for both creating entries in the database, but also for updating them. This handles multiple optional parameters allowing this data object to be used for data exchange in a consistent fashion.

    "},{"location":"dataflow/#sql-files","title":"SQL files","text":"

    The SQL files are designed to work with postgres for creating the database, and it's tables and data types. The config file format allows for setting each column as an auto incrementing column (good for IDs), setting that are required, so become 'NOT NULL'. And also a unique column, which is used for an INSERT that may trigger a conflict. This is useful to update existing data.

    "},{"location":"dataflow/#protobuf-files","title":"Protobuf files","text":"

    The protobuf files are used by gRPC to exchange data. The protoc compiler produces other wrappers as python code for the data structures. These also use the table name as the prefix, and creates table_pb2.py or table_pb2_grpc.py. These are used with gRPC. The other generated python class are designed to interface with these, since they need data structures to exchange.

    "},{"location":"endpoints/","title":"REST API Endpoints","text":"

    This is a comparison between the endpoint of Tasking Manager and the Field Mapping Tasking Manager. The goal of the TM Admin project is to support these endpoints. There is also not an obvious 1-1 relationship between endpoints the support class in TM Adamin. Endpoints are higher level than the code in TM Admin.

    For the common functions like querying the database by ID or name, these are in a base class, so shared.

    "},{"location":"endpoints/#users","title":"Users","text":"

    Endpoints for managing User profiles.

    Tasking Manager FMTM TM Admin Get paged list of all usernames Get Users UsersDB.getAll() Registers users without OpenStreetMap account UsersDB.createTable() Updates user info UsersDB.updateTable() Get user information by OpenStreetMap username UsersDB.getByName() Get stats about users registered within a period of time UsersDB.getByWhere() Get user information by id Get User by ID UsersDB.getByID() Allows user to enable or disable expert mode UsersDB.updateExpert() Allows PMs to set a user's mapping level UsersDB.updateMappingLevel() Allows PMs to set a user's role UsersDB.updateRole() Get a list of tasks a user has interacted with UsersDB.getByWhere() Resends the verification email token to the logged in user Get recommended projects for a user Get details from OpenStreetMap for a specified username Get detailed stats about a user by OpenStreetMap username Get paged lists of users matching OpenStreetMap username filter Get User Roles"},{"location":"endpoints/#organizations","title":"Organizations","text":"

    Endpoints for managing Organization profiles.

    Tasking Manager FMTM TM Admin List all organisations Get Organization OrganizationsDB.getAll() Creates a new organisation Create Organization OrganizationsDB.createTable() Deletes an organisation Delete Organizations OrganizationsDB.deleteByID Retrieves an organisation Get Organization Detail OrganizationsDB.getByID() Updates an organisation Update Organization OrganizationsDB.updateTable() Return statistics about projects and active tasks of an organisation"},{"location":"endpoints/#projects","title":"Projects","text":"

    Endpoints for managing projects.

    Tasking Manager FMTM TM Admin List and search for projects Read Projects projectsDB.getAll() Creates a tasking-manager project Create Project projectsDB.createTable() List and search projects by bounding box projectsDB.getByLocation() Get featured projects projectsDB.updateTable() Get all projects for logged in admin projectsDB.getByWhere() Get popular projects projectsDB.getByWhere() Get similar projects projectsDB.getByWhere() Gets projects user has mapped projectsDB.getByWhere() Deletes a Tasking-Manager project Delete Project projectsDB.deleteByID() Get a specified project including it's area Get Project Details projectsDB.getByID() Updates a Tasking-Manager project Update Project projectsDB.updataTable() Set a project as featured projectsDB.updateColumn() Send message to all contributors of a project Unset a project as featured projectsDB.updateColumn() Transfers a project to a new user projectsDB.updateColumn() Get all user activity on a project projectsDB.getByWhere() Get latest user activity on all of project task projectsDB.getByWhere() Get all user contributions on a project projectsDB.getByWhere() Get contributions by day for a project projectsDB.getByWhere() Get AOI of Project projectsDB.getByID() Upload Custom XLSForm Project Partial Update Upload Multi Project Boundary Task Split Upload Project Boundary Edit Project Boundary Update Odk Credentials Validate Form Generate Files Get Data Extracts Update Project Form Get Project Features Generate Log Get Categories Preview Tasks Add Features Download Form Update Project Category Download Template Download Project Boundary Download Task Boundaries Download Features Generate Project Tiles Tiles List Download Tiles Download Task Boundary Osm Project Centroid"},{"location":"endpoints/#tasks","title":"Tasks","text":"

    Endpoints for managing tasks in a project.

    Tasking Manager FMTM TM Admin Delete a list of tasks from a project Get all tasks for a project as JSON Read Tasks tasksDB.getAll() Extends duration of locked tasks tasksDB.getByWhere() Invalidate all validated tasks on a project Locks a task for mapping tasksDB.updateColumn() Lock tasks for validation tasksDB.updateColumn() Map all tasks on a project Set all bad imagery tasks as ready for mapping tasksDB.updateTable() Reset all tasks on project back to ready, preserving history Revert tasks by a specific user in a project Split a task Unlock a task that is locked for mapping resetting it to its last status tasksDB.updateTable() Unlock tasks that are locked for validation resetting them to their last status tasksDB.updateTable() Undo a task's mapping status Update Task Status tasksDB.updateTable() Set a task as mapped Update Task Status tasksDB.updateTable() Set tasks as validated Update Task Status tasksDB.updateTable() Validate all mapped tasks on a project Update Task Status tasksDB.updateTable() Get task tiles intersecting with the aoi provided tasksDB.getByLocation() Get all tasks for a project as GPX tasks.getAll() Get all mapped tasks for a project grouped by username Get all tasks for a project as OSM XML Get a task's metadata Get Task Get invalidated tasks either mapped by user or invalidated by user Get Task Stats Get Qr Code List Edit Task Boundary Task Features Count"},{"location":"protos-api/","title":"Protocol Documentation","text":""},{"location":"protos-api/#table-of-contents","title":"Table of Contents","text":"
    • services.proto

      • notification
      • tmrequest
      • tmresponse
      • tmresponse.DataEntry

      • TMAdmin

    • types_tm.proto

      • Bannertype
      • Command
      • Editors
      • Encouragingemailtype
      • Mappinglevel
      • Mappingnotallowed
      • Mappingtypes
      • Notification
      • Organizationtype
      • Permissions
      • Projectdifficulty
      • Projectpriority
      • Projectstatus
      • Taskaction
      • Taskcreationmode
      • Taskstatus
      • Teamjoinmethod
      • Teammemberfunctions
      • Teamroles
      • Teamvisibility
      • Usergender
      • Userrole
      • Validatingnotallowed
    • organizations/organizations.proto

      • organizations
    • projects/projects.proto

      • projects
    • tasks/tasks.proto

      • tasks
    • teams/teams.proto

      • teams
    • users/users.proto

      • users
    • Scalar Value Types

    Top

    "},{"location":"protos-api/#servicesproto","title":"services.proto","text":""},{"location":"protos-api/#notification","title":"notification","text":"Field Type Label Description note Notification"},{"location":"protos-api/#tmrequest","title":"tmrequest","text":"Field Type Label Description cmd Command id int64 name string"},{"location":"protos-api/#tmresponse","title":"tmresponse","text":"Field Type Label Description error_code int32 error_msg string data tmresponse.DataEntry repeated message Data { map<string, string> pairs = 3; } repeated Data data = 4;"},{"location":"protos-api/#tmresponsedataentry","title":"tmresponse.DataEntry","text":"Field Type Label Description key string value string"},{"location":"protos-api/#tmadmin","title":"TMAdmin","text":"

    The greeting service definition.

    Method Name Request Type Response Type Description doRequest tmrequest tmresponse These are for handling tmrequest for profile data from the database doNotification notification tmresponse updateUserProfile users users updateProjectProfile projects projects updateTeamProfile teams teams updateTask tasks tasks updateOrganizationProfile organizations organizations

    Top

    "},{"location":"protos-api/#types_tmproto","title":"types_tm.proto","text":""},{"location":"protos-api/#bannertype","title":"Bannertype","text":"Name Number Description INFO 0 WARNING 1"},{"location":"protos-api/#command","title":"Command","text":"Name Number Description GET_USER 0 GET_ORG 1 GET_PROJECT 2 GET_TEAM 3"},{"location":"protos-api/#editors","title":"Editors","text":"Name Number Description ID 0 JOSM 1 POTLATCH_2 2 FIELD_PAPERS 3 CUSTOM 4 RAPID 5"},{"location":"protos-api/#encouragingemailtype","title":"Encouragingemailtype","text":"Name Number Description PROJECT_PROGRESS 0 PROJECT_COMPLETE 1 BEEN_SOME_TIME 2"},{"location":"protos-api/#mappinglevel","title":"Mappinglevel","text":"Name Number Description BEGINNER 0 INTERMEDIATE 1 ADVANCED 2"},{"location":"protos-api/#mappingnotallowed","title":"Mappingnotallowed","text":"Name Number Description USER_ALREADY_HAS_TASK_LOCKED 0 USER_NOT_CORRECT_MAPPING_LEVEL 1 USER_NOT_ACCEPTED_LICENSE 2 USER_NOT_ALLOWED 3 PROJECT_NOT_PUBLISHED 4 USER_NOT_TEAM_MEMBER 5 PROJECT_HAS_NO_OSM_TEAM 6 NOT_A_MAPPING_TEAM 7"},{"location":"protos-api/#mappingtypes","title":"Mappingtypes","text":"Name Number Description ROADS 0 BUILDINGS 1 WATERWAYS 2 LAND_USE 3 OTHER 4"},{"location":"protos-api/#notification_1","title":"Notification","text":"Name Number Description BAD_DATA 0 BLOCKED_USER 1 PROJECT_FINISHED 2"},{"location":"protos-api/#organizationtype","title":"Organizationtype","text":"Name Number Description FREE 0 DISCOUNTED 1 FULL_FEE 2"},{"location":"protos-api/#permissions","title":"Permissions","text":"Name Number Description ANY_PERMISSIONS 0 LEVEL 1 TEAMS 2 TEAMS_LEVEL 3"},{"location":"protos-api/#projectdifficulty","title":"Projectdifficulty","text":"Name Number Description EASY 0 MODERATE 1 CHALLENGING 2"},{"location":"protos-api/#projectpriority","title":"Projectpriority","text":"Name Number Description URGENT 0 HIGH 1 MEDIUM 2 LOW 3"},{"location":"protos-api/#projectstatus","title":"Projectstatus","text":"Name Number Description ARCHIVED 0 PUBLISHED 1 DRAFT 2"},{"location":"protos-api/#taskaction","title":"Taskaction","text":"Name Number Description RELEASED_FOR_MAPPING 0 LOCKED_FOR_MAPPING 1 MARKED_MAPPED 2 LOCKED_FOR_VALIDATION 3 VALIDATED 4 MARKED_INVALID 5 MARKED_BAD 6 SPLIT_NEEDED 7 RECREATED 8 COMMENT 9"},{"location":"protos-api/#taskcreationmode","title":"Taskcreationmode","text":"Name Number Description GRID 0 CREATE_ROADS 1 UPLOAD 2"},{"location":"protos-api/#taskstatus","title":"Taskstatus","text":"Name Number Description READY 0 TASK_LOCKED_FOR_MAPPING 1 TASK_STATUS_MAPPED 2 TASK_LOCKED_FOR_VALIDATION 3 TASK_VALIDATED 4 TASK_INVALIDATED 5 BAD 6 SPLIT 7 TASK_ARCHIVED 8"},{"location":"protos-api/#teamjoinmethod","title":"Teamjoinmethod","text":"Name Number Description ANY_METHOD 0 BY_REQUEST 1 BY_INVITE 2"},{"location":"protos-api/#teammemberfunctions","title":"Teammemberfunctions","text":"Name Number Description MANAGER 0 MEMBER 1"},{"location":"protos-api/#teamroles","title":"Teamroles","text":"Name Number Description TEAM_READ_ONLY 0 TEAM_MAPPER 1 VALIDATOR 2 PROJECT_MANAGER 3"},{"location":"protos-api/#teamvisibility","title":"Teamvisibility","text":"Name Number Description PUBLIC 0 PRIVATE 1"},{"location":"protos-api/#usergender","title":"Usergender","text":"Name Number Description MALE 0 FEMALE 1 SELF_DESCRIBE 2 PREFER_NOT 3"},{"location":"protos-api/#userrole","title":"Userrole","text":"Name Number Description USER_READ_ONLY 0 USER_MAPPER 1 ADMIN 2"},{"location":"protos-api/#validatingnotallowed","title":"Validatingnotallowed","text":"Name Number Description USER_NOT_VALIDATOR 0 USER_LICENSE_NOT_ACCEPTED 1 USER_NOT_ON_ALLOWED_LIST 2 PROJECT_NOT_YET_PUBLISHED 3 USER_IS_BEGINNER 4 NOT_A_VALIDATION_TEAM 5 USER_NOT_IN_TEAM 6 PROJECT_HAS_NO_TEAM 7 USER_ALREADY_LOCKED_TASK 8

    Top

    "},{"location":"protos-api/#organizationsorganizationsproto","title":"organizations/organizations.proto","text":""},{"location":"protos-api/#organizations","title":"organizations","text":"Field Type Label Description id int64 name string slug string logo string description string url string orgtype Organizationtype

    Top

    "},{"location":"protos-api/#projectsprojectsproto","title":"projects/projects.proto","text":""},{"location":"protos-api/#projects","title":"projects","text":"Field Type Label Description id int64 odkid int64 author_id int64 created google.protobuf.Timestamp project_name_prefix string task_type_prefix string location_str string outline bytes status Projectstatus private bool mapper_level Mappinglevel priority Projectpriority centroid bytes hashtags string repeated

    Top

    "},{"location":"protos-api/#taskstasksproto","title":"tasks/tasks.proto","text":""},{"location":"protos-api/#tasks","title":"tasks","text":"Field Type Label Description id int64 project_task_name string outline bytes geometry_geojson string

    Top

    "},{"location":"protos-api/#teamsteamsproto","title":"teams/teams.proto","text":""},{"location":"protos-api/#teams","title":"teams","text":"Field Type Label Description id int64 name string logo string description string invite_only bool visibility Teamvisibility

    Top

    "},{"location":"protos-api/#usersusersproto","title":"users/users.proto","text":""},{"location":"protos-api/#users","title":"users","text":"Field Type Label Description id int64 username string name string city string country string tasks_mapped int32 tasks_invalidated int32 projects_mapped int32 repeated date_registered google.protobuf.Timestamp last_validation_date google.protobuf.Timestamp password string osm_id int64 facebook_id int64 irc_id int64 skype_id int64 slack_id int64 linkedin_id int64 twitter_id int64 picture_url string gender int32"},{"location":"protos-api/#scalar-value-types","title":"Scalar Value Types","text":".proto Type Notes C++ Java Python Go C# PHP Ruby double double double float float64 double float Float float float float float float32 float float Float int32 Uses variable-length encoding. Inefficient for encoding negative numbers \u2013 if your field is likely to have negative values, use sint32 instead. int32 int int int32 int integer Bignum or Fixnum (as required) int64 Uses variable-length encoding. Inefficient for encoding negative numbers \u2013 if your field is likely to have negative values, use sint64 instead. int64 long int/long int64 long integer/string Bignum uint32 Uses variable-length encoding. uint32 int int/long uint32 uint integer Bignum or Fixnum (as required) uint64 Uses variable-length encoding. uint64 long int/long uint64 ulong integer/string Bignum or Fixnum (as required) sint32 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. int32 int int int32 int integer Bignum or Fixnum (as required) sint64 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. int64 long int/long int64 long integer/string Bignum fixed32 Always four bytes. More efficient than uint32 if values are often greater than 2^28. uint32 int int uint32 uint integer Bignum or Fixnum (as required) fixed64 Always eight bytes. More efficient than uint64 if values are often greater than 2^56. uint64 long int/long uint64 ulong integer/string Bignum sfixed32 Always four bytes. int32 int int int32 int integer Bignum or Fixnum (as required) sfixed64 Always eight bytes. int64 long int/long int64 long integer/string Bignum bool bool boolean boolean bool bool boolean TrueClass/FalseClass string A string must always contain UTF-8 encoded or 7-bit ASCII text. string String str/unicode string string string String (UTF-8) bytes May contain any arbitrary sequence of bytes. string ByteString str []byte ByteString string String (ASCII-8BIT)"},{"location":"tmadmin-manage/","title":"TM Admin Manage Util","text":"

    This utility program is the standalone interface to the tm-admin project. It is responsible for creating the database and the tables, and generating the protobuf files for gRPC.

    Initially it is used to generate the SQL files for creating the database and it's tables. These are created from a YAML based config file. That file is described in more detail in this document. This same YAML file is also used to generate all the protobuf files that define each gRPC message, and the python wrappers.

    Once the SQL files have been generated, this program imports them into the database. It can also handle database schema migrations.

    usage: config [-h] -v -d DIFF -u URI YAML files\noptions:\n-h, --help            show this help message and exit\n-v [VERBOSE], --verbose [VERBOSE] verbose output\n-d DIFF, --diff DIFF  SQL file diff for migrations\n-u URI, --uri URI     Database URI\n

    The Database URI defaults to localhost/tm_admin.

    "},{"location":"wiki_redirect/","title":"TM Admin","text":"

    Please see the docs page at: https://hotosm.github.io/tm-admin/

    "}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 1d2072a0..30b1f02a 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,72 +2,72 @@ https://www.hotosm.org/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/CHANGELOG/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/LICENSE/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/about/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/api/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/build/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/communication/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/configuring/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/dataexchange/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/dataflow/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/endpoints/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/protos-api/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/tmadmin-manage/ - 2023-12-18 + 2023-12-20 daily https://www.hotosm.org/wiki_redirect/ - 2023-12-18 + 2023-12-20 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 0bc79618..d18f2917 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ