├── .idea └── .gitignore ├── LICENSE ├── README.md ├── assets ├── EduDocs_Logo.jpg ├── Nextcloud_Logo.jpg └── screenshot_pdfoutput.png ├── config.xml ├── lang ├── ENG.json ├── ESP.json ├── FRA.json └── GER.json ├── modules ├── __init__.py ├── config.py ├── csv_handler.py ├── language_loader.py ├── mapping.py ├── nextcloud_api.py ├── output_handler.py ├── password.py └── user_sync.py ├── nc-user_manager.exe ├── nc-user_manager.py ├── requirements.txt └── users.csv /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | tmp/ 10 | output/ 11 | venv/ 12 | dist/ 13 | build/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # About nc-userimporter 2 | 3 | This tool synchronizes (add, update, delete) Nextcloud users from a CSV file, which you exported from some other software or created with a spreadsheet software. 4 | 5 | ## Instructions 6 | 7 | 1. Download and extract the zip-file 8 | * in the repository: click "code"--> "download zip" 9 | * OR: https://github.com/t-markmann/nc-userimporter/archive/refs/heads/master.zip 10 | 11 | 3. Insert data: 12 | * __config.xml__: Insert your cloud-admin credentials into file _config.xml_. The user must have admin permissions in your Nextcloud. 13 | * __users.csv__: Insert the user data into the file _users.csv_ or recreate it with the same columns in a spreadsheet software. 14 | 15 | 4. Start the tool: 16 | * __Windows__: doubleclick _nc-user-manager.exe_. 17 | * __Linux__ / __Mac__: install all dependencies (https://github.com/t-markmann/nc-userimporter/wiki#install-dependencies-for-running-py-script) and run: python3 nc-userimporter.py 18 | * __Troubleshooting__: Make sure the file is executable (https://www.qwant.com/?q=make%20file%20executable%20linux / https://www.qwant.com/?q=make%20file%20executable%20mac) 19 | 20 | 5. Follow the interactive commandline instructions. Check output.log ("logs"-folder in script-directory) and your user overview in Nextcloud. 21 | 22 | 23 | ## Output 24 | 25 | Screenshot output example: 26 | 27 | ![Generated PDF file with user credentials](https://github.com/t-markmann/nc-userimporter/blob/master/assets/screenshot_pdfoutput.png) 28 | 29 | --- 30 | 31 | ## ToDo 32 | 33 | * improve documentation of features https://github.com/t-markmann/nc-userimporter/wiki#todo-documentation 34 | 35 | Open features, not yet implemented (help appreciated): 36 | * read config from CLI-input if config-file is empty; update config.xml with input values? 37 | * add other userdata 38 | -------------------------------------------------------------------------------- /assets/EduDocs_Logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-markmann/nc-userimporter/12dc9c679dd8decb0bb4e215cb6ed2509f2ba98f/assets/EduDocs_Logo.jpg -------------------------------------------------------------------------------- /assets/Nextcloud_Logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-markmann/nc-userimporter/12dc9c679dd8decb0bb4e215cb6ed2509f2ba98f/assets/Nextcloud_Logo.jpg -------------------------------------------------------------------------------- /assets/screenshot_pdfoutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-markmann/nc-userimporter/12dc9c679dd8decb0bb4e215cb6ed2509f2ba98f/assets/screenshot_pdfoutput.png -------------------------------------------------------------------------------- /config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ENG 4 | 5 | 6 | mycloud.mydomain.org 7 | Cloudadmin 8 | 9 | your_password 10 | 11 | 12 | 13 | users.csv 14 | ; 15 | , 16 | yes 17 | yes 18 | yes 19 | 12 20 | True 21 | en 22 | 23 | 24 | INFO 25 | 26 | -------------------------------------------------------------------------------- /lang/ENG.json: -------------------------------------------------------------------------------- 1 | { 2 | "nc_userimporter_welcome": "Welcome to the Nextcloud user import", 3 | "nc_userimporter_process_preview": "Please carefully review the preview before starting the import process.", 4 | "nc_userimporter_press_continue": "When you are sure that your settings in the config.xml are correct,", 5 | "nc_userimporter_any_key": "press any key to continue, or press [CTRL + C] to abort the process.", 6 | "nc_userimporter_start_user_creation": "Starting user and group creation. This might take some time...", 7 | "nc_userimporter_user_creation_completed": "User and group creation completed successfully.", 8 | "nc_userimporter_user_created": "User '{username}' created successfully.", 9 | "nc_userimporter_user_exists": "User '{username}' already exists. Proceeding to synchronization.", 10 | "nc_userimporter_failed_user_creation": "Failed to create user '{username}'.", 11 | "nc_userimporter_group_created": "Group '{group}' created successfully.", 12 | "nc_userimporter_group_exists": "Group '{group}' already exists.", 13 | "nc_userimporter_group_failed": "Failed to create group '{group}'.", 14 | "nc_userimporter_exit_program": "Exiting the program. Goodbye!", 15 | "nc_userimporter_cleanup_done": "Temporary files cleaned up.", 16 | "nc_userimporter_welcome_sync": "Welcome to the Nextcloud user synchronization (update and deletion)", 17 | "nc_userimporter_process_preview_sync": "Please carefully review the displayed comparison and information tables before confirming an action.", 18 | "nc_userimporter_press_continue_sync": "If you are sure that your settings in config.xml are correct and you have selected the right CSV file,", 19 | "nc_userimporter_any_key_sync": "press any key to continue, or [CTRL + C] to abort the process.", 20 | "nc_userimporter_sync_start": "Starting user synchronization...", 21 | "nc_userimporter_sync_completed": "Synchronization completed.", 22 | "nc_userimporter_select_option": "Please select an option:", 23 | "nc_userimporter_import_option": "Import users from CSV", 24 | "nc_userimporter_sync_option": "Synchronize users and groups", 25 | "nc_userimporter_exit_option": "Exit the program", 26 | "nc_userimporter_enter_choice": "Enter your choice (1/2/3):", 27 | "nc_userimporter_invalid_choice": "Invalid choice, please try again.", 28 | "nc_userimporter_attention_no_password_set": "ATTENTION: You have specified that users for whom no password has been entered will receive an e-mail to set a password for themselves. Please make absolutely sure that a correct e-mail address is entered for every user for whom no password has been set!", 29 | "output_handler_greeting": "Hello", 30 | "output_handler_account_created": "A Nextcloud account has been created for you.", 31 | "output_handler_login_instructions": "You can log in with the following credentials:", 32 | "output_handler_nc_url": "Nextcloud URL", 33 | "output_handler_username": "Username", 34 | "output_handler_password": "Password", 35 | "output_handler_qr_code_alternative": "Alternatively, you can scan the following QR code in the Nextcloud app:", 36 | "user_sync_fetched_nextcloud_users": "Fetched users from Nextcloud", 37 | "user_sync_deleted_users_detected": "Deleted users detected", 38 | "user_sync_skip_admin": "Skipping deletion because user belongs to the admin group", 39 | "user_sync_prompt_delete": "!!! DELETE USER? !!!", 40 | "user_sync_prompt_deletion": "User is in Nextcloud but not in the CSV. Do you want to DELETE this user? (y/n): ", 41 | "user_sync_successful_deletion": "User successfully deleted", 42 | "user_sync_field": "Field", 43 | "user_sync_csv_user": "CSV User", 44 | "user_sync_nc_user": "Nextcloud User", 45 | "user_sync_username": "Username", 46 | "user_sync_display_name": "Display Name", 47 | "user_sync_email": "Email", 48 | "user_sync_groups": "Groups", 49 | "user_sync_subadmin_groups": "Subadmin Groups", 50 | "user_sync_changes_detected": "!!! CHANGES DETECTED !!!", 51 | "user_sync_prompt_changes": "Apply these changes to user? (y/n): " 52 | } 53 | -------------------------------------------------------------------------------- /lang/ESP.json: -------------------------------------------------------------------------------- 1 | { 2 | "nc_userimporter_welcome": "Bienvenido a la importación de usuarios de Nextcloud", 3 | "nc_userimporter_process_preview": "Por favor, revise cuidadosamente la vista previa antes de comenzar el proceso de importación.", 4 | "nc_userimporter_press_continue": "Cuando esté seguro de que su configuración en el archivo config.xml es correcta,", 5 | "nc_userimporter_any_key": "presione cualquier tecla para continuar o presione [CTRL + C] para cancelar el proceso.", 6 | "nc_userimporter_start_user_creation": "Comenzando la creación de usuarios y grupos. Esto puede tardar un poco...", 7 | "nc_userimporter_user_creation_completed": "La creación de usuarios y grupos se completó con éxito.", 8 | "nc_userimporter_user_created": "El usuario '{username}' se creó con éxito.", 9 | "nc_userimporter_user_exists": "El usuario '{username}' ya existe. Continuando con la sincronización.", 10 | "nc_userimporter_failed_user_creation": "Error al crear el usuario '{username}'.", 11 | "nc_userimporter_group_created": "El grupo '{group}' se creó con éxito.", 12 | "nc_userimporter_group_exists": "El grupo '{group}' ya existe.", 13 | "nc_userimporter_group_failed": "Error al crear el grupo '{group}'.", 14 | "nc_userimporter_exit_program": "Saliendo del programa. ¡Adiós!", 15 | "nc_userimporter_cleanup_done": "Los archivos temporales han sido limpiados.", 16 | "nc_userimporter_welcome_sync": "Bienvenido a la sincronización de usuarios de Nextcloud (actualización y eliminación)", 17 | "nc_userimporter_process_preview_sync": "Por favor, revise cuidadosamente las tablas de comparación e información antes de confirmar una acción.", 18 | "nc_userimporter_press_continue_sync": "Si está seguro de que su configuración en config.xml es correcta y ha seleccionado el archivo CSV correcto,", 19 | "nc_userimporter_any_key_sync": "presione cualquier tecla para continuar, o [CTRL + C] para abortar el proceso.", 20 | "nc_userimporter_sync_start": "Comenzando la sincronización de usuarios...", 21 | "nc_userimporter_sync_completed": "Sincronización completada.", 22 | "nc_userimporter_select_option": "Por favor, seleccione una opción:", 23 | "nc_userimporter_import_option": "Importar usuarios desde CSV", 24 | "nc_userimporter_sync_option": "Sincronizar usuarios y grupos", 25 | "nc_userimporter_exit_option": "Salir del programa", 26 | "nc_userimporter_enter_choice": "Ingrese su elección (1/2/3):", 27 | "nc_userimporter_invalid_choice": "Opción no válida, inténtelo de nuevo.", 28 | "nc_userimporter_attention_no_password_set": "ATENCIÓN: Ha especificado que los usuarios para los cuales no se ha ingresado una contraseña recibirán un correo electrónico para establecer una contraseña por sí mismos. ¡Asegúrese absolutamente de que se haya ingresado una dirección de correo electrónico correcta para cada usuario al que no se le haya asignado una contraseña!", 29 | "output_handler_greeting": "Hola", 30 | "output_handler_account_created": "Se ha creado una cuenta de Nextcloud para ti.", 31 | "output_handler_login_instructions": "Puedes iniciar sesión con las siguientes credenciales:", 32 | "output_handler_nc_url": "URL de Nextcloud", 33 | "output_handler_username": "Nombre de usuario", 34 | "output_handler_password": "Contraseña", 35 | "output_handler_qr_code_alternative": "Alternativamente, puedes escanear el siguiente código QR en la app de Nextcloud:", 36 | "user_sync_fetched_nextcloud_users": "Usuarios recuperados de Nextcloud", 37 | "user_sync_deleted_users_detected": "Usuarios eliminados detectados", 38 | "user_sync_skip_admin": "Se omite la eliminación porque el usuario pertenece al grupo admin", 39 | "user_sync_prompt_delete": "!!! ¿ELIMINAR USUARIO? !!!", 40 | "user_sync_prompt_deletion": "El usuario está en Nextcloud pero no en el CSV. ¿Deseas ELIMINAR este usuario? (y/n): ", 41 | "user_sync_successful_deletion": "Usuario eliminado con éxito", 42 | "user_sync_field": "Campo", 43 | "user_sync_csv_user": "Usuario CSV", 44 | "user_sync_nc_user": "Usuario de Nextcloud", 45 | "user_sync_username": "Nombre de usuario", 46 | "user_sync_display_name": "Nombre para mostrar", 47 | "user_sync_email": "Correo electrónico", 48 | "user_sync_groups": "Grupos", 49 | "user_sync_subadmin_groups": "Grupos Subadmin", 50 | "user_sync_changes_detected": "!!! CAMBIOS DETECTADOS !!!", 51 | "user_sync_prompt_changes": "¿Aplicar estos cambios al usuario? (y/n): " 52 | } 53 | -------------------------------------------------------------------------------- /lang/FRA.json: -------------------------------------------------------------------------------- 1 | { 2 | "nc_userimporter_welcome": "Bienvenue dans l'importation des utilisateurs Nextcloud", 3 | "nc_userimporter_process_preview": "Veuillez examiner attentivement l'aperçu avant de commencer le processus d'importation.", 4 | "nc_userimporter_press_continue": "Lorsque vous êtes sûr que vos paramètres dans le fichier config.xml sont corrects,", 5 | "nc_userimporter_any_key": "appuyez sur n'importe quelle touche pour continuer ou appuyez sur [CTRL + C] pour annuler le processus.", 6 | "nc_userimporter_start_user_creation": "Création des utilisateurs et des groupes en cours. Cela peut prendre un certain temps...", 7 | "nc_userimporter_user_creation_completed": "La création des utilisateurs et des groupes a été effectuée avec succès.", 8 | "nc_userimporter_user_created": "L'utilisateur '{username}' a été créé avec succès.", 9 | "nc_userimporter_user_exists": "L'utilisateur '{username}' existe déjà. La synchronisation se poursuit.", 10 | "nc_userimporter_failed_user_creation": "Échec de la création de l'utilisateur '{username}'.", 11 | "nc_userimporter_group_created": "Le groupe '{group}' a été créé avec succès.", 12 | "nc_userimporter_group_exists": "Le groupe '{group}' existe déjà.", 13 | "nc_userimporter_group_failed": "Échec de la création du groupe '{group}'.", 14 | "nc_userimporter_exit_program": "Fermeture du programme. Au revoir !", 15 | "nc_userimporter_cleanup_done": "Les fichiers temporaires ont été nettoyés.", 16 | "nc_userimporter_welcome_sync": "Bienvenue dans la synchronisation des utilisateurs Nextcloud (mise à jour et suppression)", 17 | "nc_userimporter_process_preview_sync": "Veuillez examiner attentivement les tableaux de comparaison et d'information affichés avant de confirmer une action.", 18 | "nc_userimporter_press_continue_sync": "Si vous êtes sûr que vos paramètres dans le fichier config.xml sont corrects et que vous avez sélectionné le bon fichier CSV,", 19 | "nc_userimporter_any_key_sync": "appuyez sur une touche pour continuer, ou [CTRL + C] pour annuler le processus.", 20 | "nc_userimporter_sync_start": "Début de la synchronisation des utilisateurs...", 21 | "nc_userimporter_sync_completed": "La synchronisation est terminée.", 22 | "nc_userimporter_select_option": "Veuillez choisir une option :", 23 | "nc_userimporter_import_option": "Importer des utilisateurs depuis un fichier CSV", 24 | "nc_userimporter_sync_option": "Synchroniser les utilisateurs et les groupes", 25 | "nc_userimporter_exit_option": "Quitter le programme", 26 | "nc_userimporter_enter_choice": "Entrez votre choix (1/2/3) :", 27 | "nc_userimporter_invalid_choice": "Choix invalide, veuillez réessayer.", 28 | "nc_userimporter_attention_no_password_set": "ATTENTION : Vous avez spécifié que les utilisateurs pour lesquels aucun mot de passe n'a été saisi recevront un e-mail pour définir eux-mêmes un mot de passe. Veuillez vous assurer absolument qu'une adresse e-mail correcte est saisie pour chaque utilisateur pour lequel aucun mot de passe n'a été défini !", 29 | "output_handler_greeting": "Bonjour", 30 | "output_handler_account_created": "Un compte Nextcloud a été créé pour vous.", 31 | "output_handler_login_instructions": "Vous pouvez vous connecter avec les identifiants suivants:", 32 | "output_handler_nc_url": "URL Nextcloud", 33 | "output_handler_username": "Nom d'utilisateur", 34 | "output_handler_password": "Mot de passe", 35 | "output_handler_qr_code_alternative": "Sinon, vous pouvez scanner le QR code suivant dans l'application Nextcloud:", 36 | "user_sync_fetched_nextcloud_users": "Utilisateurs récupérés de Nextcloud", 37 | "user_sync_deleted_users_detected": "Utilisateurs supprimés détectés", 38 | "user_sync_skip_admin": "Suppression ignorée car l'utilisateur appartient au groupe admin", 39 | "user_sync_prompt_delete": "!!! SUPPRIMER L'UTILISATEUR? !!!", 40 | "user_sync_prompt_deletion": "L'utilisateur est dans Nextcloud mais pas dans le CSV. Voulez-vous SUPPRIMER cet utilisateur? (y/n): ", 41 | "user_sync_successful_deletion": "Utilisateur supprimé avec succès", 42 | "user_sync_field": "Champ", 43 | "user_sync_csv_user": "Utilisateur CSV", 44 | "user_sync_nc_user": "Utilisateur Nextcloud", 45 | "user_sync_username": "Nom d'utilisateur", 46 | "user_sync_display_name": "Nom d'affichage", 47 | "user_sync_email": "Email", 48 | "user_sync_groups": "Groupes", 49 | "user_sync_subadmin_groups": "Groupes Subadmin", 50 | "user_sync_changes_detected": "!!! CHANGEMENTS DÉTECTÉS !!!", 51 | "user_sync_prompt_changes": "Appliquer ces modifications à l'utilisateur? (y/n): " 52 | } 53 | -------------------------------------------------------------------------------- /lang/GER.json: -------------------------------------------------------------------------------- 1 | { 2 | "nc_userimporter_welcome": "Willkommen beim Nextcloud-Benutzerimport", 3 | "nc_userimporter_process_preview": "Bitte überprüfen Sie die Vorschau sorgfältig, bevor Sie den Importprozess starten.", 4 | "nc_userimporter_press_continue": "Wenn Sie sicher sind, dass Ihre Einstellungen in der config.xml korrekt sind,", 5 | "nc_userimporter_any_key": "drücken Sie eine beliebige Taste, um fortzufahren, oder [CTRL + C], um den Vorgang abzubrechen.", 6 | "nc_userimporter_start_user_creation": "Beginne mit der Erstellung von Benutzern und Gruppen. Dies kann einige Zeit dauern...", 7 | "nc_userimporter_user_creation_completed": "Benutzer- und Gruppenerstellung erfolgreich abgeschlossen.", 8 | "nc_userimporter_user_created": "Benutzer '{username}' wurde erfolgreich erstellt.", 9 | "nc_userimporter_user_exists": "Benutzer '{username}' existiert bereits. Synchronisation wird fortgesetzt.", 10 | "nc_userimporter_failed_user_creation": "Benutzer '{username}' konnte nicht erstellt werden.", 11 | "nc_userimporter_group_created": "Gruppe '{group}' wurde erfolgreich erstellt.", 12 | "nc_userimporter_group_exists": "Gruppe '{group}' existiert bereits.", 13 | "nc_userimporter_group_failed": "Gruppe '{group}' konnte nicht erstellt werden.", 14 | "nc_userimporter_exit_program": "Das Programm wird beendet. Auf Wiedersehen!", 15 | "nc_userimporter_cleanup_done": "Temporäre Dateien wurden bereinigt.", 16 | "nc_userimporter_welcome_sync": "Willkommen bei der Nextcloud-Benutzersynchronisation (Aktualisierung und Löschung)", 17 | "nc_userimporter_process_preview_sync": "Bitte überprüfen Sie die angezeigten Vergleichs- und Informationstabellen sorgfältig, bevor Sie eine Aktion bestätigen.", 18 | "nc_userimporter_press_continue_sync": "Wenn Sie sicher sind, dass Ihre Einstellungen in der config.xml korrekt sind und Sie die richtige CSV-Datei ausgewählt haben,", 19 | "nc_userimporter_any_key_sync": "drücken Sie eine beliebige Taste, um fortzufahren, oder [CTRL + C], um den Vorgang abzubrechen.", 20 | "nc_userimporter_sync_start": "Synchronisation der Benutzer wird gestartet...", 21 | "nc_userimporter_sync_completed": "Synchronisation abgeschlossen.", 22 | "nc_userimporter_select_option": "Bitte wählen Sie eine Option:", 23 | "nc_userimporter_import_option": "Benutzer aus CSV importieren", 24 | "nc_userimporter_sync_option": "Benutzer und Gruppen synchronisieren", 25 | "nc_userimporter_exit_option": "Programm beenden", 26 | "nc_userimporter_enter_choice": "Geben Sie Ihre Wahl ein (1/2/3):", 27 | "nc_userimporter_invalid_choice": "Ungültige Auswahl, bitte versuchen Sie es erneut.", 28 | "nc_userimporter_attention_no_password_set": "ACHTUNG: Sie haben angegeben, dass Benutzer, für die kein Passwort eingegeben wurde, eine E-Mail erhalten, um ein Passwort selbst festzulegen. Bitte stellen Sie unbedingt sicher, dass für jeden Benutzer, für den kein Passwort festgelegt wurde, eine korrekte E-Mail-Adresse eingetragen ist!", 29 | "output_handler_greeting": "Hallo", 30 | "output_handler_account_created": "Ein Nextcloud-Konto wurde für Sie erstellt.", 31 | "output_handler_login_instructions": "Sie können sich mit den folgenden Anmeldedaten einloggen:", 32 | "output_handler_nc_url": "Nextcloud-URL", 33 | "output_handler_username": "Benutzername", 34 | "output_handler_password": "Passwort", 35 | "output_handler_qr_code_alternative": "Alternativ können Sie den folgenden QR-Code in der Nextcloud-App scannen:", 36 | "user_sync_fetched_nextcloud_users": "Benutzer aus Nextcloud abgerufen", 37 | "user_sync_deleted_users_detected": "Gelöschte Benutzer erkannt", 38 | "user_sync_skip_admin": "Löschen übersprungen, da der Benutzer zur Admin-Gruppe gehört", 39 | "user_sync_prompt_delete": "!!! BENUTZER LÖSCHEN? !!!", 40 | "user_sync_prompt_deletion": "Benutzer ist in Nextcloud, aber nicht in der CSV. Möchten Sie diesen Benutzer LÖSCHEN? (y/n): ", 41 | "user_sync_successful_deletion": "Benutzer erfolgreich gelöscht", 42 | "user_sync_field": "Feld", 43 | "user_sync_csv_user": "CSV-Benutzer", 44 | "user_sync_nc_user": "Nextcloud-Benutzer", 45 | "user_sync_username": "Benutzername", 46 | "user_sync_display_name": "Anzeigename", 47 | "user_sync_email": "E-Mail", 48 | "user_sync_groups": "Gruppen", 49 | "user_sync_subadmin_groups": "Subadmin-Gruppen", 50 | "user_sync_changes_detected": "!!! ÄNDERUNGEN ERKANNT !!!", 51 | "user_sync_prompt_changes": "Änderungen für diesen Benutzer anwenden? (y/n): " 52 | } 53 | -------------------------------------------------------------------------------- /modules/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This package contains several utility modules for managing Nextcloud user imports, 3 | password generation, CSV handling, output generation, and API communication with Nextcloud. 4 | 5 | Modules included: 6 | - config: Provides the ConfigReader class for reading and parsing the XML configuration file. 7 | - password: Provides the PasswordGenerator class for generating random secure passwords. 8 | - csv_handler: Provides the read_csv function for handling CSV file imports. 9 | - output_handler: Provides the generate_qr_code and generate_pdf functions for creating QR codes and PDF documents. 10 | - mapping: Exports the MAPPING dictionary used for special character handling in usernames. 11 | - nextcloud_api: Provides the NextcloudAPI class for interacting with the Nextcloud API. 12 | """ 13 | 14 | # Import specific classes and functions from the package modules for external use. 15 | from .config import ConfigReader # Handles reading and parsing XML configuration files 16 | from .password import PasswordGenerator # Generates secure random passwords 17 | from .csv_handler import read_csv # Reads and parses CSV files for user imports 18 | from .output_handler import generate_qr_code, generate_pdf # Generates QR codes and PDFs for user output 19 | from .mapping import MAPPING # Provides a dictionary for special character mapping (e.g., for username sanitization) 20 | from .nextcloud_api import NextcloudAPI # Manages interaction with the Nextcloud APIfrom .user_sync import NextcloudUserManager 21 | from .user_sync import NextcloudUserManager 22 | from .language_loader import load_language -------------------------------------------------------------------------------- /modules/config.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup 2 | import codecs 3 | import logging 4 | 5 | class ConfigReader: 6 | """ 7 | ConfigReader is responsible for loading and parsing an XML-based configuration file. 8 | It provides an interface for accessing configuration values stored in the XML file. 9 | Values are read once during initialization and can be accessed via the `get` method. 10 | """ 11 | 12 | def __init__(self, config_file): 13 | """ 14 | Initializes the ConfigReader and loads the configuration file. 15 | 16 | Args: 17 | config_file (str): The path to the XML configuration file. 18 | """ 19 | self.config_file = config_file 20 | self.config_values = self._load_config() 21 | 22 | def _load_config(self): 23 | """ 24 | Reads and parses the XML configuration file using BeautifulSoup. 25 | 26 | Returns: 27 | dict: A dictionary of configuration keys and their corresponding values. 28 | 29 | Raises: 30 | FileNotFoundError: If the config file does not exist. 31 | UnicodeDecodeError: If there is an issue reading the file in UTF-8 encoding. 32 | """ 33 | try: 34 | # Open the config file with UTF-8 encoding using the codecs module 35 | with codecs.open(self.config_file, mode='r', encoding='utf-8') as configfile: 36 | config_content = configfile.read() 37 | except FileNotFoundError: 38 | logging.error(f"Configuration file '{self.config_file}' not found.") 39 | raise 40 | except UnicodeDecodeError: 41 | logging.error(f"Error reading '{self.config_file}' with UTF-8 encoding.") 42 | raise 43 | 44 | # Parse the XML content using BeautifulSoup with the 'lxml-xml' parser 45 | config_xmlsoup = BeautifulSoup(config_content, "lxml-xml") 46 | 47 | # Define the expected configuration keys in the XML file 48 | config_keys = [ 49 | 'cloudurl', 'adminname', 'adminpass', 'csvfile', 'csvdelimiter', 50 | 'csvdelimitergroups', 'generatepassword', 'passwordlength', 51 | 'sslverify', 'language', 'pdf_one_file', 'pdf_single_files', 'loglevel', 'scriptlang' 52 | ] 53 | 54 | # Dictionary to hold key-value pairs from the XML configuration file 55 | config_values = {} 56 | 57 | # Extract values for the expected configuration keys from the XML 58 | for key in config_keys: 59 | element = config_xmlsoup.find(key) # Find the XML tag by key name 60 | if element and element.string: # Check if the element exists and contains text 61 | config_values[key] = element.string.strip() # Store value without surrounding whitespace 62 | else: 63 | logging.warning(f"Element <{key}> not found or has no text content.") 64 | 65 | return config_values 66 | 67 | def get(self, key, fallback=None): 68 | """ 69 | Retrieves the value for a given configuration key. 70 | 71 | Args: 72 | key (str): The name of the configuration key. 73 | fallback (str, optional): A fallback value to return if the key is not found. 74 | Defaults to None. 75 | 76 | Returns: 77 | str: The value associated with the key, or the fallback value if the key is not found. 78 | 79 | Raises: 80 | KeyError: If the key is not found and no fallback is provided. 81 | """ 82 | value = self.config_values.get(key) 83 | 84 | if value is None: 85 | if fallback is not None: 86 | # Log a warning if we fall back to the default value 87 | logging.warning(f"Configuration key '{key}' not found. Using fallback value '{fallback}'.") 88 | return fallback 89 | else: 90 | # Log an error and raise an exception if no fallback is provided 91 | logging.error(f"Configuration key '{key}' is missing and no fallback was provided.") 92 | raise KeyError(f"Missing configuration key: {key}") 93 | return value 94 | -------------------------------------------------------------------------------- /modules/csv_handler.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import codecs 3 | import logging 4 | 5 | def read_csv(filepath, delimiter=','): 6 | """ 7 | Reads a CSV file and returns the data as a list of dictionaries. 8 | Each dictionary represents a row with keys as the CSV header. 9 | 10 | :param filepath: The path to the CSV file. 11 | :param delimiter: The delimiter used in the CSV file (default is ','). 12 | :return: A list of dictionaries where each dictionary represents a row in the CSV. 13 | """ 14 | try: 15 | # Open the CSV file with UTF-8 encoding to ensure proper handling of special characters 16 | with codecs.open(filepath, mode='r', encoding='utf-8') as csvfile: 17 | reader = csv.DictReader(csvfile, delimiter=delimiter) 18 | 19 | # Read all rows into a list of dictionaries 20 | data = [row for row in reader] 21 | 22 | # Check if the CSV file is empty or improperly formatted 23 | if not data: 24 | logging.warning(f"CSV file '{filepath}' is empty or improperly formatted.") 25 | 26 | return data 27 | 28 | except FileNotFoundError as e: 29 | # Log and raise an error if the CSV file is not found 30 | logging.error(f"CSV file not found: {e}") 31 | raise 32 | 33 | except csv.Error as e: 34 | # Log and raise an error if there is an issue with CSV formatting 35 | logging.error(f"Error reading CSV file '{filepath}': {e}") 36 | raise 37 | 38 | except Exception as e: 39 | # Catch and log any other unexpected exceptions 40 | logging.error(f"An unexpected error occurred while reading the CSV file '{filepath}': {e}") 41 | raise 42 | -------------------------------------------------------------------------------- /modules/language_loader.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import logging 4 | 5 | def load_language(config_reader): 6 | """ 7 | Loads the language file based on the language setting in the configuration file (config.xml). 8 | 9 | If the specified language file is not found, it defaults to English ('ENG.json'). 10 | 11 | :param config_reader: An instance of ConfigReader used to retrieve configuration settings. 12 | :return: A dictionary containing the language strings. 13 | """ 14 | 15 | # Retrieve the script language from the configuration, defaulting to English if not set 16 | script_lang = config_reader.get('scriptlang', 'ENG') 17 | logging.debug(f"Attempting to load language: {script_lang}") 18 | 19 | # Construct the path to the language file based on the script language 20 | lang_file_path = os.path.join('lang', f"{script_lang}.json") 21 | 22 | try: 23 | # Attempt to open and load the specified language file 24 | with open(lang_file_path, 'r', encoding='utf-8') as lang_file: 25 | language_data = json.load(lang_file) 26 | logging.debug(f"Successfully loaded language file: {lang_file_path}") 27 | return language_data 28 | except FileNotFoundError: 29 | # Log an error if the specified language file is not found, then default to English 30 | logging.error(f"Language file '{lang_file_path}' not found. Defaulting to English.") 31 | 32 | # Path to the default English language file 33 | default_lang_file_path = os.path.join('lang', 'ENG.json') 34 | 35 | try: 36 | # Attempt to load the default English language file 37 | with open(default_lang_file_path, 'r', encoding='utf-8') as default_lang_file: 38 | default_language_data = json.load(default_lang_file) 39 | logging.info(f"Loaded default English language file: {default_lang_file_path}") 40 | return default_language_data 41 | except FileNotFoundError: 42 | # If the default language file is also not found, raise a critical error 43 | logging.critical(f"Default language file '{default_lang_file_path}' not found. Exiting program.") 44 | raise SystemExit(f"Critical Error: Default language file '{default_lang_file_path}' not found.") 45 | -------------------------------------------------------------------------------- /modules/mapping.py: -------------------------------------------------------------------------------- 1 | # Mapping dictionary for converting special characters and umlauts to their ASCII-equivalent. 2 | # This is primarily used for converting non-ASCII characters to a compatible spelling for usernames. 3 | 4 | MAPPING = { 5 | # German umlauts 6 | ord("Ä"): "Ae", ord("ä"): "ae", 7 | ord("Ö"): "Oe", ord("ö"): "oe", 8 | ord("Ü"): "Ue", ord("ü"): "ue", 9 | ord("ß"): "ss", 10 | 11 | # Scandinavian letters 12 | ord("Å"): "A", ord("å"): "a", 13 | ord("Ø"): "Oe", ord("ø"): "oe", 14 | ord("Æ"): "Ae", ord("æ"): "ae", 15 | 16 | # French accented letters 17 | ord("À"): "A", ord("à"): "a", 18 | ord("Á"): "A", ord("á"): "a", 19 | ord("Â"): "A", ord("â"): "a", 20 | ord("Ã"): "A", ord("ã"): "a", 21 | ord("Ç"): "C", ord("ç"): "c", 22 | ord("È"): "E", ord("è"): "e", 23 | ord("É"): "E", ord("é"): "e", 24 | ord("Ê"): "E", ord("ê"): "e", 25 | ord("Ë"): "E", ord("ë"): "e", 26 | ord("Ì"): "I", ord("ì"): "i", 27 | ord("Í"): "I", ord("í"): "i", 28 | ord("Î"): "I", ord("î"): "i", 29 | ord("Ï"): "I", ord("ï"): "i", 30 | ord("Ð"): "D", ord("ð"): "d", 31 | ord("Ñ"): "N", ord("ñ"): "n", 32 | ord("Ò"): "O", ord("ò"): "o", 33 | ord("Ó"): "O", ord("ó"): "o", 34 | ord("Ô"): "O", ord("ô"): "o", 35 | ord("Õ"): "O", ord("õ"): "o", 36 | ord("Œ"): "Oe", ord("œ"): "oe", 37 | ord("Ù"): "U", ord("ù"): "u", 38 | ord("Ú"): "U", ord("ú"): "u", 39 | ord("Û"): "U", ord("û"): "u", 40 | ord("Ý"): "Y", ord("ý"): "y", 41 | ord("Ÿ"): "Y", ord("ÿ"): "y", 42 | 43 | # Icelandic letters 44 | ord("Þ"): "Th", ord("þ"): "Th", 45 | 46 | # Czech/Slovak characters 47 | ord("Š"): "S", ord("š"): "s", 48 | ord("Č"): "C", ord("č"): "c" 49 | } 50 | -------------------------------------------------------------------------------- /modules/nextcloud_api.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import logging 3 | from lxml import etree 4 | import certifi 5 | 6 | 7 | class NextcloudAPI: 8 | def __init__(self, base_url, adminname, adminpass, ssl_verify=True): 9 | """ 10 | Initialize the NextcloudAPI class with base URL, admin username, password, and SSL verification setting. 11 | 12 | :param base_url: The base URL of the Nextcloud server. 13 | :param adminname: The username of the admin account. 14 | :param adminpass: The password of the admin account. 15 | :param ssl_verify: Boolean indicating whether to verify SSL certificates. 16 | """ 17 | self.logger = logging.getLogger(__name__) # Logger specific to this class 18 | 19 | # Ensure the base URL starts with https:// and remove trailing slash if present 20 | if not base_url.startswith("https://"): 21 | base_url = f"https://{base_url}" 22 | self.base_url = base_url.rstrip('/') 23 | 24 | self.adminname = adminname 25 | self.adminpass = adminpass 26 | self.headers = { 27 | 'OCS-APIRequest': 'true', # Required for Nextcloud OCS API requests 28 | 'Accept-Language': 'en' # Force English response 29 | } 30 | self.auth = (self.adminname, self.adminpass) # Basic authentication for Nextcloud API 31 | 32 | if ssl_verify is True: 33 | self.ssl_verify = certifi.where() 34 | self.logger.debug(f"Using certifi bundle: {self.ssl_verify}") # Gib den Pfad von certifi.where() aus 35 | else: 36 | self.ssl_verify = False 37 | self.logger.info("SSL verification disabled") 38 | 39 | def _request(self, method, endpoint, data=None, headers=None): 40 | """ 41 | Helper method to send requests to the Nextcloud API. 42 | 43 | Args: 44 | method (str): HTTP method (GET, POST, PUT, DELETE). 45 | endpoint (str): API endpoint. 46 | data (dict): Optional data to send in the request. 47 | headers (dict): Optional headers for the request. 48 | 49 | Returns: 50 | dict: Parsed response dictionary, or False if the request failed. 51 | """ 52 | url = f"{self.base_url}/{endpoint}" 53 | headers = headers or self.headers 54 | 55 | try: 56 | self.logger.debug(f"Requesting {method} {url} with data: {data}") 57 | if method in ['POST', 'PUT']: 58 | headers['Content-Type'] = 'application/x-www-form-urlencoded' 59 | 60 | response = requests.request( 61 | method=method, 62 | url=url, 63 | headers=headers, 64 | auth=self.auth, 65 | data=data, 66 | verify=self.ssl_verify 67 | ) 68 | response.raise_for_status() 69 | 70 | if response.headers.get('Content-Type') == 'application/xml' or response.text.startswith(' {value}") 246 | return True 247 | elif status_code == 101: 248 | logging.error(f"Failed to update user '{username}': User not found.") 249 | elif status_code == 102: 250 | logging.error(f"Failed to update user '{username}': Invalid input data for {key}.") 251 | else: 252 | logging.error(f"Failed to update user '{username}': Unexpected status code {status_code}.") 253 | else: 254 | logging.error(f"Failed to update user '{username}': Unexpected response type: {response}") 255 | 256 | return False 257 | 258 | def disable_user(self, username): 259 | """Disable the specified user by username.""" 260 | return self._request('PUT', f'ocs/v1.php/cloud/users/{username}/disable') 261 | 262 | def enable_user(self, username): 263 | """Enable the specified user by username.""" 264 | return self._request('PUT', f'ocs/v1.php/cloud/users/{username}/enable') 265 | 266 | def delete_user(self, username): 267 | """Delete the specified user by username.""" 268 | return self._request('DELETE', f'ocs/v1.php/cloud/users/{username}') 269 | 270 | 271 | # Group Management Functions 272 | 273 | def get_groups(self): 274 | """Retrieve a list of all groups from the Nextcloud server.""" 275 | return self._request('GET', 'ocs/v1.php/cloud/groups') 276 | 277 | def get_user_groups(self, username): 278 | """ 279 | Retrieve the groups a specific user belongs to by username and return them as a list. 280 | """ 281 | response = self._request('GET', f'ocs/v1.php/cloud/users/{username}/groups') 282 | if self.is_successful(response): 283 | return self.parse_groups_from_response(response['response']) 284 | else: 285 | self.logger.error(f"Failed to fetch groups for user '{username}'") 286 | return [] 287 | 288 | def create_groups(self, groups): 289 | """Create new groups on the Nextcloud server.""" 290 | return [self._request('POST', 'ocs/v1.php/cloud/groups', data={'groupid': group}) for group in groups] 291 | 292 | def ensure_groups_exist(self, groups): 293 | """ 294 | Ensure that the specified groups exist in Nextcloud. If any group doesn't exist, create it. 295 | 296 | Args: 297 | groups (list): List of groups to check and create if necessary. 298 | 299 | Returns: 300 | bool: True if all groups exist or were successfully created, False otherwise. 301 | """ 302 | # Fetch existing groups 303 | existing_groups_response = self.get_groups() 304 | if not self.is_successful(existing_groups_response): 305 | self.logger.error("Failed to fetch existing groups.") 306 | return False 307 | 308 | # Parse the existing groups 309 | existing_groups = set(self.parse_groups_from_response(existing_groups_response['response'])) 310 | 311 | # Create groups that don't exist 312 | for group in groups: 313 | if group not in existing_groups: 314 | self.logger.info(f"Group '{group}' does not exist. Creating it...") 315 | group_creation_response = self.create_groups([group]) 316 | if not self.is_successful(group_creation_response[0]): 317 | self.logger.info(f"Failed to create group '{group}': {group_creation_response[0].get('message')}") 318 | return False 319 | else: 320 | self.logger.info(f"Group '{group}' created successfully.") 321 | 322 | return True 323 | 324 | def add_user_to_groups(self, username, groups): 325 | """Add the specified user to one or more groups.""" 326 | responses = [self._request('POST', f'ocs/v1.php/cloud/users/{username}/groups', data={'groupid': group}) for group in groups] 327 | return all(self.is_successful(response) for response in responses) 328 | 329 | def remove_user_from_groups(self, username, groups): 330 | """ 331 | Remove the specified user from one or more groups. 332 | 333 | Args: 334 | username (str): The username of the user to remove from groups. 335 | groups (list): A list of group IDs to remove the user from. 336 | 337 | Returns: 338 | bool: True if the user was successfully removed from all groups, False otherwise. 339 | """ 340 | for group in groups: 341 | response = self._request('DELETE', f'ocs/v1.php/cloud/users/{username}/groups?groupid={group}') 342 | if not self.is_successful(response): 343 | self.logger.error(f"Failed to remove {username} from group '{group}': {response.get('message')}") 344 | return False 345 | return True 346 | 347 | def sync_user_to_groups(self, username, current_groups, new_groups): 348 | """ 349 | Synchronize a user to groups by adding or removing them as necessary. 350 | 351 | Args: 352 | username (str): The username of the user. 353 | current_groups (set): The current set of groups the user belongs to. 354 | new_groups (set): The new set of groups the user should belong to. 355 | 356 | Returns: 357 | bool: True if the synchronization is successful, False otherwise. 358 | """ 359 | groups_to_add = new_groups - current_groups 360 | groups_to_remove = current_groups - new_groups 361 | 362 | # Ensure that all groups to add exist, create them if necessary 363 | if groups_to_add: 364 | logging.info(f"Ensuring that the following groups exist: {groups_to_add}") 365 | if not self.ensure_groups_exist(groups_to_add): 366 | logging.error(f"Failed to ensure all groups exist for {username}.") 367 | return False 368 | 369 | # Add the user to new groups 370 | if groups_to_add: 371 | logging.info(f"Adding {username} to groups: {groups_to_add}") 372 | if not self.add_user_to_groups(username, groups_to_add): 373 | logging.error(f"Failed to add {username} to groups.") 374 | return False 375 | 376 | # Remove the user from groups that are no longer assigned 377 | if groups_to_remove: 378 | logging.info(f"Removing {username} from groups: {groups_to_remove}") 379 | if not self.remove_user_from_groups(username, groups_to_remove): 380 | logging.error(f"Failed to remove {username} from groups.") 381 | return False 382 | 383 | return True 384 | 385 | def sync_groups(self, username, new_groups): 386 | current_groups = set(self.get_user_groups(username)) 387 | return self.sync_user_to_groups(username, current_groups, new_groups) 388 | 389 | 390 | # Subadmin-Group Management Functions 391 | 392 | 393 | def get_user_subadmin_groups(self, username): 394 | """Retrieve the groups in which the specified user is a subadmin.""" 395 | response = self._request('GET', f'ocs/v1.php/cloud/users/{username}/subadmins') 396 | if self.is_successful(response): 397 | return self.parse_groups_from_response(response['response']) 398 | else: 399 | self.logger.error(f"Failed to fetch subadmin groups for user '{username}'") 400 | return [] 401 | 402 | def promote_user_in_group(self, username, groups): 403 | """ 404 | Promote the specified user to subadmin in one or more groups. 405 | 406 | Args: 407 | username (str): The username of the user to promote. 408 | groups (list): A list of group IDs to promote the user to subadmin. 409 | 410 | Returns: 411 | bool: True if the user was successfully promoted to subadmin in all groups, False otherwise. 412 | """ 413 | # Ensure that all groups exist before promoting the user 414 | if not self.ensure_groups_exist(groups): 415 | self.logger.error(f"Failed to ensure all groups exist for promoting {username} to subadmin.") 416 | return False 417 | 418 | # Proceed to promote the user to subadmin in each group 419 | for group in groups: 420 | response = self._request('POST', f'ocs/v1.php/cloud/users/{username}/subadmins', data={'groupid': group}) 421 | if not self.is_successful(response): 422 | self.logger.error(f"Failed to promote {username} to subadmin in group '{group}': {response.get('message')}") 423 | return False 424 | return True 425 | 426 | def demote_user_in_group(self, username, groups): 427 | """Demote the specified user from subadmin in one or more groups.""" 428 | # DELETE requests should send groupid in the URL, not as data 429 | return [self._request('DELETE', f'ocs/v1.php/cloud/users/{username}/subadmins?groupid={group}') for group in groups] 430 | 431 | def sync_subadmin_groups(self, username, new_subadmin_groups): 432 | """ 433 | Synchronize the user's subadmin status for groups. 434 | 435 | Args: 436 | username (str): The username of the user to sync subadmin groups for. 437 | new_subadmin_groups (set): The new set of subadmin groups for the user. 438 | 439 | Returns: 440 | bool: True if the synchronization was successful, False otherwise. 441 | """ 442 | current_subadmin_groups = set(self.get_user_subadmin_groups(username)) 443 | subadmin_to_add = new_subadmin_groups - current_subadmin_groups 444 | subadmin_to_remove = current_subadmin_groups - new_subadmin_groups 445 | 446 | # Ensure all groups to add exist 447 | if subadmin_to_add: 448 | self.logger.info(f"Ensuring that the following groups exist for subadmin promotion: {subadmin_to_add}") 449 | if not self.ensure_groups_exist(subadmin_to_add): 450 | self.logger.error(f"Failed to ensure groups exist for subadmin promotion for {username}.") 451 | return False 452 | 453 | if subadmin_to_add: 454 | self.logger.info(f"Promoting {username} to subadmin of groups: {subadmin_to_add}") 455 | if not self.promote_user_in_group(username, subadmin_to_add): 456 | self.logger.error(f"Failed to promote {username} to subadmin.") 457 | return False 458 | 459 | if subadmin_to_remove: 460 | self.logger.info(f"Demoting {username} from subadmin of groups: {subadmin_to_remove}") 461 | if not self.demote_user_in_group(username, subadmin_to_remove): 462 | self.logger.error(f"Failed to demote {username} from subadmin.") 463 | return False 464 | 465 | return True 466 | 467 | 468 | # Circle Management Functions 469 | 470 | 471 | def get_circles(self): 472 | """List all circles available in Nextcloud.""" 473 | return self._request('GET', 'apps/circles/circles') 474 | 475 | 476 | # Other Operations 477 | 478 | def resend_welcome_mail(self, username): 479 | """Resend the welcome email to the specified user.""" 480 | return self._request('POST', f'ocs/v1.php/cloud/users/{username}/welcome') 481 | 482 | -------------------------------------------------------------------------------- /modules/output_handler.py: -------------------------------------------------------------------------------- 1 | import os 2 | from reportlab.lib.pagesizes import A4 3 | from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak 4 | from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle 5 | from reportlab.lib.enums import TA_JUSTIFY 6 | import qrcode 7 | from html import escape 8 | 9 | def generate_qr_code(data, output_dir, filename): 10 | """ 11 | Generates a QR code based on provided data and saves it as an image file. 12 | 13 | Args: 14 | data (str): The data to encode in the QR code. 15 | output_dir (str): The directory where the QR code image will be saved. 16 | filename (str): The name of the QR code image file (without extension). 17 | 18 | Returns: 19 | str: The full path to the saved QR code image. 20 | """ 21 | qr = qrcode.QRCode( 22 | version=1, 23 | error_correction=qrcode.constants.ERROR_CORRECT_L, 24 | box_size=10, 25 | border=4 26 | ) 27 | qr.add_data(data) 28 | img = qr.make_image(fill_color="black", back_color="white") 29 | 30 | # Save QR code image as a .jpg file 31 | img_path = os.path.join(output_dir, f"{filename}.jpg") 32 | img.save(img_path) 33 | 34 | # Clear the QR object for reuse 35 | qr.clear() 36 | 37 | return img_path 38 | 39 | nclogo = "assets/Nextcloud_Logo.jpg" # Nextcloud logo 40 | im = Image(nclogo, 150, 106) 41 | 42 | def generate_pdf(user_data, qr_code_path, output_filepath, config_ncUrl, lang, multi_user=False): 43 | """ 44 | Generates a PDF for either a single user or multiple users. 45 | 46 | Args: 47 | user_data (dict): User data, either for a single user or a list of users in multi-user mode. 48 | qr_code_path (str): The path to the QR code image (for single user mode). 49 | output_filepath (str): The output path for the generated PDF. 50 | config_ncUrl (str): The Nextcloud URL. 51 | lang (dict): The dictionary containing translations for output text. 52 | multi_user (bool): Whether to generate a multi-user PDF. 53 | """ 54 | doc = SimpleDocTemplate(output_filepath, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) 55 | 56 | story = [] 57 | styles = getSampleStyleSheet() 58 | styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) 59 | 60 | if multi_user: 61 | for user in user_data['users']: 62 | _build_single_user_section(story, styles, user, user.get('qr_code_path'), config_ncUrl, lang) 63 | story.append(PageBreak()) # Add page break between users 64 | else: 65 | _build_single_user_section(story, styles, user_data, qr_code_path, config_ncUrl, lang) 66 | 67 | doc.build(story) 68 | 69 | def _build_single_user_section(story, styles, user_data, qr_code_path, config_ncUrl, lang): 70 | """ 71 | Helper function to build the PDF content for a single user. 72 | 73 | Args: 74 | story (list): The list of elements that make up the PDF content. 75 | styles (StyleSheet): Styles for formatting the PDF. 76 | user_data (dict): Contains 'username' and 'password' for the user. 77 | qr_code_path (str): Path to the generated QR code image. 78 | config_ncUrl (str): The Nextcloud URL for the user. 79 | lang (dict): The dictionary containing translations for output text. 80 | """ 81 | 82 | # Add Nextcloud logo at the top of the page 83 | story.append(im) 84 | story.append(Spacer(1, 12)) 85 | 86 | # Greeting and account creation message 87 | displayname = user_data.get('displayname', '').strip() # Entferne Leerzeichen 88 | if not displayname: 89 | displayname = user_data['username'] # Fallback auf den Benutzernamen 90 | 91 | # Add greeting 92 | ptext = f"{lang.get('output_handler_greeting', 'Missing translation string for: output_handler_greeting')} {displayname}," 93 | story.append(Paragraph(ptext, styles["Justify"])) 94 | story.append(Spacer(1, 12)) 95 | 96 | # Account creation message 97 | ptext = f"{lang.get('output_handler_account_created', 'Missing translation string for: output_handler_account_created')}" 98 | story.append(Paragraph(ptext, styles["Justify"])) 99 | story.append(Spacer(1, 12)) 100 | 101 | # Login instructions 102 | ptext = f"{lang.get('output_handler_login_instructions', 'Missing translation string for: output_handler_login_instructions')}" 103 | story.append(Paragraph(ptext, styles["Normal"])) 104 | story.append(Spacer(1, 24)) 105 | 106 | # Nextcloud URL 107 | ptext = f"{lang.get('output_handler_nc_url', 'Missing translation string for: output_handler_nc_url')}: {config_ncUrl}" 108 | story.append(Paragraph(ptext, styles["Normal"])) 109 | story.append(Spacer(1, 24)) 110 | 111 | # Username 112 | ptext = f"{lang.get('output_handler_username', 'Missing translation string for: output_handler_username')}:" 113 | story.append(Paragraph(ptext, styles["Normal"])) 114 | story.append(Spacer(1, 12)) 115 | ptext = f"{user_data['username']}" 116 | story.append(Paragraph(ptext, styles["Normal"])) 117 | story.append(Spacer(1, 24)) 118 | 119 | # Password 120 | ptext = f"{lang.get('output_handler_password', 'Missing translation string for: output_handler_password')}:" 121 | story.append(Paragraph(ptext, styles["Normal"])) 122 | story.append(Spacer(1, 12)) 123 | ptext = f"{escape(user_data['password'])}" 124 | story.append(Paragraph(ptext, styles["Normal"])) 125 | story.append(Spacer(1, 24)) 126 | 127 | # QR Code 128 | if qr_code_path and os.path.exists(qr_code_path): 129 | ptext = f"{lang.get('output_handler_qr_code_alternative', 'Missing translation string for: output_handler_qr_code_alternative')}" 130 | story.append(Paragraph(ptext, styles["Normal"])) 131 | story.append(Spacer(1, 24)) 132 | # Insert the QR code image 133 | story.append(Image(qr_code_path, 150, 150)) 134 | 135 | story.append(Spacer(1, 24)) 136 | 137 | def _build_single_user_pdf(story, styles, user_data, qr_code_path, nclogo, config_ncUrl, lang): 138 | """ 139 | Builds the PDF structure for a single user, including the Nextcloud logo. 140 | 141 | Args: 142 | story (list): The list of elements that make up the PDF content. 143 | styles (StyleSheet): Styles for formatting the PDF. 144 | user_data (dict): Contains 'username' and 'password' for the user. 145 | qr_code_path (str): Path to the generated QR code image. 146 | nclogo (str): Path to the Nextcloud logo. 147 | config_ncUrl (str): The Nextcloud URL for the user. 148 | lang (dict): The dictionary containing translations for output text. 149 | """ 150 | _build_single_user_section(story, styles, user_data, qr_code_path, config_ncUrl, lang) 151 | -------------------------------------------------------------------------------- /modules/password.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | class PasswordGenerator: 5 | """ 6 | A class to generate random passwords with a specified length. 7 | 8 | The generated password will always include at least one uppercase letter, 9 | one lowercase letter, one digit, and one special character to ensure complexity. 10 | """ 11 | 12 | def __init__(self, length=8): 13 | """ 14 | Initializes the PasswordGenerator with the desired password length. 15 | 16 | Args: 17 | length (int): The length of the password to be generated. Defaults to 8. 18 | Must be at least 4 to ensure inclusion of all character types. 19 | 20 | Raises: 21 | ValueError: If the provided password length is less than 4. 22 | """ 23 | if length < 4: 24 | raise ValueError("Password length should be at least 4 to include all character types.") 25 | self.length = length 26 | 27 | def generate(self): 28 | """ 29 | Generates a random password with the specified length. 30 | 31 | The password will always contain at least one character from each of the following: 32 | - Uppercase letters 33 | - Lowercase letters 34 | - Digits 35 | - Special characters 36 | 37 | Returns: 38 | str: A randomly generated password. 39 | """ 40 | # Ensure the password contains at least one character from each category 41 | password = [ 42 | random.choice(string.ascii_uppercase), # At least one uppercase letter 43 | random.choice(string.ascii_lowercase), # At least one lowercase letter 44 | random.choice(string.digits), # At least one digit 45 | random.choice(string.punctuation) # At least one special character 46 | ] 47 | 48 | # Pool of all possible characters 49 | all_characters = string.ascii_letters + string.digits + string.punctuation 50 | 51 | # Generate the remaining characters to match the desired password length 52 | password += [random.choice(all_characters) for _ in range(self.length - 4)] 53 | 54 | # Shuffle the list to ensure randomness of the character order 55 | random.shuffle(password) 56 | 57 | # Return the final password as a string 58 | return ''.join(password) 59 | -------------------------------------------------------------------------------- /modules/user_sync.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from lxml import etree 3 | from tabulate import tabulate 4 | from modules.mapping import MAPPING # Import the mapping for special characters 5 | 6 | class NextcloudUserManager: 7 | """ 8 | Manages Nextcloud users by comparing CSV user data with Nextcloud's current user list 9 | and applying changes such as adding, updating, or deleting users. 10 | """ 11 | 12 | # Constructor and Helper Methods 13 | 14 | 15 | def __init__(self, api_instance, lang): 16 | """ 17 | Initialize the class with an instance of NextcloudAPI and language handler. 18 | 19 | Args: 20 | api_instance (NextcloudAPI): An instance of the Nextcloud API handler. 21 | lang (dict): Language dictionary for translation strings. 22 | """ 23 | self.api = api_instance 24 | self.lang = lang 25 | 26 | def apply_mapping(self, text): 27 | """ 28 | Apply the special character and umlaut mapping to a given text. 29 | 30 | Args: 31 | text (str): The text to which the mapping should be applied. 32 | 33 | Returns: 34 | str: The text after applying the character mapping. 35 | """ 36 | return text.translate(MAPPING) 37 | 38 | 39 | # CSV Loading and User Data Preparation 40 | 41 | 42 | def load_csv_users(self, csv_users): 43 | """ 44 | Apply character mapping to the usernames in the given CSV user data and handle empty display names. 45 | 46 | Args: 47 | csv_users (list): A list of dictionaries representing CSV user data. 48 | 49 | Returns: 50 | list: The modified list of CSV user dictionaries with mapped usernames and filled display names. 51 | """ 52 | # Apply mapping to usernames in the CSV and handle empty display names 53 | for user in csv_users: 54 | if not user.get('username'): 55 | logging.error(f"Missing or empty 'username' field for user: {user}") 56 | else: 57 | user['username_mapped'] = self.apply_mapping(user['username']) 58 | 59 | # Fill displayname with username if displayname is empty 60 | if not user.get('displayname'): 61 | logging.info(f"Displayname for user '{user['username']}' is empty. Using username as displayname.") 62 | user['displayname'] = user['username_mapped'] 63 | 64 | return csv_users 65 | 66 | 67 | 68 | # CSV -> Nextcloud User Synchronization 69 | 70 | 71 | def check_for_modified_users(self, csv_users, nextcloud_users): 72 | nextcloud_user_dict = {user['id']: user for user in nextcloud_users} 73 | 74 | for csv_user in csv_users: 75 | username_mapped = csv_user['username_mapped'] 76 | if username_mapped in nextcloud_user_dict: 77 | nextcloud_user = nextcloud_user_dict[username_mapped] 78 | changes = self.detect_changes(csv_user, nextcloud_user) 79 | if changes: 80 | if self.compare_and_display_changes(csv_user, nextcloud_user): 81 | self.apply_changes_to_user(username_mapped, changes) 82 | 83 | def compare_and_sync_users(self, csv_users): 84 | response = self.api.get_users() 85 | if not self.api.is_successful(response): 86 | logging.error("Failed to fetch Nextcloud users.") 87 | return 88 | 89 | nextcloud_users = self.api.parse_users_from_response(response['response']) 90 | 91 | for user in nextcloud_users: 92 | self.fetch_and_populate_user_details(user) 93 | 94 | # Perform comparison and sync operations 95 | self.check_for_deleted_users(csv_users, nextcloud_users) 96 | self.check_for_modified_users(csv_users, nextcloud_users) 97 | 98 | def fetch_and_populate_user_details(self, nextcloud_user): 99 | try: 100 | response = self.api.get_user(nextcloud_user['id']) 101 | if self.api.is_successful(response): 102 | self.populate_user_details(nextcloud_user, response['response']) 103 | else: 104 | logging.error(f"Failed to fetch details for user '{nextcloud_user['id']}'.") 105 | except Exception as e: 106 | logging.error(f"Error fetching details for user '{nextcloud_user['id']}': {e}") 107 | 108 | def populate_user_details(self, nextcloud_user, response): 109 | """ 110 | Populate display name, email, groups, and subadmin groups for a Nextcloud user. 111 | 112 | Args: 113 | nextcloud_user (dict): The user dictionary to be populated. 114 | response (requests.Response): The API response containing user details. 115 | """ 116 | root = etree.fromstring(response.content) 117 | logging.debug(f"Full API response for user {nextcloud_user['id']}: {etree.tostring(root, pretty_print=True).decode('utf-8')}") 118 | 119 | nextcloud_user['displayname'] = self.api.get_xml_value(root, ".//displayname", '') 120 | nextcloud_user['email'] = self.api.get_xml_value(root, ".//email", '') 121 | nextcloud_user['groups'] = self.api.get_user_groups(nextcloud_user['id']) 122 | nextcloud_user['subadmin'] = self.api.get_user_subadmin_groups(nextcloud_user['id']) 123 | 124 | 125 | # Modification Management 126 | 127 | 128 | def detect_changes(self, csv_user, nextcloud_user): 129 | """ 130 | Detect changes between CSV user and Nextcloud user. 131 | 132 | Args: 133 | csv_user (dict): A user from the CSV file. 134 | nextcloud_user (dict): A user from Nextcloud. 135 | 136 | Returns: 137 | dict: A dictionary of changes to be applied, or an empty dictionary if no changes are detected. 138 | """ 139 | changes = {} 140 | 141 | # Email comparison 142 | csv_email = csv_user['email'].strip().lower() 143 | nextcloud_email = nextcloud_user.get('email', '').strip().lower() 144 | if csv_email != nextcloud_email: 145 | changes['email'] = csv_email 146 | 147 | # Displayname comparison and fallback to username if empty 148 | csv_displayname = csv_user['displayname'].strip() 149 | #if not csv_displayname: # If displayname is empty, use the username 150 | # csv_displayname = csv_user['username_mapped'] 151 | nextcloud_displayname = nextcloud_user.get('displayname', '').strip() 152 | if csv_displayname != nextcloud_displayname: 153 | changes['displayname'] = csv_displayname 154 | 155 | # Groups comparison 156 | csv_groups = set(group.strip() for group in csv_user['groups'].split(',') if group.strip()) 157 | nextcloud_groups = set(group.strip() for group in nextcloud_user['groups']) 158 | if csv_groups != nextcloud_groups: 159 | changes['groups'] = csv_groups 160 | 161 | # Subadmin groups comparison 162 | csv_subadmin = set(group.strip() for group in csv_user['subadmin'].split(',') if group.strip()) 163 | nextcloud_subadmin = set(group.strip() for group in nextcloud_user.get('subadmin', [])) 164 | if csv_subadmin != nextcloud_subadmin: 165 | changes['subadmin'] = csv_subadmin 166 | 167 | return changes 168 | 169 | 170 | def compare_and_display_changes(self, csv_user, nextcloud_user): 171 | """ 172 | Display a table comparing the CSV user and the Nextcloud user for potential changes. 173 | 174 | Args: 175 | csv_user (dict): The user data from the CSV file. 176 | nextcloud_user (dict): The user data fetched from Nextcloud. 177 | """ 178 | csv_email = csv_user['email'].strip() if csv_user['email'].strip() else '' 179 | nextcloud_email = nextcloud_user.get('email', '').strip() 180 | 181 | table_data = [ 182 | [self.lang.get('user_sync_field', 'Missing translation string for: user_sync_field'), self.lang.get('user_sync_csv_user', 'Missing translation string for: user_sync_csv_user'), self.lang.get('user_sync_nc_user', 'Missing translation string for: user_sync_nc_user')], 183 | [self.lang.get('user_sync_username', 'Missing translation string for: user_sync_username'), csv_user['username_mapped'], nextcloud_user['id']], 184 | [self.lang.get('user_sync_display_name', 'Missing translation string for: user_sync_display_name'), csv_user['displayname'], nextcloud_user.get('displayname', '')], 185 | [self.lang.get('user_sync_email', 'Missing translation string for: user_sync_email'), csv_email, nextcloud_email], 186 | [self.lang.get('user_sync_groups', 'Missing translation string for: user_sync_groups'), csv_user['groups'], ', '.join(nextcloud_user.get('groups', []))], 187 | [self.lang.get('user_sync_subadmin_groups', 'Missing translation string for: user_sync_subadmin_groups'), csv_user['subadmin'], ', '.join(nextcloud_user.get('subadmin', []))] 188 | ] 189 | 190 | print("") 191 | print(f"{self.lang.get('user_sync_changes_detected', 'Missing translation string for: user_sync_changes_detected')}") 192 | print(tabulate(table_data, headers="firstrow", tablefmt="grid")) 193 | 194 | apply_changes = input(f"{self.lang.get('user_sync_prompt_changes', 'Missing translation string for: user_sync_prompt_changes')}").lower() 195 | return apply_changes == 'y' 196 | 197 | def apply_changes_to_user(self, username, changes): 198 | """ 199 | Apply detected changes to a Nextcloud user. 200 | 201 | Args: 202 | username (str): The username of the user to update. 203 | changes (dict): A dictionary of changes to apply. 204 | """ 205 | for key, value in changes.items(): 206 | if key == 'groups': 207 | self.api.sync_groups(username, value) 208 | elif key == 'subadmin': 209 | self.api.sync_subadmin_groups(username, value) 210 | else: 211 | self.api.edit_user(username, key, value) 212 | 213 | 214 | # User Deletion Management 215 | 216 | 217 | def check_for_deleted_users(self, csv_users, nextcloud_users): 218 | csv_usernames = {user['username_mapped'] for user in csv_users} 219 | nextcloud_usernames = {user['id'] for user in nextcloud_users} 220 | 221 | deleted_users = nextcloud_usernames - csv_usernames 222 | logging.info(f"Deleted users detected: {deleted_users}") 223 | 224 | for username in deleted_users: 225 | # Benutzergruppen und Subadmin-Gruppen könnten bereits vorhanden sein 226 | nextcloud_user = next(user for user in nextcloud_users if user['id'] == username) 227 | 228 | if 'admin' in nextcloud_user['groups']: 229 | logging.info(f"Skipping admin user: '{username}'") 230 | continue 231 | 232 | self.prompt_user_deletion(username) 233 | 234 | def prompt_user_deletion(self, username): 235 | """ 236 | Prompt the user for deletion confirmation and proceed based on user input. 237 | 238 | Args: 239 | username (str): The user ID to potentially delete. 240 | """ 241 | user_details_response = self.api.get_user(username) 242 | if not self.api.is_successful(user_details_response): 243 | logging.error(f"Failed to fetch details for user '{username}'.") 244 | return 245 | 246 | nextcloud_user = { 247 | 'id': username, 248 | 'displayname': self.api.get_xml_value(etree.fromstring(user_details_response['response'].content), ".//displayname", ''), 249 | 'email': self.api.get_xml_value(etree.fromstring(user_details_response['response'].content), ".//email", ''), 250 | 'groups': ', '.join(self.api.get_user_groups(username)), 251 | 'subadmin': ', '.join(self.api.get_user_subadmin_groups(username)), 252 | } 253 | 254 | table_data = [ 255 | ["ID", "Display name", "Email", "Groups", "Group admin for"], 256 | [nextcloud_user['id'], nextcloud_user['displayname'], nextcloud_user['email'], 257 | nextcloud_user['groups'], nextcloud_user['subadmin']] 258 | ] 259 | print("") 260 | print(f"{self.lang.get('user_sync_prompt_delete', 'Missing translation string for: user_sync_prompt_delete')}") 261 | print(tabulate(table_data, headers="firstrow", tablefmt="grid")) 262 | 263 | if input(f"{self.lang.get('user_sync_prompt_deletion', 'Missing translation string for: user_sync_prompt_deletion')}").lower() == 'y': 264 | response = self.api.delete_user(username) 265 | if self.api.is_successful(response): 266 | logging.info(f"{self.lang.get('user_sync_successful_deletion', 'Missing translation string for: user_sync_successful_deletion')}: '{username}'") 267 | else: 268 | logging.error(f"Failed to delete user '{username}'.") -------------------------------------------------------------------------------- /nc-user_manager.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/t-markmann/nc-userimporter/12dc9c679dd8decb0bb4e215cb6ed2509f2ba98f/nc-user_manager.exe -------------------------------------------------------------------------------- /nc-user_manager.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import sys 4 | import html 5 | import logging 6 | from datetime import datetime 7 | from tabulate import tabulate 8 | from modules import ConfigReader, PasswordGenerator, NextcloudAPI, NextcloudUserManager, read_csv, generate_qr_code, generate_pdf, load_language, MAPPING 9 | 10 | # Useful resources for contributors: 11 | # Nextcloud user API https://docs.nextcloud.com/server/latest/admin_manual/configuration_user/instruction_set_for_users.html 12 | # Nextcloud group API https://docs.nextcloud.com/server/latest/admin_manual/configuration_user/instruction_set_for_groups.html 13 | # CURL to Python request converter https://curl.trillworks.com/ 14 | 15 | # Determine if running in a build package (frozen) or from a separate Python script 16 | def get_app_directory(): 17 | if getattr(sys, 'frozen', False): 18 | return os.path.dirname(os.path.abspath(sys.executable)) 19 | else: 20 | return os.path.dirname(os.path.abspath(__file__)) 21 | 22 | appdir = get_app_directory() 23 | 24 | # Set up logging configuration 25 | def setup_logging(log_dir, log_file, config_loglevel): 26 | os.makedirs(log_dir, exist_ok=True) # Ensure the log directory exists 27 | log_file_path = os.path.join(log_dir, log_file) # Combine log directory and log file name 28 | loglevel = getattr(logging, config_loglevel.upper(), logging.INFO) 29 | logging.basicConfig( 30 | level=loglevel, 31 | format='%(asctime)s - %(levelname)s - %(message)s', 32 | handlers=[logging.FileHandler(log_file_path), logging.StreamHandler()] 33 | ) 34 | 35 | # Load configuration settings from config.xml 36 | def load_config(config_reader): 37 | try: 38 | return { 39 | 'base_url': config_reader.get('cloudurl'), 40 | 'admin_name': config_reader.get('adminname'), 41 | 'admin_pass': config_reader.get('adminpass'), 42 | 'pdf_one_file': config_reader.get('pdf_one_file', 'yes'), 43 | 'pdf_single_files': config_reader.get('pdf_single_files', 'yes'), 44 | 'ssl_verify': config_reader.get('sslverify', 'True'), 45 | 'user_language': config_reader.get('language', 'en'), 46 | 'csv_delimiter': config_reader.get('csvdelimiter', ';'), 47 | 'group_delimiter': config_reader.get('csvdelimitergroups', ','), 48 | 'password_length': int(config_reader.get('passwordlength', 12)), 49 | 'generate_password': config_reader.get('generatepassword', 'yes'), 50 | 'csv_file': config_reader.get('csvfile'), 51 | 'log_level': config_reader.get('loglevel') 52 | } 53 | except KeyError as e: 54 | print(f"Critical Error: Missing configuration key: {e}") 55 | sys.exit(1) 56 | 57 | # get path from csv-file 58 | def get_csv_file_path(csv_file_name): 59 | # check if program is frozen 60 | if getattr(sys, 'frozen', False): 61 | # path to executable 62 | base_path = os.path.dirname(sys.executable) 63 | else: 64 | # use Python-Script path 65 | base_path = os.path.dirname(__file__) 66 | 67 | # combine base-path with filename of csv 68 | return os.path.join(base_path, csv_file_name) 69 | 70 | 71 | # Clean up temporary files 72 | def clean_tmp_files(tmp_dir): 73 | if os.path.exists(tmp_dir): 74 | for f in os.listdir(tmp_dir): 75 | os.remove(os.path.join(tmp_dir, f)) 76 | 77 | # Initialize Nextcloud API 78 | def initialize_nc_api(config): 79 | ssl_verify = config['ssl_verify'].lower() == 'true' if isinstance(config['ssl_verify'], str) else config['ssl_verify'] 80 | try: 81 | return NextcloudAPI( 82 | config['base_url'], 83 | config['admin_name'], 84 | config['admin_pass'], 85 | ssl_verify 86 | ) 87 | except KeyError as e: 88 | print(f"Critical Error: Missing configuration key: {e}") 89 | sys.exit(1) 90 | 91 | # Display header information 92 | def display_header(): 93 | print("\n\n###################################################################################") 94 | print("# NEXTCLOUD-USER-MANAGER (IMPORT, UPDATE, DELETE) #") 95 | print("###################################################################################") 96 | print("Copyright (C) 2019-2024 Torsten Markmann (t-markmann), edudocs.org & uplinked.net") 97 | print("Main Contributor: Johannes Schirge (Shen)") 98 | print("Thanks to all Contributors: https://github.com/t-markmann/nc-userimporter/graphs/contributors ") 99 | print("This program comes with ABSOLUTELY NO WARRANTY") 100 | print("This is free software, and you are welcome to redistribute it under certain conditions.") 101 | print("") 102 | 103 | def display_info_create_user_and_groups(): 104 | print("###################################################################################") 105 | print(f" {language.get('nc_userimporter_welcome', 'Missing translation string for: nc_userimporter_welcome')}") 106 | print(f" {language.get('nc_userimporter_process_preview', 'Missing translation string for: nc_userimporter_process_preview')}") 107 | print("###################################################################################") 108 | print("") 109 | 110 | def display_info_synchronize_user(): 111 | print("###################################################################################") 112 | print(f" {language.get('nc_userimporter_welcome_sync', 'Missing translation string for: nc_userimporter_welcome_sync')}") 113 | print(f" {language.get('nc_userimporter_process_preview_sync', 'Missing translation string for: nc_userimporter_process_preview_sync')}") 114 | print("###################################################################################") 115 | print("") 116 | 117 | display_header() 118 | 119 | # Create Users and Groups 120 | def create_users_and_groups(csv_data, config, nc_api): 121 | logging.info("Begin user creation process...") 122 | users_to_process = [] 123 | 124 | for row in csv_data: 125 | try: 126 | username = row['username'] 127 | password = row['password'] 128 | displayname = row['displayname'] if row['displayname'] else username 129 | email = row['email'] 130 | groups = row['groups'].split(config['group_delimiter']) 131 | subadmin = row['subadmin'].split(config['group_delimiter']) if row['subadmin'] else [] 132 | quota = row.get('quota', '1GB') 133 | 134 | if not password and config['generate_password'] == 'yes': 135 | password = PasswordGenerator(config['password_length']) 136 | 137 | logging.info(f"Creating user '{username}' with display name '{displayname}' and email '{email}'") 138 | response = nc_api.add_user(username, password, displayname, email, groups, quota, config['user_language']) 139 | 140 | if response: 141 | logging.info(f"User '{username}' created successfully.") 142 | users_to_process.append({'username': username, 'password': password, 'displayname': displayname}) 143 | 144 | if groups: 145 | nc_api.sync_groups(username, set(groups)) 146 | if subadmin: 147 | nc_api.sync_subadmin_groups(username, set(subadmin)) 148 | else: 149 | logging.error(f"Failed to create user '{username}'") 150 | 151 | except Exception as e: 152 | logging.error(f"Error while processing user '{username}': {str(e)}") 153 | 154 | logging.info("User creation process completed.") 155 | return users_to_process 156 | 157 | # Generate PDF-files 158 | def generate_pdf_files(users_to_process, config, tmp_dir, output_dir): 159 | if not users_to_process: 160 | logging.info("No users to process. PDF generation skipped.") 161 | return 162 | 163 | today = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') 164 | 165 | if config['pdf_single_files'] == 'yes': 166 | for user in users_to_process: 167 | qr_code_path = generate_qr_code(f"nc://login/user:{user['username']}&password:{user['password']}&server:{config['base_url']}", tmp_dir, user['username']) 168 | if qr_code_path: 169 | output_filepath = os.path.join(output_dir, f"{user['username']}_{today}.pdf") 170 | generate_pdf({'username': user['username'], 'password': user['password'], 'displayname': user['displayname']}, qr_code_path, output_filepath, config['base_url'], language) 171 | else: 172 | logging.error(f"Failed to generate QR code for user {user['username']}. PDF generation skipped.") 173 | 174 | if config['pdf_one_file'] == 'yes' or (config['pdf_one_file'] == 'no' and config['pdf_single_files'] == 'no'): 175 | output_filename = f"userlist_{today}.pdf" 176 | output_filepath = os.path.join(output_dir, output_filename) 177 | for user in users_to_process: 178 | user['qr_code_path'] = generate_qr_code(f"nc://login/user:{user['username']}&password:{user['password']}&server:{config['base_url']}", tmp_dir, user['username']) 179 | generate_pdf({'users': users_to_process}, "", output_filepath, config['base_url'], language, multi_user=True) 180 | 181 | # Import new users from CSV 182 | def import_users(config, nc_api): 183 | try: 184 | display_info_create_user_and_groups() 185 | print(f"{language.get('nc_userimporter_press_continue', 'Missing translation string for: nc_userimporter_press_continue')}") 186 | input(f"{language.get('nc_userimporter_any_key', 'Missing translation string for: nc_userimporter_any_key')}") 187 | 188 | output_dir = 'output' 189 | tmp_dir = 'tmp' 190 | os.makedirs(output_dir, exist_ok=True) 191 | os.makedirs(tmp_dir, exist_ok=True) 192 | 193 | # use the function get_csv_file_path() to get the csv-path 194 | csv_file_path = get_csv_file_path(config['csv_file']) 195 | csv_data = read_csv(csv_file_path, config['csv_delimiter']) 196 | 197 | usertable = [["Username", "Display name", "Password", "Email", "Groups", "Group admin for", "Quota"]] 198 | for row in csv_data: 199 | pass_anon = "*" * len(html.escape(row['password'])) if row['password'] else "Not set" 200 | row['username'] = html.escape(row['username']).translate(MAPPING) 201 | quota = html.escape(row['quota']) if row['quota'] is not None else '' 202 | usertable.append([row['username'], row['displayname'], pass_anon, row['email'], row['groups'], row['subadmin'], quota]) 203 | 204 | print(tabulate(usertable, headers="firstrow")) 205 | input(f"{language.get('nc_userimporter_any_key', 'Missing translation string for: nc_userimporter_any_key')}") 206 | 207 | users_to_process = create_users_and_groups(csv_data, config, nc_api) 208 | generate_pdf_files(users_to_process, config, tmp_dir, output_dir) 209 | print(f"\n{language.get('nc_userimporter_user_creation_completed', 'Missing translation string for: nc_userimporter_user_creation_completed')}") 210 | 211 | except KeyboardInterrupt: 212 | print(f"\n{language.get('nc_userimporter_exit_program', 'Missing translation string for: nc_userimporter_exit_program')}") 213 | sys.exit(0) 214 | 215 | finally: 216 | clean_tmp_files(tmp_dir) 217 | 218 | # Synchronize existing users (update and delete) 219 | def synchronize_users(config, user_manager): 220 | display_info_synchronize_user() 221 | print(f"{language.get('nc_userimporter_press_continue_sync', 'Missing translation string for: nc_userimporter_press_continue_sync')}") 222 | input(f"{language.get('nc_userimporter_any_key_sync', 'Missing translation string for: nc_userimporter_any_key_sync')}") 223 | logging.info(f"{language.get('nc_userimporter_sync_start', 'Missing translation string for: nc_userimporter_sync_start')}") 224 | 225 | try: 226 | # Verwende die Funktion get_csv_file_path() anstelle von os.path.dirname(__file__) 227 | csv_file_path = get_csv_file_path(config['csv_file']) 228 | csv_data = read_csv(csv_file_path, config['csv_delimiter']) 229 | mapped_csv_data = user_manager.load_csv_users(csv_data) 230 | user_manager.compare_and_sync_users(mapped_csv_data) 231 | logging.info(f"{language.get('nc_userimporter_sync_completed', 'Missing translation string for: nc_userimporter_sync_completed')}") 232 | except KeyError as e: 233 | print(f"Critical Error: Missing configuration key: {e}") 234 | sys.exit(1) 235 | 236 | 237 | # Main menu 238 | def main_menu(config, nc_api, user_manager): 239 | while True: 240 | print(f"\n{language.get('nc_userimporter_select_option', 'Missing translation string for: nc_userimporter_select_option')}") 241 | print(f"1) {language.get('nc_userimporter_import_option', 'Missing translation string for: nc_userimporter_import_option')}") 242 | print(f"2) {language.get('nc_userimporter_sync_option', 'Missing translation string for: nc_userimporter_sync_option')}") 243 | print(f"3) {language.get('nc_userimporter_exit_option', 'Missing translation string for: nc_userimporter_exit_option')}") 244 | 245 | choice = input(f"{language.get('nc_userimporter_enter_choice', 'Missing translation string for: nc_userimporter_enter_choice')}").strip() 246 | 247 | if choice == '1': 248 | import_users(config, nc_api) 249 | elif choice == '2': 250 | synchronize_users(config, user_manager) 251 | elif choice == '3': 252 | print(f"{language.get('nc_userimporter_exit_program', 'Missing translation string for: nc_userimporter_exit_program')}") 253 | break 254 | else: 255 | print(f"{language.get('nc_userimporter_invalid_choice', 'Missing translation string for: nc_userimporter_invalid_choice')}") 256 | 257 | # Main program execution 258 | if __name__ == "__main__": 259 | try: 260 | config_reader = ConfigReader(os.path.join(appdir, 'config.xml')) 261 | config = load_config(config_reader) 262 | setup_logging('logs', 'output.log', config['log_level']) # logs/output.log will be used now 263 | language = load_language(config_reader) 264 | nc_api = initialize_nc_api(config) 265 | user_manager = NextcloudUserManager(nc_api, language) 266 | main_menu(config, nc_api, user_manager) 267 | except KeyboardInterrupt: 268 | print(f"\n{language.get('nc_userimporter_exit_program', 'Missing translation string for: nc_userimporter_exit_program')}") 269 | sys.exit(0) 270 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4==4.12.3 2 | certifi==2024.8.30 3 | lxml==5.3.0 4 | qrcode==7.4.2 5 | reportlab==4.2.2 6 | Requests==2.32.3 7 | tabulate==0.9.0 -------------------------------------------------------------------------------- /users.csv: -------------------------------------------------------------------------------- 1 | username;displayname;password;email;groups;subadmin;quota 2 | broe;Bob Hilbert;bobpass%word)0001;bobhilbert@example.com;student;100 MB 3 | csmith;Chris Smith;;chrissmith@example.com;teacher;;1 GB 4 | Jhößer;;lkajsdflj98(798kl/asdf;;student;;1GB 5 | Åçì.Œñšú;Åçì Œñšú;lökajs§$%&wnnal28972nna;;;; 6 | adoe;Alice Doe;alicepassword;alicedoe@example.com;Lehrkraefte;subadmin-group;5 GB 7 | --------------------------------------------------------------------------------