diff --git a/LICENSE b/LICENSE
index cefc2d2ab245d76fe75ccfa23d5b6fe3693a83c1..80a61fa12afec5b92cf1e85350854ff9b8df1c9d 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,121 +1,661 @@
- 木兰宽松许可证, 第1版
-
- 木兰宽松许可证, 第1版
- 2019年8月 http://license.coscl.org.cn/MulanPSL
-
- 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第1版(“本许可证”)的如下条款的约束:
-
- 0. 定义
-
- “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。
-
- “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
-
- “法人实体”是指提交贡献的机构及其“关联实体”。
-
- “关联实体”是指,对“本许可证”下的一方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
-
- “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
-
- 1. 授予版权许可
-
- 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
-
- 2. 授予专利许可
-
- 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括仅因您或他人修改“贡献”或其他结合而将必然会侵犯到的专利权利要求。如您或您的“关联实体”直接或间接地(包括通过代理、专利被许可人或受让人),就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
-
- 3. 无商标许可
-
- “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。
-
- 4. 分发限制
-
- 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
-
- 5. 免责声明与责任限制
-
- “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
-
- 条款结束。
-
- 如何将木兰宽松许可证,第1版,应用到您的软件
-
- 如果您希望将木兰宽松许可证,第1版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步:
-
- 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字;
-
- 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中;
-
- 3, 请将如下声明文本放入每个源文件的头部注释中。
-
- Copyright (c) [2019] [name of copyright holder]
- [Software Name] is licensed under the Mulan PSL v1.
- You can use this software according to the terms and conditions of the Mulan PSL v1.
- You may obtain a copy of Mulan PSL v1 at:
- http://license.coscl.org.cn/MulanPSL
- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- PURPOSE.
- See the Mulan PSL v1 for more details.
-
-
- Mulan Permissive Software License,Version 1
-
- Mulan Permissive Software License,Version 1 (Mulan PSL v1)
- August 2019 http://license.coscl.org.cn/MulanPSL
-
- Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v1 (this License) with following terms and conditions:
-
- 0. Definition
-
- Software means the program and related documents which are comprised of those Contribution and licensed under this License.
-
- Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
-
- Legal Entity means the entity making a Contribution and all its Affiliates.
-
- Affiliates means entities that control, or are controlled by, or are under common control with a party to this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
-
- Contribution means the copyrightable work licensed by a particular Contributor under this License.
-
- 1. Grant of Copyright License
-
- Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
-
- 2. Grant of Patent License
-
- Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed, excluding of any patent claims solely be infringed by your or others’ modification or other combinations. If you or your Affiliates directly or indirectly (including through an agent, patent licensee or assignee), institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
-
- 3. No Trademark License
-
- No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4.
-
- 4. Distribution Restriction
-
- You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
-
- 5. Disclaimer of Warranty and Limitation of Liability
-
- The Software and Contribution in it are provided without warranties of any kind, either express or implied. In no event shall any Contributor or copyright holder be liable to you for any damages, including, but not limited to any direct, or indirect, special or consequential damages arising from your use or inability to use the Software or the Contribution in it, no matter how it’s caused or based on which legal theory, even if advised of the possibility of such damages.
-
- End of the Terms and Conditions
-
- How to apply the Mulan Permissive Software License,Version 1 (Mulan PSL v1) to your software
-
- To apply the Mulan PSL v1 to your work, for easy identification by recipients, you are suggested to complete following three steps:
-
- i. Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner;
- ii. Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package;
- iii. Attach the statement to the appropriate annotated syntax at the beginning of each source file.
-
- Copyright (c) [2019] [name of copyright holder]
- [Software Name] is licensed under the Mulan PSL v1.
- You can use this software according to the terms and conditions of the Mulan PSL v1.
- You may obtain a copy of Mulan PSL v1 at:
- http://license.coscl.org.cn/MulanPSL
- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- PURPOSE.
-
- See the Mulan PSL v1 for more details.
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/README.md b/README.md
index 950f06271790a6f81379f5e4788af0d158b0313c..795e099fef446364f5c883032fa130defa5c718f 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,8 @@
## 介绍
1. 在Odoo中封装了相关企业微信API,便于开发者在Odoo中直接调用。
-2. 集成了通讯录同步、自建应用等功能。
-3. 企业微信专用的 `widget`
+2. 集成了通讯录同步、企业微信免登以及扫码登录等功能。
+
## 软件架构
软件架构说明
@@ -19,6 +19,7 @@
1. 注意注册 企业Id 应用id 和密钥
2. 注意设定企业微信资源存储路径用于存储企微资源的路径,需要对路径具有读写权限
3. 在获取JSAPI临时凭证可以先尝试手动获取确认一切正常在进行后续.
+4. 必须绑定通讯录以及自建应用,自建应用必须能读取通讯录信息
#### 参与贡献
diff --git a/wecom_api/api/wecom_server_api.py b/wecom_api/api/wecom_server_api.py
index d4bcb87cd5e75920aa73b1110cc488a830cfd3af..7ac6f72d005cdcbccc619055fd262f1fbc3c23d3 100644
--- a/wecom_api/api/wecom_server_api.py
+++ b/wecom_api/api/wecom_server_api.py
@@ -3,8 +3,10 @@
import json
import requests
from datetime import datetime, timedelta
+from odoo import api, fields, models, tools, _
from odoo import api, fields, models, SUPERUSER_ID, _
+
# from .wecom_abstract_api import ApiException
@@ -29,31 +31,16 @@ class WecomServerApi(models.TransientModel):
:param secret : 应用密钥
:returns 模型"wecom.service_api"对象
"""
- api = self.search(
- [
- ("corpid", "=", corpid),
- ("secret", "=", secret),
- ],
- limit=1,
- )
+ api = self.search([("corpid", "=", corpid), ("secret", "=", secret), ], limit=1)
if not api:
# 创建API令牌记录
- api = self.sudo().create(
- {
- "corpid": corpid,
- "secret": secret,
- }
- )
+ api = self.sudo().create({"corpid": corpid, "secret": secret, })
if api["access_token"] is False or api["access_token"] == "":
# token为空,刷新API令牌记录
api.refreshAccessToken()
- if (
- api["token_expiration_time"] is False
- or api["token_expiration_time"] < datetime.now()
- ):
+ if api["token_expiration_time"] is False or api["token_expiration_time"] < datetime.now():
# token过期,刷新API令牌记录
api.refreshAccessToken()
-
return api
def getAccessToken(self):
@@ -69,10 +56,8 @@ class WecomServerApi(models.TransientModel):
刷新模型 'wecom.service_api' 的令牌
同时刷新发起请求的模型 'wecom.apps' 的令牌
"""
- response = self.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call("GET_ACCESS_TOKEN"),
- {"corpid": self.corpid, "corpsecret": self.secret},
- )
+ response = self.httpCall(self.env["wecom.service_api_list"].get_server_api_call("GET_ACCESS_TOKEN"),
+ {"corpid": self.corpid, "corpsecret": self.secret}, )
expiration_second = timedelta(seconds=response["expires_in"])
dict = {
@@ -86,9 +71,8 @@ class WecomServerApi(models.TransientModel):
compay_id = self.env["res.company"].search(
[("corpid", "=", self.corpid)], limit=1
)
- app_id = self.env["wecom.apps"].search(
- [("company_id", "=", compay_id.id), ("secret", "=", self.secret)], limit=1
- )
+ app_id = self.env["wecom.apps"].search([("company_id", "=", compay_id.id), ("secret", "=", self.secret)],
+ limit=1)
app_id.sudo().write(dict)
diff --git a/wecom_api/models/wecom_server_api_list.py b/wecom_api/models/wecom_server_api_list.py
index 641f1388b163da0bcf699e45dc5ddb403ffe0946..08c7c39c1adfd42bb0229a04dce1f9cc0c23857e 100644
--- a/wecom_api/models/wecom_server_api_list.py
+++ b/wecom_api/models/wecom_server_api_list.py
@@ -11,37 +11,37 @@ class WecomServerApiList(models.Model):
type = fields.Selection(
[
- ("1", "Base"), # 基础
- ("2", "Contacts"), # 通讯录,
- ("3", "Customer contact"), # 客户联系
- ("4", "Wechat customer service"), # 微信客服
- ("5", "Identity authentication"), # 身份验证
- ("6", "Application management"), # 应用管理
- ("7", "Message push"), # 消息推送
- ("8", "Media material"), # 媒体素材
- ("9", "OA"), # OA
- ("10", "Efficiency tools"), # 效率工具
- ("11", "externalpay"), # 企业支付
- ("12", "Corp Group"), # 企业互联
- ("13", "Corp Chain"), # 企业链,上下游
- ("14", "Session content archiving"), # 会话内容存档
- ("15", "Electronic invoice"), # 电子发票
- ("16", "School"), # 家校沟通
- ("17", "School Apps"), # 家校应用
+ ("1", "Base"), # 基础
+ ("2", "Contacts"), # 通讯录,
+ ("3", "Customer contact"), # 客户联系
+ ("4", "Wechat customer service"), # 微信客服
+ ("5", "Identity authentication"), # 身份验证
+ ("6", "Application management"), # 应用管理
+ ("7", "Message push"), # 消息推送
+ ("8", "Media material"), # 媒体素材
+ ("9", "OA"), # OA
+ ("10", "Efficiency tools"), # 效率工具
+ ("11", "externalpay"), # 企业支付
+ ("12", "Corp Group"), # 企业互联
+ ("13", "Corp Chain"), # 企业链,上下游
+ ("14", "Session content archiving"), # 会话内容存档
+ ("15", "Electronic invoice"), # 电子发票
+ ("16", "School"), # 家校沟通
+ ("17", "School Apps"), # 家校应用
("18", "Report"), # 政民沟通
],
string="Api Type",
required=True,
default="GET",
- )
+ )
- name = fields.Char("Request Name", required=True,)
- function_name = fields.Char("Request Function Name", required=True, readonly=True,)
+ name = fields.Char("Request Name", required=True, )
+ function_name = fields.Char("Request Function Name", required=True, readonly=True, )
- short_url = fields.Char("Request Short Url", required=True,)
+ short_url = fields.Char("Request Short Url", required=True, )
request_type = fields.Selection(
- [("GET", "GET"), ("POST", "POST"),],
+ [("GET", "GET"), ("POST", "POST"), ],
string="Api Request Type",
required=True,
default="GET",
@@ -53,7 +53,7 @@ class WecomServerApiList(models.Model):
("function_name_uniq", "unique (function_name)", "The function is unique !",),
]
- def get_server_api_call(self, function_name):
+ def get_server_api_call(self, function_name, debug=False):
"""
根据函数名称获取 企业微信API的路由和请求方式
:param function_name : 函数名称
@@ -61,7 +61,10 @@ class WecomServerApiList(models.Model):
"""
# ['/cgi-bin/gettoken', 'GET']
data = []
- res = self.search([("function_name", "=", function_name)], limit=1,)
- data.append(res.short_url)
+ res = self.search([("function_name", "=", function_name)], limit=1, )
+ if debug:
+ data.append('%s&debug=%s' % (res.short_url, 1))
+ else:
+ data.append(res.short_url)
data.append(res.request_type)
return data
diff --git a/wecom_auth_oauth/controllers/main.py b/wecom_auth_oauth/controllers/main.py
index b84dc2751aea0c597b7aebf876aa9b92b58cffcf..c6a3489411aef11d4e08e6fa317a90a92d0ef91a 100644
--- a/wecom_auth_oauth/controllers/main.py
+++ b/wecom_auth_oauth/controllers/main.py
@@ -41,20 +41,20 @@ class OAuthLogin(Home):
try:
providers = (
request.env["auth.oauth.provider"]
- .sudo()
- .search_read([("enabled", "=", True)])
+ .sudo()
+ .search_read([("enabled", "=", True)])
)
except Exception:
providers = []
# 构造企业微信一键登录(应用内免登录)和扫码登录链接
for provider in providers:
if (
- "https://open.weixin.qq.com/connect/oauth2/authorize"
- in provider["auth_endpoint"]
+ "https://open.weixin.qq.com/connect/oauth2/authorize"
+ in provider["auth_endpoint"]
):
# 一键登录
return_url = (
- request.httprequest.url_root + "wxowrk_auth_oauth/authorize"
+ request.httprequest.url_root + "wxowrk_auth_oauth/authorize"
)
state = self.get_state(provider)
@@ -72,8 +72,8 @@ class OAuthLogin(Home):
"#wechat_redirect",
)
elif (
- "https://open.work.weixin.qq.com/wwopen/sso/qrConnect"
- in provider["auth_endpoint"]
+ "https://open.work.weixin.qq.com/wwopen/sso/qrConnect"
+ in provider["auth_endpoint"]
):
# 扫描登录
return_url = request.httprequest.url_root + "wxowrk_auth_oauth/qr"
@@ -117,27 +117,25 @@ class OAuthController(http.Controller):
state = json.loads(kw["state"])
company = (
request.env["res.company"]
- .sudo()
- .search(
- [("corpid", "=", state["a"]), ("is_wecom_organization", "=", True),],
+ .sudo()
+ .search(
+ [("corpid", "=", state["a"]), ("is_wecom_organization", "=", True), ],
)
)
try:
wxapi = (
request.env["wecom.service_api"]
- .sudo()
- .InitServiceApi(company.corpid, company.sudo().auth_app_id.secret)
+ .sudo()
+ .InitServiceApi(company.corpid, company.sudo().auth_app_id.secret)
)
# 根据code获取成员信息
response = wxapi.httpCall(
- request.env["wecom.service_api_list"]
- .sudo()
- .get_server_api_call("GET_USER_INFO_BY_CODE"),
- {"code": code,},
- )
-
+ request.env["wecom.service_api_list"].sudo().get_server_api_call("GET_USER_INFO_BY_CODE"),
+ {"code": code, },
+ )
+ _logger.info('根据code获取成员信息,返回报文:%s' % response)
dbname = state["d"]
if not http.db_filter([dbname]):
return BadRequest()
@@ -147,6 +145,7 @@ class OAuthController(http.Controller):
with registry.cursor() as cr:
try:
env = api.Environment(cr, SUPERUSER_ID, context)
+ _logger.info('根据code获取成员信息,返回报文:%s' % response)
db, login, key = env['res.users'].sudo().wecom_auth_oauth(provider, response)
cr.commit()
action = state.get("a")
@@ -171,7 +170,7 @@ class OAuthController(http.Controller):
# Since /web is hardcoded, verify user has right to land on it
if werkzeug.urls.url_parse(
- resp.location
+ resp.location
).path == "/web" and not request.env.user.has_group(
"base.group_user"
):
@@ -213,25 +212,25 @@ class OAuthController(http.Controller):
code = kw.pop("code", None)
company = (
request.env["res.company"]
- .sudo()
- .search(
- [("corpid", "=", kw["appid"]), ("is_wecom_organization", "=", True),],
+ .sudo()
+ .search(
+ [("corpid", "=", kw["appid"]), ("is_wecom_organization", "=", True), ],
)
)
try:
wxapi = (
request.env["wecom.service_api"]
- .sudo()
- .InitServiceApi(company.corpid, company.sudo().auth_app_id.secret)
+ .sudo()
+ .InitServiceApi(company.corpid, company.sudo().auth_app_id.secret)
)
response = wxapi.httpCall(
request.env["wecom.service_api_list"]
- .sudo()
- .get_server_api_call("GET_USER_INFO_BY_CODE"),
- {"code": code,},
+ .sudo()
+ .get_server_api_call("GET_USER_INFO_BY_CODE"),
+ {"code": code, },
)
-
+
state = json.loads(kw["state"].replace("M", '"'))
dbname = state["d"]
if not http.db_filter([dbname]):
@@ -265,7 +264,7 @@ class OAuthController(http.Controller):
resp.autocorrect_location_header = False
if werkzeug.urls.url_parse(
- resp.location
+ resp.location
).path == "/web" and not request.env.user.has_group(
"base.group_user"
):
diff --git a/wecom_auth_oauth/models/res_users.py b/wecom_auth_oauth/models/res_users.py
index 362c428ed463a2f8504dfbe7f6f15d5d6346b9c4..fa6b40674d6245b64b4cd9101820b4d9cf72875b 100644
--- a/wecom_auth_oauth/models/res_users.py
+++ b/wecom_auth_oauth/models/res_users.py
@@ -1,8 +1,11 @@
# -*- coding: utf-8 -*-
+import logging
from odoo import models, api, _
from odoo.exceptions import AccessDenied
+_logger = logging.getLogger(__name__)
+
class ResUsers(models.Model):
_inherit = "res.users"
@@ -21,32 +24,30 @@ class ResUsers(models.Model):
wecom_web_auth_endpoint = "https://open.weixin.qq.com/connect/oauth2/authorize"
wecom_qr_auth_endpoint = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect"
- wecom_providers = (
- self.env["auth.oauth.provider"].sudo().search([("id", "=", provider),])
- )
+ wecom_providers = self.env["auth.oauth.provider"].sudo().search([("id", "=", provider), ])
- if (
- wecom_web_auth_endpoint in wecom_providers["auth_endpoint"]
- or wecom_qr_auth_endpoint in wecom_providers["auth_endpoint"]
+ if (wecom_web_auth_endpoint in wecom_providers["auth_endpoint"]
+ or wecom_qr_auth_endpoint in wecom_providers["auth_endpoint"]
):
# 扫码登录
- oauth_userid = params["UserId"].lower()
- oauth_user = self.search(
- [
- # ("oauth_uid", "=", oauth_userid),
- ("wecom_userid", "=", oauth_userid),
- ("is_wecom_user", "=", True),
- ("active", "=", True),
- ]
- )
-
- if not oauth_user or len(oauth_user) > 1:
+ oauth_userid = params["UserId"]
+ oauth_user = self.search([("wecom_userid", "=", oauth_userid),
+ ("is_wecom_user", "=", True),
+ ("active", "=", True),
+ # ("oauth_uid", "=", oauth_userid),
+ ])
+
+ # if not oauth_user:
+ # return AccessDenied
+ # elif len(oauth_user) > 1:
+ # return AccessDenied
+ if oauth_user and len(oauth_user) == 1:
+ return (self.env.cr.dbname, oauth_user.login, oauth_userid)
+ else:
return AccessDenied
- return (self.env.cr.dbname, oauth_user.login, oauth_userid)
else:
return AccessDenied
-
def _check_credentials(self, password, env):
# password为企业微信的用户ID
try:
diff --git a/wecom_base/models/wecom_app_event_type.py b/wecom_base/models/wecom_app_event_type.py
index 50297750edf4150e80a75b52acdd27743ad760f5..f0bcef81c54ce3445496fb1439da0fcb797d2537 100644
--- a/wecom_base/models/wecom_app_event_type.py
+++ b/wecom_base/models/wecom_app_event_type.py
@@ -16,7 +16,6 @@ _logger = logging.getLogger(__name__)
class WeComAppEventType(models.Model):
-
_name = "wecom.app.event_type"
_description = "Wecom Application Event"
_order = "id"
@@ -32,14 +31,14 @@ class WeComAppEventType(models.Model):
# - UserError: Warning Exception to use with raise
# To return an action, assign: action = {...}\n\n\n\n"""
- name = fields.Char(string="Name", translate=True, copy=False, required=True,)
- model_ids = fields.Many2many("ir.model", string="Related Model",)
+ name = fields.Char(string="Name", translate=True, copy=False, required=True, )
+ model_ids = fields.Many2many("ir.model", string="Related Model", )
msg_type = fields.Char(
string="Message Type", copy=False, required=True, default="event"
)
- event = fields.Char(string="Event Code", copy=False, required=True,)
+ event = fields.Char(string="Event Code", copy=False, required=True, )
change_type = fields.Char(string="Change Type", copy=False)
- code = fields.Char(string="Python Code", default="",)
+ code = fields.Char(string="Python Code", default="", )
command = fields.Char(string="Command", copy=False)
def handle_event(self):
@@ -57,11 +56,8 @@ class WeComAppEventType(models.Model):
)
% (event_str, changetype_str,)
)
- event = (
- self.env["wecom.app.event_type"]
- .sudo()
- .search([("event", "=", event_str), ("change_type", "=", changetype_str),])
- )
+ event = self.env["wecom.app.event_type"].sudo().search([("event", "=", event_str),
+ ("change_type", "=", changetype_str), ])
if not event:
_logger.warning(
_(
@@ -76,9 +72,7 @@ class WeComAppEventType(models.Model):
# ^ ·企业微信服务器在五秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次
# ^ ·当接收成功后,http头部返回200表示接收ok,其他错误码企业微信后台会一律当做失败并发起重试
try:
- event.with_context(
- xml_tree=xml_tree, company_id=company_id
- ).sudo().run()
+ event.with_context(xml_tree=xml_tree, company_id=company_id).sudo().run()
except Exception as e:
_logger.warning(
_(
diff --git a/wecom_base/models/wecom_apps.py b/wecom_base/models/wecom_apps.py
index 913c97c19e619f61cd640be449b87ceed79142e7..9d6d8f1887b97818120aedef562b5c926acb49b8 100644
--- a/wecom_base/models/wecom_apps.py
+++ b/wecom_base/models/wecom_apps.py
@@ -136,7 +136,7 @@ class WeComApps(models.Model):
string="Visible range (Department)", copy=False
) # 企业应用可见范围(部门)
allow_tags = fields.Char(string="Visible range (Tag))", copy=False) # 企业应用可见范围(标签)
- close = fields.Boolean(string="Disabled", copy=False) # 企业应用是否被停用
+ close = fields.Boolean(string="Disabled", copy=False) # 企业应用是否被停用
redirect_domain = fields.Char(string="Trusted domain name", copy=True) # 企业应用可信域名
report_location_flag = fields.Boolean(
string="Open the geographic location and report", copy=False
@@ -397,8 +397,8 @@ class WeComApps(models.Model):
)
try:
if (
- self.jsapi_ticket_expiration_time
- and self.jsapi_ticket_expiration_time > datetime.now()
+ self.jsapi_ticket_expiration_time
+ and self.jsapi_ticket_expiration_time > datetime.now()
):
# 未过期,
# print("未过期")
@@ -420,16 +420,25 @@ class WeComApps(models.Model):
{"type": "agent_config"},
)
except ApiException as ex:
+ msg = {
+ "title": _("Tips"),
+ "message": _("Not Successfully obtained application ticket,Error info :%s!" % ex),
+ "sticky": False,
+ "next": {
+ "type": "ir.actions.client",
+ "tag": "reload",
+ }}
return self.env["wecomapi.tools.action"].ApiExceptionDialog(
ex, raise_exception=True
)
+
else:
if response["errcode"] == 0:
self.write(
{
"jsapi_ticket": response["ticket"],
"jsapi_ticket_expiration_time": datetime.now()
- + timedelta(seconds=response["expires_in"]),
+ + timedelta(seconds=response["expires_in"]),
}
)
msg = {
diff --git a/wecom_contacts/models/res_company.py b/wecom_contacts/models/res_company.py
index 267c6b734e940a694e92c36ea6e9aad9975e577f..eeb13f90eeb4b22b1d06e1fba9441f8eeb29e03f 100644
--- a/wecom_contacts/models/res_company.py
+++ b/wecom_contacts/models/res_company.py
@@ -51,53 +51,35 @@ class Company(models.Model):
"""
定时任务,每隔两小时更新企业的jsapi_ticket
"""
- for company in self:
- if (
- company.is_wecom_organization
- and company.corpid
- and company.contacts_app_id
- ):
+ company_ids = self.search([('is_wecom_organization', '=', True)])
+ for company in company_ids:
+ if company.is_wecom_organization and company.corpid and company.contacts_app_id:
+ _logger.info(_("Automatic tasks:Start getting JSAPI ticket for company [%s]") % (company.name))
+ if company.wecom_jsapi_ticket_expiration_time and company.wecom_jsapi_ticket_expiration_time > datetime.now():
_logger.info(
- _("Automatic tasks:Start getting JSAPI ticket for company [%s]")
- % (company.name)
+ _("The company [%s] ticket is still valid and does not need to be updated!") % (company.name)
)
- if (
- company.wecom_jsapi_ticket_expiration_time
- and company.wecom_jsapi_ticket_expiration_time > datetime.now()
- ):
+ else:
+ try:
+ wecom_api = self.env["wecom.service_api"].InitServiceApi(company.corpid,
+ company.contacts_app_id.secret)
+ response = wecom_api.httpCall(
+ self.env["wecom.service_api_list"].get_server_api_call("GET_JSAPI_TICKET"
+ ),
+ {},
+ )
+ except ApiException as ex:
+ _logger.error(
+ _("Error in obtaining company [%s] ticket, reason: %s")
+ % (company.name, ex)
+ )
+ else:
+ if response["errcode"] == 0:
+ wecom_jsapi_ticket_expiration_time = datetime.now() + timedelta(seconds=response["expires_in"])
+ company.write({"wecom_jsapi_ticket": response["ticket"],
+ "wecom_jsapi_ticket_expiration_time": wecom_jsapi_ticket_expiration_time, })
+ finally:
_logger.info(
- _(
- "The company [%s] ticket is still valid and does not need to be updated!"
- )
+ _("Automatic tasks:End of company [%s] JSAPI ticket update")
% (company.name)
)
- else:
- try:
- wecom_api = self.env["wecom.service_api"].InitServiceApi(
- self.company_id.corpid, self.contacts_app_id.secret
- )
- response = wecom_api.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call(
- "GET_JSAPI_TICKET"
- ),
- {},
- )
- except ApiException as ex:
- _logger.error(
- _("Error in obtaining company [%s] ticket, reason: %s")
- % (company.name, ex)
- )
- else:
- if response["errcode"] == 0:
- company.write(
- {
- "wecom_jsapi_ticket": response["ticket"],
- "wecom_jsapi_ticket_expiration_time": datetime.now()
- + timedelta(seconds=response["expires_in"]),
- }
- )
- finally:
- _logger.info(
- _("Automatic tasks:End of company [%s] JSAPI ticket update")
- % (company.name)
- )
diff --git a/wecom_contacts/models/res_config_settings.py b/wecom_contacts/models/res_config_settings.py
index 1960b8d76d38cb8fb99ddcf086ac7f14de2260e4..187a8999545e99cb1107a7e9e86d1412f853879c 100644
--- a/wecom_contacts/models/res_config_settings.py
+++ b/wecom_contacts/models/res_config_settings.py
@@ -158,7 +158,10 @@ class ResConfigSettings(models.TransientModel):
raise ValidationError(
_("Please enable the function of join enterprise QR code!")
)
-
+ if not self.company_id.corpid or not self.contacts_app_id.secret:
+ raise ValidationError(
+ _("Please enable corpid or secret!")
+ )
if debug:
_logger.info(
_("Start getting join enterprise QR code of company [%s]")
@@ -222,6 +225,8 @@ class ResConfigSettings(models.TransientModel):
if debug:
_logger.info(_("Start to get enterprise wechat API domain name IP segment"))
try:
+ if not self.contacts_app_id.secret:
+ raise ValidationError(_("Please bind contact app secret"))
wecomapi = self.env["wecom.service_api"].InitServiceApi(
self.company_id.corpid, self.contacts_app_id.secret
)
diff --git a/wecom_contacts/models/res_partner_category.py b/wecom_contacts/models/res_partner_category.py
index d0407818f4bcbebdd4efc70168b6752f6f050b24..8875204a985c588e9bae700e5c6794c276867fbc 100644
--- a/wecom_contacts/models/res_partner_category.py
+++ b/wecom_contacts/models/res_partner_category.py
@@ -198,7 +198,7 @@ class PartnerCategory(models.Model):
.sudo()
.search(
[
- ("wecom_userid", "=", user["userid"].lower()),
+ ("wecom_userid", "=", user["userid"]),
("company_id", "=", company.id),
("is_wecom_user", "=", True),
"|",
diff --git a/wecom_contacts_sync/i18n/zh_CN.po b/wecom_contacts_sync/i18n/zh_CN.po
index 18157dc07922479c8ebe37e1599d73c6e45584b9..3225c160d86fb66ca0a7583df377e15b8a9310d7 100644
--- a/wecom_contacts_sync/i18n/zh_CN.po
+++ b/wecom_contacts_sync/i18n/zh_CN.po
@@ -1233,7 +1233,7 @@ msgstr "个人二维码"
#. module: wecom_contacts_sync
#: code:addons/wecom_contacts_sync/models/res_config_settings.py:0
#, python-format
-msgid "Please bind contact app!"
+msgid "c!"
msgstr "请绑定通讯录应用!"
#. module: wecom_contacts_sync
diff --git a/wecom_contacts_sync/models/hr_employee_category.py b/wecom_contacts_sync/models/hr_employee_category.py
index 2d36ee48dd3970376bae05a77eb67d3c601e0fb4..7f40c702834d41595af3762729b332ab15976913 100644
--- a/wecom_contacts_sync/models/hr_employee_category.py
+++ b/wecom_contacts_sync/models/hr_employee_category.py
@@ -207,8 +207,8 @@ class EmployeeCategory(models.Model):
del_tag_members.update({"tagid": tagid})
if (
- len(add_tag_members["userlist"]) > 0
- or len(add_tag_members["partylist"]) > 0
+ len(add_tag_members["userlist"]) > 0
+ or len(add_tag_members["partylist"]) > 0
):
# 添加远程标签成员
response = wxapi.httpCall(
@@ -218,8 +218,8 @@ class EmployeeCategory(models.Model):
add_tag_members,
)
if (
- len(del_tag_members["userlist"]) > 0
- or len(del_tag_members["partylist"]) > 0
+ len(del_tag_members["userlist"]) > 0
+ or len(del_tag_members["partylist"]) > 0
):
# 删除远程标签尘缘
response = wxapi.httpCall(
@@ -234,7 +234,7 @@ class EmployeeCategory(models.Model):
{
"title": _("Fail"),
"message": _("API error: %s, error name: %s, error message: %s")
- % (str(ex.errCode), error["name"], ex.errMsg),
+ % (str(ex.errCode), error["name"], ex.errMsg),
"type": "warning",
"sticky": True,
"className": "bg-warning",
@@ -283,7 +283,7 @@ class EmployeeCategory(models.Model):
remote_partylist = []
if response["errcode"] == 0:
for user in response["userlist"]:
- remote_userlist.append(user["userid"].lower())
+ remote_userlist.append(user["userid"])
for party in response["partylist"]:
remote_partylist.append(party)
@@ -341,7 +341,7 @@ class EmployeeCategory(models.Model):
{
"title": _("Fail"),
"message": _("API error: %s, error name: %s, error message: %s")
- % (str(ex.errCode), error["name"], ex.errMsg),
+ % (str(ex.errCode), error["name"], ex.errMsg),
"type": "warning",
"sticky": True,
"className": "bg-warning",
@@ -478,7 +478,7 @@ class EmployeeCategory(models.Model):
"msg": _(
"Failed to download tag [%s] member of company [%s]!"
)
- % (tag["tagname"], company.name),
+ % (tag["tagname"], company.name),
}
)
finally:
@@ -538,10 +538,10 @@ class EmployeeCategory(models.Model):
for user in response["userlist"]:
employee = (
self.env["hr.employee"]
- .sudo()
- .search(
+ .sudo()
+ .search(
[
- ("wecom_userid", "=", user["userid"].lower()),
+ ("wecom_userid", "=", user["userid"]),
("company_id", "=", company.id),
("is_wecom_user", "=", True),
"|",
@@ -560,8 +560,8 @@ class EmployeeCategory(models.Model):
for party in response["partylist"]:
department = (
self.env["hr.department"]
- .sudo()
- .search(
+ .sudo()
+ .search(
[
("wecom_department_id", "=", party),
("is_wecom_department", "=", True),
@@ -677,25 +677,25 @@ class EmployeeCategory(models.Model):
]
employee = (
self.env["hr.employee"]
- .sudo()
- .search([("company_id", "=", company_id.id)] + domain)
+ .sudo()
+ .search([("company_id", "=", company_id.id)] + domain)
)
department = (
self.env["hr.department"]
- .sudo()
- .search([("company_id", "=", company_id.id)] + domain)
+ .sudo()
+ .search([("company_id", "=", company_id.id)] + domain)
)
update_dict = {}
for key, value in dic.items():
if (
- key == "ToUserName"
- or key == "FromUserName"
- or key == "CreateTime"
- or key == "Event"
- or key == "MsgType"
- or key == "ChangeType"
+ key == "ToUserName"
+ or key == "FromUserName"
+ or key == "CreateTime"
+ or key == "Event"
+ or key == "MsgType"
+ or key == "ChangeType"
):
# 忽略掉 不需要的key
pass
@@ -721,33 +721,19 @@ class EmployeeCategory(models.Model):
if "add_employee_ids" in update_dict.keys():
for wecom_userid in update_dict["add_employee_ids"].split(","):
add_employee_list.append(
- employee.search(
- [("wecom_userid", "=", wecom_userid.lower())], limit=1
- ).id
+ employee.search([("wecom_userid", "=", wecom_userid)], limit=1).id
)
elif "del_employee_ids" in update_dict.keys():
for wecom_userid in update_dict["del_employee_ids"].split(","):
- del_employee_list.append(
- employee.search(
- [("wecom_userid", "=", wecom_userid.lower())], limit=1
- ).id
- )
+ del_employee_list.append(employee.search([("wecom_userid", "=", wecom_userid.lower())], limit=1).id)
elif "add_department_ids" in update_dict.keys():
for wecom_department_id in update_dict["add_department_ids"].split(","):
add_department_list.append(
- department.search(
- [("wecom_department_id", "=", wecom_department_id)],
- limit=1,
- ).id
- )
+ department.search([("wecom_department_id", "=", wecom_department_id)], limit=1).id)
elif "del_department_ids" in update_dict.keys():
for wecom_department_id in update_dict["del_department_ids"].split(","):
del_department_list.append(
- department.search(
- [("wecom_department_id", "=", wecom_department_id)],
- limit=1,
- ).id
- )
+ department.search([("wecom_department_id", "=", wecom_department_id)], limit=1, ).id)
# print(
# add_employee_list,
diff --git a/wecom_contacts_sync/models/res_users.py b/wecom_contacts_sync/models/res_users.py
index 620bf7a0b421299e2ff8e54b6f21e27c9de51cd7..5a0e8fb34b971b4d90e26305ab8149bd158856f6 100644
--- a/wecom_contacts_sync/models/res_users.py
+++ b/wecom_contacts_sync/models/res_users.py
@@ -100,9 +100,9 @@ class User(models.Model):
"employee_ids": [(6, 0, [object.id])],
"employee_id": object.id,
"lang": self.env.lang,
- "company_id": object.company_id.id,
+ # "company_id": object.company_id.id,
# 以下为企业微信字段
- "wecom_userid": object.wecom_userid.lower(),
+ "wecom_userid": object.wecom_userid,
"wecom_openid": object.wecom_openid,
"is_wecom_user": object.is_wecom_user,
"qr_code": object.qr_code,
@@ -295,7 +295,7 @@ class User(models.Model):
"""
user = self.sudo().search(
[
- ("wecom_userid", "=", wecom_user["userid"].lower()),
+ ("wecom_userid", "=", wecom_user["userid"]),
("company_id", "=", company.id),
("is_wecom_user", "=", True),
"|",
@@ -354,7 +354,7 @@ class User(models.Model):
"company_ids": [Command.link(user.company_id.id)],
"company_id": user.company_id.id,
"name": wecom_user["name"],
- "login": wecom_user["userid"].lower(), # 登陆账号 使用 企业微信用户id的小写
+ "login": wecom_user["userid"], # 登陆账号 使用 企业微信用户id的小写
"password": self.env["wecomapi.tools.security"].random_passwd(8),
"email": wecom_user["email"],
"work_phone": wecom_user["telephone"],
@@ -364,7 +364,7 @@ class User(models.Model):
"gender": self.env["wecomapi.tools.convert"].sex2gender(
wecom_user["gender"]
),
- "wecom_userid": wecom_user["userid"].lower(),
+ "wecom_userid": wecom_user["userid"],
"image_1920": self.env["wecomapi.tools.file"].get_avatar_base64(
contacts_use_default_avatar,
wecom_user["gender"],
@@ -383,7 +383,7 @@ class User(models.Model):
except Exception as e:
result = _("Error creating company %s partner %s %s, error reason: %s") % (
company.name,
- wecom_user["userid"].lower(),
+ wecom_user["userid"],
wecom_user["name"],
repr(e),
)
@@ -413,7 +413,7 @@ class User(models.Model):
{
"notification_type": "inbox",
"name": wecom_user["name"],
- "login": wecom_user["userid"].lower(), # 登陆账号 使用 企业微信用户id的小写
+ "login": wecom_user["userid"], # 登陆账号 使用 企业微信用户id的小写
"email": wecom_user["email"],
"work_phone": wecom_user["telephone"],
"mobile_phone": wecom_user["mobile"],
@@ -422,7 +422,7 @@ class User(models.Model):
"gender": self.env["wecomapi.tools.convert"].sex2gender(
wecom_user["gender"]
),
- "wecom_userid": wecom_user["userid"].lower(),
+ "wecom_userid": wecom_user["userid"],
# "image_1920": self.env["wecomapi.tools.file"].get_avatar_base64(
# contacts_use_default_avatar,
# wecom_user["gender"],
@@ -435,7 +435,7 @@ class User(models.Model):
except Exception as e:
result = _("Error creating company %s partner %s %s, error reason: %s") % (
company.name,
- wecom_user["userid"].lower(),
+ wecom_user["userid"],
wecom_user["name"],
repr(e),
)
@@ -467,7 +467,7 @@ class User(models.Model):
]
user = self.sudo().search([("company_id", "=", company_id.id)] + domain)
callback_user = user.search(
- [("wecom_userid", "=", dic["UserID"].lower())] + domain,
+ [("wecom_userid", "=", dic["UserID"])] + domain,
limit=1,
)
# print("用户CMD", cmd)
@@ -502,7 +502,7 @@ class User(models.Model):
if key in WECOM_USER_MAPPING_ODOO_USER.keys():
if WECOM_USER_MAPPING_ODOO_USER[key] != "":
if WECOM_USER_MAPPING_ODOO_USER[key] == "wecom_userid":
- update_dict.update({"wecom_userid": value.lower()})
+ update_dict.update({"wecom_userid": value})
elif WECOM_USER_MAPPING_ODOO_USER[key] == "active":
# 状态
# 激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。
diff --git a/wecom_contacts_sync/models/wecom_apps.py b/wecom_contacts_sync/models/wecom_apps.py
index 250106497b942eb9717801d2a441aa91dd6be4e2..2d037facfae88e158a90ef990d55f517c70b3ef7 100644
--- a/wecom_contacts_sync/models/wecom_apps.py
+++ b/wecom_contacts_sync/models/wecom_apps.py
@@ -156,8 +156,8 @@ class WeComApps(models.Model):
app_config_id = self.env["wecom.app_config"].search([("id", "=", id)])
app_config = (
self.env["wecom.app_config"]
- .sudo()
- .search([("app_id", "=", self.id), ("key", "=", app_config_id.key)])
+ .sudo()
+ .search([("app_id", "=", self.id), ("key", "=", app_config_id.key)])
)
if not app_config:
@@ -169,7 +169,7 @@ class WeComApps(models.Model):
"ttype": app_config_id.ttype,
"value": ""
if app_config_id.key == "join_qrcode"
- or app_config_id.key == "join_qrcode_last_time"
+ or app_config_id.key == "join_qrcode_last_time"
else app_config_id.value,
"description": app_config_id.description,
}
@@ -200,7 +200,7 @@ class WeComApps(models.Model):
sync_start_time = time.time()
for app in self.search(
- [("company_id", "!=", False), ("type_code", "=", "['contacts']")]
+ [("company_id", "!=", False), ("type_code", "=", "['contacts']")]
):
_logger.info(
_(
@@ -309,106 +309,72 @@ Synchronize Wecom tag results:
"""
同步通讯录
"""
- # result = {
-
- # }
result = {}
- result.update(
- {
- "company_name": self.company_id.name,
- "sync_state": "completed",
- "wecom_department_sync_state": "fail",
- "wecom_department_sync_times": 0,
- "wecom_department_sync_result": "",
- "wecom_user_sync_state": "fail",
- "wecom_user_sync_times": 0,
- "wecom_user_sync_result": "",
- "wecom_tag_sync_state": "fail",
- "wecom_tag_sync_times": 0,
- "wecom_tag_sync_result": "",
- }
- )
+ result.update({"company_name": self.company_id.name,
+ "sync_state": "completed",
+ "wecom_department_sync_state": "fail",
+ "wecom_department_sync_times": 0,
+ "wecom_department_sync_result": "",
+ "wecom_user_sync_state": "fail",
+ "wecom_user_sync_times": 0,
+ "wecom_user_sync_result": "",
+ "wecom_tag_sync_state": "fail",
+ "wecom_tag_sync_times": 0,
+ "wecom_tag_sync_result": ""})
# 同步企微部门
- sync_department_result = (
- self.env["wecom.department"]
- .with_context(company_id=self.company_id)
- .download_wecom_deps()
- )
+ sync_department_result = self.env["wecom.department"].with_context(
+ company_id=self.company_id).download_wecom_deps()
# [{'name': 'download_department_data', 'state': True, 'time': 0.3037421703338623, 'msg': 'Department list sync completed.'}]
- (
- wecom_department_sync_state,
- wecom_department_sync_times,
- wecom_department_sync_result,
- ) = self.handle_sync_task_state(sync_department_result, self.company_id)
-
- result.update(
- {
- "wecom_department_sync_state": wecom_department_sync_state,
- "wecom_department_sync_times": wecom_department_sync_times,
- "wecom_department_sync_result": wecom_department_sync_result,
- }
- )
+ (wecom_department_sync_state,
+ wecom_department_sync_times,
+ wecom_department_sync_result,
+ ) = self.handle_sync_task_state(sync_department_result, self.company_id)
+
+ result.update({"wecom_department_sync_state": wecom_department_sync_state,
+ "wecom_department_sync_times": wecom_department_sync_times,
+ "wecom_department_sync_result": wecom_department_sync_result,
+ })
if result["wecom_department_sync_state"] == "fail":
return result
# 同步企微用户
- sync_user_result = (
- self.env["wecom.user"]
- .with_context(company_id=self.company_id)
- .download_wecom_users()
- )
- (
- wecom_user_sync_state,
- wecom_user_sync_times,
- wecom_user_sync_result,
- ) = self.handle_sync_task_state(sync_user_result, self.company_id)
- result.update(
- {
- "wecom_user_sync_state": wecom_user_sync_state,
- "wecom_user_sync_times": wecom_user_sync_times,
- "wecom_user_sync_result": wecom_user_sync_result,
- }
- )
+ sync_user_result = (self.env["wecom.user"].with_context(company_id=self.company_id).download_wecom_users())
+ (wecom_user_sync_state,
+ wecom_user_sync_times,
+ wecom_user_sync_result,
+ ) = self.handle_sync_task_state(sync_user_result, self.company_id)
+ result.update({"wecom_user_sync_state": wecom_user_sync_state,
+ "wecom_user_sync_times": wecom_user_sync_times,
+ "wecom_user_sync_result": wecom_user_sync_result,
+ })
if result["wecom_user_sync_state"] == "fail":
return result
# 同步企微标签
- sync_wecom_tag_result = (
- self.env["wecom.tag"]
- .with_context(company_id=self.company_id)
- .download_wecom_tags()
- )
- (
- wecom_tag_sync_state,
- wecom_tag_sync_times,
- wecom_tag_sync_result,
- ) = self.handle_sync_task_state(sync_wecom_tag_result, self.company_id)
- result.update(
- {
- "wecom_tag_sync_state": wecom_tag_sync_state,
- "wecom_tag_sync_times": wecom_tag_sync_times,
- "wecom_tag_sync_result": wecom_tag_sync_result,
- }
- )
-
+ sync_wecom_tag_result = self.env["wecom.tag"].with_context(company_id=self.company_id).download_wecom_tags()
+
+ (wecom_tag_sync_state,
+ wecom_tag_sync_times,
+ wecom_tag_sync_result,
+ ) = self.handle_sync_task_state(sync_wecom_tag_result, self.company_id)
+ result.update({"wecom_tag_sync_state": wecom_tag_sync_state,
+ "wecom_tag_sync_times": wecom_tag_sync_times,
+ "wecom_tag_sync_result": wecom_tag_sync_result})
if result["wecom_tag_sync_state"] == "fail":
return result
-
return result
def get_state_name(self, key):
"""
获取状态名称
"""
- STATE = {
- "completed": _("All completed"),
- "partially": _("Partially complete"),
- "fail": _("All failed"),
- }
+ STATE = {"completed": _("All completed"),
+ "partially": _("Partially complete"),
+ "fail": _("All failed")}
return dict(STATE).get(key, _("Unknown")) # 如果没有找到,返回Unknown
def handle_sync_result(self, index, rows, result):
@@ -431,9 +397,7 @@ Synchronize Wecom tag results:
fail_state_rows = len(df[df["sync_state"] == "fail"]) # 获取失败行数
# 获取部门失败行数
- fail_department_state_rows = len(
- df[df["wecom_department_sync_state"] == "fail"]
- )
+ fail_department_state_rows = len(df[df["wecom_department_sync_state"] == "fail"])
# 获取用户失败行数
fail_user_state_rows = len(df[df["wecom_user_sync_state"] == "fail"])
@@ -456,10 +420,7 @@ Synchronize Wecom tag results:
# 部门
if fail_department_state_rows == all_state_rows:
wecom_department_sync_state = "fail"
- elif (
- fail_department_state_rows > 0
- and fail_department_state_rows < all_state_rows
- ):
+ elif (fail_department_state_rows > 0 and fail_department_state_rows < all_state_rows):
wecom_department_sync_state = "partially"
elif fail_department_state_rows == 0:
wecom_department_sync_state = "completed"
@@ -471,6 +432,8 @@ Synchronize Wecom tag results:
wecom_user_sync_state = "partially"
elif fail_user_state_rows == 0:
wecom_user_sync_state = "completed"
+ else:
+ wecom_user_sync_state = ''
if fail_tag_state_rows == all_state_rows:
wecom_tag_sync_state = "fail"
@@ -479,12 +442,11 @@ Synchronize Wecom tag results:
elif fail_tag_state_rows == 0:
wecom_tag_sync_state = "completed"
- return (
- sync_state,
- wecom_department_sync_state,
- wecom_user_sync_state,
- wecom_tag_sync_state,
- )
+ return (sync_state,
+ wecom_department_sync_state,
+ wecom_user_sync_state,
+ wecom_tag_sync_state,
+ )
def handle_sync_task_state(self, result, company):
"""
diff --git a/wecom_contacts_sync/models/wecom_department.py b/wecom_contacts_sync/models/wecom_department.py
index ca39fe62689cc92a71f265129e7cf1a9341f8b7a..2af7697b1386fbce6ec03d805bb22525e5a3001c 100644
--- a/wecom_contacts_sync/models/wecom_department.py
+++ b/wecom_contacts_sync/models/wecom_department.py
@@ -16,104 +16,90 @@ class WecomDepartment(models.Model):
_name = "wecom.department"
_description = "Wecom department"
_order = "complete_name"
+ _rec_name = 'complete_name'
# 企微字段
- department_id = fields.Integer(
- string="Department ID", readonly=True, default=0
- ) # 部门id
- name = fields.Char(
- string="Name",
- readonly=True,
- default="",
- compute="_compute_name",
- ) # 部门名称
+ department_id = fields.Integer(string="Department ID", readonly=True, default=0) # 部门id
+ name = fields.Char(string="Name", readonly=True, default="", compute="_compute_name", store=True, ) # 部门名称
name_en = fields.Char(string="English name", readonly=True, default="") # 英部门文名称
- department_leader = fields.Char(
- string="Department Leader", readonly=True, default="[]"
- ) # 部门负责人的UserID;第三方仅通讯录应用可获取
- parentid = fields.Integer(
- string="Parent department id",
- readonly=True,
- default=0,
- domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
- ) # 父部门id。根部门为1
- order = fields.Integer(
- string="Sequence",
- readonly=True,
- default=0,
- ) # 在父部门中的次序值。order值大的排序靠前。值范围是[0, 2^32)
+ # 部门负责人的UserID;第三方仅通讯录应用可获取
+ department_leader = fields.Char(string="Department Leader", readonly=True, default="[]")
+ # 父部门id 根部门为1
+ parentid = fields.Integer(string="Parent department id", readonly=True, default=0,
+ domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
+ order = fields.Integer(string="Sequence", readonly=True, default=0, ) # 在父部门中的次序值。order值大的排序靠前。值范围是[0, 2^32)
# odoo字段
- company_id = fields.Many2one(
- "res.company",
- required=True,
- domain="[('is_wecom_organization', '=', True)]",
- copy=False,
- store=True,
- )
- parent_id = fields.Many2one(
- "wecom.department",
- string="Parent Department",
- index=True,
- domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
- store=True,
- compute="_compute_parent_id",
- )
- child_ids = fields.One2many(
- "wecom.department", "parentid", string="Child Departments"
- )
-
- complete_name = fields.Char(
- "Complete Name", compute="_compute_complete_name", recursive=True, store=True
- )
- department_leader_ids = fields.Many2many(
- "wecom.user",
- "user_department_rel",
- "tag_id",
- "user_id",
- string="Department Leader",
- )
- user_ids = fields.Many2many(
- "wecom.user",
- "wecom_user_department_rel",
- "department_id",
- "user_id",
- string="Members",
- )
+ company_id = fields.Many2one("res.company", required=True, domain="[('is_wecom_organization', '=', True)]",
+ copy=False, store=True, )
+ parent_id = fields.Many2one("wecom.department", string="Parent Department", index=True,
+ domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
+ store=True, compute="_compute_parent_id")
+ child_ids = fields.One2many("wecom.department", "parentid", string="Child Departments")
+
+ complete_name = fields.Char("Complete Name", compute="_compute_complete_name", recursive=True, store=True)
+ department_leader_ids = fields.Many2many("wecom.user", "user_department_rel", "tag_id", "user_id",
+ string="Department Leader", compute='_compute_department_leader', )
+ user_ids = fields.Many2many("wecom.user", "wecom_user_department_rel", "department_id", "user_id",
+ string="Members") # , compute='_compute_user_ids')
color = fields.Integer("Color Index")
@api.depends("department_id", "company_id")
def _compute_name(self):
for department in self:
if not department.name:
- department.name = "%s:%s" % (
- department.company_id.name,
- department.department_id,
- )
+ department.name = "%s:%s" % (department.company_id.name, department.department_id,)
+
+ @api.onchange("department_leader", "company_id")
+ @api.depends("department_leader", "company_id")
+ def _compute_department_leader(self):
+ for department in self:
+ if department.department_leader:
+ wecom_users = []
+ department_leaders = eval(department.department_leader)
+ for leader in department_leaders:
+ print(leader)
+ wecom_user = self.env['wecom.user'].search([('userid', '=', leader),
+ ("company_id", "=", self.company_id.id)], limit=1)
+ if wecom_user:
+ wecom_users.append(wecom_user.id)
+ department.write({"department_leader_ids": [(6, 0, wecom_users)]})
+
+ # @api.onchange("department_leader", "company_id")
+ # @api.depends("department_leader", "company_id")
+ # def _compute_user_ids(self):
+ # for department in self:
+ # if department.department_leader:
+ # wecom_users = []
+ # department_leaders = eval(department.department_leader)
+ # for leader in department_leaders:
+ # print(leader)
+ # wecom_user = self.env['wecom.user'].search([('userid', '=', leader),
+ # ("company_id", "=", self.company_id.id)], limit=1)
+ # if wecom_user:
+ # wecom_users.append(wecom_user.id)
+ # department.write({"department_leader_ids": [(6, 0, wecom_users)]})
@api.depends("parentid", "company_id")
def _compute_parent_id(self):
for department in self:
if department.parentid:
- parent_department = self.sudo().search(
- [
- ("department_id", "=", department.parentid),
- ("company_id", "=", department.company_id.id),
- ]
- )
+ parent_department = self.sudo().search([("department_id", "=", department.parentid),
+ ("company_id", "=", department.company_id.id), ])
department.parent_id = parent_department.id
@api.depends("name", "parent_id", "company_id")
def _compute_complete_name(self):
for department in self:
if department.parent_id:
- department.complete_name = "%s / %s" % (
- department.parent_id.complete_name,
- department.name,
- )
+ department.complete_name = "%s / %s" % (department.parent_id.complete_name, department.name,)
else:
department.complete_name = department.name
+ def write(self, vals):
+ res = super(WecomDepartment, self).write(vals)
+ return res
+
# @api.onchange('parent_id')
# def _onchange_parentid(self):
# for department in self:
@@ -140,62 +126,53 @@ class WecomDepartment(models.Model):
tasks = []
try:
- wxapi = self.env["wecom.service_api"].InitServiceApi(
- company.corpid, company.contacts_app_id.secret
- )
+ # 改为只能使用默认的自建应用获取
+ wecom_app = self.env['wecom.apps'].search([('company_id', '=', company.id),
+ ('type', '=', 'self')], order='sequence Desc', limit=1)
+ wxapi = self.env["wecom.service_api"].InitServiceApi(company.corpid, wecom_app.secret)
# 2022-08-10 按官方建议进行重构
# 官方建议换用 获取子部门ID列表 与 获取单个部门详情 组合的方式获取部门
- response = wxapi.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call(
- "DEPARTMENT_SIMPLELIST"
- ),
- )
+ # response = wxapi.httpCall(self.env["wecom.service_api_list"].get_server_api_call("DEPARTMENT_SIMPLELIST"), )
+ # 2022-08-10 按官方建议进行重构
+ # 使用自建应用权限可以获取部门ID以及name以及联系人信息
+ response = wxapi.httpCall(self.env["wecom.service_api_list"].get_server_api_call("DEPARTMENT_LIST"))
except ApiException as ex:
end_time = time.time()
self.env["wecomapi.tools.action"].ApiExceptionDialog(
ex, raise_exception=False
)
- tasks = [
- {
- "name": "download_department_data",
- "state": False,
- "time": end_time - start_time,
- "msg": str(ex),
- }
- ]
+ tasks = [{"name": "download_department_data",
+ "state": False,
+ "time": end_time - start_time,
+ "msg": str(ex),
+ }
+ ]
except Exception as e:
end_time = time.time()
- tasks = [
- {
- "name": "download_department_data",
- "state": False,
- "time": end_time - start_time,
- "msg": str(e),
- }
- ]
+ tasks = [{"name": "download_department_data",
+ "state": False,
+ "time": end_time - start_time,
+ "msg": str(e), }]
else:
if response["errcode"] == 0:
# 获取只有 'id' , 'parentid' , 'order' 字段的列表
- wecom_departments = response["department_id"]
-
+ # wecom_departments = response["department_id"]
+ wecom_departments = response["department"]
# 1.下载部门
for wecom_department in wecom_departments:
- download_department_result = self.download_department(
- company, wecom_department
- )
+ download_department_result = self.download_department(company, wecom_department)
if download_department_result:
for r in download_department_result:
tasks.append(r) # 加入 下载员工失败结果
# 3.完成
end_time = time.time()
- task = {
- "name": "download_department_data",
- "state": True,
- "time": end_time - start_time,
- "msg": _("Department list sync completed."),
- }
+ task = {"name": "download_department_data",
+ "state": True,
+ "time": end_time - start_time,
+ "msg": _("Department list sync completed."),
+ }
tasks.append(task)
finally:
return tasks # 返回结果
@@ -205,16 +182,8 @@ class WecomDepartment(models.Model):
下载部门
"""
# 查询数据库是否存在相同的企业微信部门ID,有则更新,无则新建
- department = self.sudo().search(
- [
- ("department_id", "=", wecom_department["id"]),
- ("company_id", "=", company.id),
- ],
- limit=1,
- )
-
- result = {}
-
+ department = self.sudo().search([("department_id", "=", wecom_department["id"]),
+ ("company_id", "=", company.id), ], limit=1, )
if not department:
result = self.create_department(company, department, wecom_department)
else:
@@ -226,54 +195,43 @@ class WecomDepartment(models.Model):
创建部门
"""
try:
- department.create(
- {
- "department_id": wecom_department["id"],
- "parentid": wecom_department["parentid"],
- "order": wecom_department["order"],
- "company_id": company.id,
- }
- )
+ department.create({"department_id": wecom_department["id"],
+ "parentid": wecom_department["parentid"],
+ "order": wecom_department["order"],
+ "complete_name": wecom_department["name"],
+ "department_leader": wecom_department["department_leader"],
+ "company_id": company.id, })
except Exception as e:
- result = _(
- "Error creating company [%s]'s department [%s], error reason: %s"
- ) % (
- company.name,
- wecom_department["id"],
- repr(e),
- )
+ result = _("Error creating company [%s]'s department [%s], error reason: %s") % (company.name,
+ wecom_department["id"],
+ repr(e),
+ )
_logger.warning(result)
- return {
- "name": "add_department",
- "state": False,
- "time": 0,
- "msg": result,
- }
+ return {"name": "add_department",
+ "state": False,
+ "time": 0,
+ "msg": result,
+ }
def update_department(self, company, department, wecom_department):
"""
更新部门
"""
try:
- department.write(
- {
- "parentid": wecom_department["parentid"],
- "order": wecom_department["order"],
- }
- )
+ department.write({"name": wecom_department["name"],
+ "complete_name": wecom_department["name"],
+ "parentid": wecom_department["parentid"],
+ "order": wecom_department["order"],
+ "department_leader": wecom_department["department_leader"],
+ "company_id": company.id, })
except Exception as e:
- result = _("Error updating Department [%s], error details:%s") % (
- wecom_department["name"],
- str(e),
- )
- result = _(
- "Error update company [%s]'s Department [%s], error reason: %s"
- ) % (
- company.name,
- wecom_department["id"],
- repr(e),
- )
+ result = _("Error updating Department [%s], error details:%s") % (wecom_department["name"],
+ str(e),)
+ result = _("Error update company [%s]'s Department [%s], error reason: %s") % (company.name,
+ wecom_department["id"],
+ repr(e),
+ )
_logger.warning(result)
return {
"name": "update_department",
@@ -344,87 +302,70 @@ class WecomDepartment(models.Model):
params = {}
message = ""
try:
- wxapi = self.env["wecom.service_api"].InitServiceApi(
- company.corpid, company.contacts_app_id.secret
- )
- response = wxapi.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call(
- "DEPARTMENT_DETAILS"
- ),
- {"id": str(self.department_id)},
- )
+ # 改为只能使用默认的自建应用获取
+ wecom_app = self.env['wecom.apps'].search([('company_id', '=', company.id),
+ ('type', '=', 'self')], order='sequence Desc', limit=1)
+ wxapi = self.env["wecom.service_api"].InitServiceApi(company.corpid, wecom_app.secret)
+ response = wxapi.httpCall(self.env["wecom.service_api_list"].get_server_api_call("DEPARTMENT_DETAILS"),
+ {"id": str(self.department_id)}, )
department = response["department"]
for key in department.keys():
if type(department[key]) in (list, dict) and department[key]:
- json_str = json.dumps(
- department[key],
- sort_keys=False,
- indent=2,
- separators=(",", ":"),
- ensure_ascii=False,
- )
+ json_str = json.dumps(department[key],
+ sort_keys=False,
+ indent=2,
+ separators=(",", ":"),
+ ensure_ascii=False,
+ )
department[key] = json_str
- self.sudo().write(
- {
- "name": department["name"],
- "name_en": self.env[
- "wecomapi.tools.dictionary"
- ].check_dictionary_keywords(department, "name_en"),
- "department_leader": department["department_leader"],
- "parentid": department["parentid"],
- "order": department["order"],
- }
- )
+ self.sudo().write({"name": department["name"],
+ "name_en": self.env["wecomapi.tools.dictionary"].check_dictionary_keywords(department,
+ "name_en"),
+ "department_leader": department["department_leader"],
+ "parentid": department["parentid"],
+ "order": department["order"], }
+ )
except ApiException as ex:
- message = _("Department [id:%s, name:%s] failed to download,Reason: %s") % (
- self.department_id,
- self.name,
- str(ex),
- )
+ message = _("Department [id:%s, name:%s] failed to download,Reason: %s") % (self.department_id,
+ self.name,
+ str(ex))
_logger.warning(message)
- params = {
- "title": _("Download failed!"),
- "message": message,
- "sticky": True, # 延时关闭
- "className": "bg-danger",
- "type": "danger",
- }
+ params = {"title": _("Download failed!"),
+ "message": message,
+ "sticky": True, # 延时关闭
+ "className": "bg-danger",
+ "type": "danger",
+ }
except Exception as e:
- message = _("Department [id:%s, name:%s] failed to download,Reason: %s") % (
- self.department_id,
- self.name,
- str(e),
- )
+ message = _("Department [id:%s, name:%s] failed to download,Reason: %s") % (self.department_id,
+ self.name,
+ str(e),
+ )
_logger.warning(message)
- params = {
- "title": _("Download failed!"),
- "message": message,
- "sticky": True, # 延时关闭
- "className": "bg-danger",
- "type": "danger",
- }
+ params = {"title": _("Download failed!"),
+ "message": message,
+ "sticky": True, # 延时关闭
+ "className": "bg-danger",
+ "type": "danger"
+ }
else:
- message = _("Department [id:%s, name:%s] downloaded successfully") % (
- self.department_id,
- self.name,
- )
- params = {
- "title": _("Download Success!"),
- "message": message,
- "sticky": False, # 延时关闭
- "className": "bg-success",
- "type": "success",
- "next": {
- "type": "ir.actions.client",
- "tag": "reload",
- }, # 刷新窗体
- }
+ message = _("Department [id:%s, name:%s] downloaded successfully") % (self.department_id,
+ self.name,
+ )
+ params = {"title": _("Download Success!"),
+ "message": message,
+ "sticky": False, # 延时关闭
+ "className": "bg-success",
+ "type": "success",
+ "next": {"type": "ir.actions.client",
+ "tag": "reload",
+ }, # 刷新窗体
+ }
finally:
- action = {
- "type": "ir.actions.client",
- "tag": "display_notification",
- "params": params,
- }
+ action = {"type": "ir.actions.client",
+ "tag": "display_notification",
+ "params": params,
+ }
return action
# ------------------------------------------------------------
diff --git a/wecom_contacts_sync/models/wecom_user.py b/wecom_contacts_sync/models/wecom_user.py
index 65eec13e3b340d3e963718c792221025a5cc77d2..50d421ef96e197ab031abbd2c9217d3d6859f4fb 100644
--- a/wecom_contacts_sync/models/wecom_user.py
+++ b/wecom_contacts_sync/models/wecom_user.py
@@ -19,42 +19,30 @@ class WecomUser(models.Model):
_order = "order_in_department"
# 企微字段
- userid = fields.Char(
- string="User ID",
- readonly=True,
- default="",
- ) # 成员UserID。对应管理端的帐号
+ userid = fields.Char(string="User ID",
+ readonly=True,
+ default="",
+ ) # 成员UserID。对应管理端的帐号
name = fields.Char(string="Name", readonly=True, default="") # 成员名称
english_name = fields.Char(
string="English name", readonly=True, default=""
) # 英部门文名称
mobile = fields.Char(string="mobile phone", readonly=True, default="") # 手机号码
- department = fields.Char(
- string="Multiple Department ID", readonly=True, store=True, default="[]"
- ) # 成员所属部门id列表
-
- main_department = fields.Char(
- string="Main department", readonly=True, default=""
- ) # 主部门
- order = fields.Char(
- string="Sequence", readonly=True, default="[]"
- ) # 部门内的排序值,默认为0。数量必须和department一致,数值越大排序越前面。值范围是[0, 2^32)
+ department = fields.Char(string="Multiple Department ID", readonly=True, store=True, default="[]") # 成员所属部门id列表
+
+ main_department = fields.Char(string="Main department", readonly=True, default="") # 主部门
+ order = fields.Char(string="Sequence", readonly=True, default="[]")
+ # 部门内的排序值,默认为0。数量必须和department一致,数值越大排序越前面。值范围是[0, 2^32)
position = fields.Char(string="Position", readonly=True, default="") # 职务信息;
- gender = fields.Char(
- string="Gender", readonly=True, default=""
- ) # 性别。0表示未定义,1表示男性,2表示女性。
+ gender = fields.Char(string="Gender", readonly=True, default="") # 性别。0表示未定义,1表示男性,2表示女性。
email = fields.Char(string="Email", readonly=True, default="") # 邮箱
biz_mail = fields.Char(string="BizMail", readonly=True, default="") # 企业邮箱
- is_leader_in_dept = fields.Char(
- string="Is Department Leader", readonly=True, default="[]"
- ) # 表示在所在的部门内是否为部门负责人。0-否;1-是。是一个列表,数量必须与department一致。
- direct_leader = fields.Char(
- string="Direct Leader", readonly=True, default="[]"
- ) # 直属上级UserID,返回在应用可见范围内的直属上级列表,最多有五个直属上级
+ is_leader_in_dept = fields.Char(string="Is Department Leader", readonly=True, default="[]")
+ # 表示在所在的部门内是否为部门负责人。0-否;1-是。是一个列表,数量必须与department一致。
+ direct_leader = fields.Char(string="Direct Leader", readonly=True, default="[]")
+ # 直属上级UserID,返回在应用可见范围内的直属上级列表,最多有五个直属上级
avatar = fields.Char(string="Avatar", readonly=True, default="") # 头像url
- thumb_avatar = fields.Char(
- string="Avatar thumbnail", readonly=True, default=""
- ) # 头像缩略图url
+ thumb_avatar = fields.Char(string="Avatar thumbnail", readonly=True, default="") # 头像缩略图url
telephone = fields.Char(string="Telephone", readonly=True, default="") # 座机号码
alias = fields.Char(string="Alias", readonly=True, default="") # 别名
extattr = fields.Text(
@@ -78,70 +66,54 @@ class WecomUser(models.Model):
) # 开放用户Id,全局唯一,对于同一个服务商,不同应用获取到企业内同一个成员的open_userid是相同的,最多64个字节。仅第三方应用可获取
# odoo 字段
- company_id = fields.Many2one(
- "res.company",
- required=True,
- domain="[('is_wecom_organization', '=', True)]",
- copy=False,
- store=True,
- readonly=True,
- )
- department_id = fields.Many2one(
- "wecom.department",
- "Department",
- domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
- compute="_compute_department_id",
- store=True,
- )
- department_ids = fields.Many2many(
- "wecom.department",
- "wecom_user_department_rel",
- "user_id",
- "department_id",
- string="Multiple Departments",
- readonly=True,
- compute="_compute_department_ids",
- )
- tag_ids = fields.Many2many(
- "wecom.tag",
- "wecom_user_tag_rel",
- "wecom_user_id",
- "wecom_tag_id",
- string="Tags",
- )
- department_complete_name = fields.Char(
- string="Department complete Name", related="department_id.complete_name"
- )
- order_in_department = fields.Integer(
- string="Sequence in department",
- readonly=True,
- default="0",
- ) # 成员在对应部门中的排序值,默认为0。数量必须和department一致
- status_name = fields.Selection(
- [
- ("1", _("Activated")),
- ("2", _("Disabled")),
- ("4", _("Not active")),
- ("5", _("Exit the enterprise")),
- ],
- string="Status",
- readonly=True,
- # compute="_compute_status_name",
- ) # 激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。已激活代表已激活企业微信或已关注微信插件(原企业号)。未激活代表既未激活企业微信又未关注微信插件(原企业号)。
-
- gender_name = fields.Selection(
- [("1", _("Male")), ("2", _("Female")), ("0", _("Undefined"))],
- string="Gender",
- # compute="_compute_gender_name",
- )
+ company_id = fields.Many2one("res.company",
+ required=True,
+ domain="[('is_wecom_organization', '=', True)]",
+ copy=False,
+ store=True,
+ readonly=True, )
+ department_id = fields.Many2one("wecom.department", "Department",
+ domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
+ compute="_compute_department_id", store=True)
+ department_ids = fields.Many2many("wecom.department",
+ "wecom_user_department_rel",
+ "user_id",
+ "department_id",
+ string="Multiple Departments",
+ readonly=True,
+ compute="_compute_department_ids", )
+ tag_ids = fields.Many2many("wecom.tag",
+ "wecom_user_tag_rel",
+ "wecom_user_id",
+ "wecom_tag_id",
+ string="Tags",
+ )
+ department_complete_name = fields.Char(string="Department complete Name", related="department_id.complete_name")
+ order_in_department = fields.Integer(string="Sequence in department",
+ readonly=True,
+ default="0",
+ ) # 成员在对应部门中的排序值,默认为0。数量必须和department一致
+ status_name = fields.Selection([("1", _("Activated")),
+ ("2", _("Disabled")),
+ ("4", _("Not active")),
+ ("5", _("Exit the enterprise")), ],
+ string="Status", readonly=True,
+ # compute="_compute_status_name",
+ ) # 激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。已激活代表已激活企业微信或已关注微信插件(原企业号)。未激活代表既未激活企业微信又未关注微信插件(原企业号)。
+
+ gender_name = fields.Selection([("1", _("Male")),
+ ("2", _("Female")),
+ ("0", _("Undefined"))],
+ string="Gender",
+ # compute="_compute_gender_name",
+ )
color = fields.Integer("Color Index")
- active = fields.Boolean(
- "Active",
- default=True,
- store=True,
- readonly=True,
- # compute="_compute_active",
- )
+ active = fields.Boolean("Active",
+ default=True,
+ store=True,
+ readonly=True,
+ # compute="_compute_active",
+ )
@api.depends("status")
def _compute_status_name(self):
@@ -159,13 +131,8 @@ class WecomUser(models.Model):
@api.depends("main_department")
def _compute_department_id(self):
for user in self:
- department_id = self.env["wecom.department"].search(
- [
- ("department_id", "=", user.main_department),
- ("company_id", "=", user.company_id.id),
- ],
- limit=1,
- )
+ department_id = self.env["wecom.department"].search([("department_id", "=", user.main_department),
+ ("company_id", "=", user.company_id.id)], limit=1)
if department_id:
user.department_id = department_id
@@ -181,9 +148,7 @@ class WecomUser(models.Model):
"""
for user in self:
department_list = eval(user.department)
- department_ids = self.get_parent_department(
- user.company_id, department_list
- )
+ department_ids = self.get_parent_department(user.company_id, department_list)
user.write({"department_ids": [(6, 0, department_ids)]})
@@ -193,62 +158,64 @@ class WecomUser(models.Model):
"""
department_ids = []
for department in departments:
- department_id = self.env["wecom.department"].search(
- [
- ("department_id", "=", department),
- ("company_id", "=", company.id),
- ],
- limit=1,
- )
+ department_id = self.env["wecom.department"].search([("department_id", "=", department),
+ ("company_id", "=", company.id)], limit=1)
if department_id:
department_ids.append(department_id.id)
return department_ids
-
def copy_as_system_user(self):
"""
复制为系统用户
"""
app_config = self.env["wecom.app_config"].sudo()
- contacts_allow_add_system_users = app_config.get_param(
- self.company_id.contacts_app_id.id, "contacts_allow_add_system_users"
- ) # 允许创建用户
+ contacts_allow_add_system_users = app_config.get_param(self.company_id.contacts_app_id.id,
+ "contacts_allow_add_system_users"
+ ) # 允许创建用户
if contacts_allow_add_system_users:
# 允许 通讯录 生成系统用户
+ # 首先 检查这个用户名称是否存在系统用户
+ user_name = tools.ustr(self.name)
login = tools.ustr(self.userid)
- domain=[('wecom_userid','=',login),"|",("active", "=", True),("active", "=", False)]
- user = self.env["res.users"].search(domain, limit=1)
- if not user:
- # 不存在系统用户,则创建系统用户
-
- group_portal_id = self.env["ir.model.data"]._xmlid_to_res_id("base.group_portal") # 门户用户组
- user.create({
- "name": self.name if self.name else login,
- "login": login,
- "groups_id": [(6, 0, [group_portal_id])],
- "share": False,
- "active": True if self.status == 1 else False,
- # "image_1920": self.avatar,
- "company_id": self.company_id.id,
- # 以下为企业微信字段
- "wecom_userid": login,
- "wecom_openid": self.open_userid,
- "is_wecom_user": True,
- "qr_code": self.qr_code,
- "wecom_user_order": self.order,
- })
+ user = self.env["res.users"].search(
+ [('name', '=', user_name), "|", ("active", "=", True), ("active", "=", False)], limit=1)
+ if user:
+ # 以下为企业微信字段
+ user.write({"wecom_userid": login,
+ "wecom_openid": self.open_userid,
+ "is_wecom_user": True,
+ "qr_code": self.qr_code,
+ "wecom_user_order": self.order,
+ })
+ else:
+ domain = [('wecom_userid', '=', login), "|", ("active", "=", True), ("active", "=", False)]
+ user = self.env["res.users"].search(domain, limit=1)
+ if not user:
+ # 不存在系统用户,则创建系统用户
+ group_portal_id = self.env["ir.model.data"]._xmlid_to_res_id("base.group_portal") # 门户用户组
+ user.create({"name": self.name if self.name else login,
+ "login": login,
+ "groups_id": [(6, 0, [group_portal_id])],
+ "share": False,
+ "active": True if self.status == 1 else False,
+ # "image_1920": self.avatar,
+ "company_id": self.company_id.id,
+ # 以下为企业微信字段
+ "wecom_userid": login,
+ "wecom_openid": self.open_userid,
+ "is_wecom_user": True,
+ "qr_code": self.qr_code,
+ "wecom_user_order": self.order,
+ })
else:
# 不允许 通讯录 生成系统用户
- msg = {
- "title": _("Error!"),
- "message": _("The current configuration does not allow replication as a system user!"),
- "sticky": False
- }
+ msg = {"title": _("Error!"),
+ "message": _("The current configuration does not allow replication as a system user!"),
+ "sticky": False
+ }
return self.env["wecomapi.tools.action"].WecomWarningNotification(msg)
-
-
# ------------------------------------------------------------
# 企微用户下载
# ------------------------------------------------------------
@@ -258,53 +225,36 @@ class WecomUser(models.Model):
下载用户列表
"""
start_time = time.time()
-
company = self.env.context.get("company_id")
if type(company) == int:
company = self.env["res.company"].browse(company)
-
tasks = []
-
try:
- wxapi = self.env["wecom.service_api"].InitServiceApi(
- company.corpid, company.contacts_app_id.secret
- )
+ wxapi = self.env["wecom.service_api"].InitServiceApi(company.corpid, company.contacts_app_id.secret)
# 2020-8-27 按照官方API要求,进行重构
# json对象只有 userid 和 department 两个字段
# 参数:"cursor", 必须:否, 说明:用于分页查询的游标,字符串类型,由上一次调用返回,首次调用不填
# 参数:"limit", 必须:否, 说明:分页,预期请求的数据量,取值范围 1 ~ 10000
- response = wxapi.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call("USER_LIST_ID"),
- {}
- # {"department_id": "1", "fetch_child": "1",},
- )
+ response = wxapi.httpCall(self.env["wecom.service_api_list"].get_server_api_call("USER_LIST_ID"),
+ {}
+ # {"department_id": "1", "fetch_child": "1",},
+ )
except ApiException as ex:
end_time = time.time()
-
- self.env["wecomapi.tools.action"].ApiExceptionDialog(
- str(ex), raise_exception=False
- )
- tasks = [
- {
- "name": "download_user_data",
- "state": False,
- "time": end_time - start_time,
- "msg": str(ex),
- }
- ]
+ self.env["wecomapi.tools.action"].ApiExceptionDialog(str(ex), raise_exception=False)
+ tasks = [{"name": "download_user_data",
+ "state": False,
+ "time": end_time - start_time,
+ "msg": str(ex), }]
except Exception as e:
end_time = time.time()
- tasks = [
- {
- "name": "download_user_data",
- "state": False,
- "time": end_time - start_time,
- "msg": str(e),
- }
- ]
+ tasks = [{"name": "download_user_data",
+ "state": False,
+ "time": end_time - start_time,
+ "msg": str(e), }]
else:
# response["userlist"] 只含 'department', 'userid' 2个字段
if response["errcode"] == 0:
@@ -314,7 +264,7 @@ class WecomUser(models.Model):
for dic in dept_user:
userid, department = dic["userid"], dic["department"]
d[userid]["userid"] = userid
- d[userid]["department"].extend(str(department))
+ d[userid]["department"].append(str(department))
userlist = []
for key, value in d.items():
@@ -336,12 +286,10 @@ class WecomUser(models.Model):
# 3.完成下载
end_time = time.time()
- task = {
- "name": "download_user_data",
- "state": True,
- "time": end_time - start_time,
- "msg": _("User list sync completed."),
- }
+ task = {"name": "download_user_data",
+ "state": True,
+ "time": end_time - start_time,
+ "msg": _("User list sync completed."), }
tasks.append(task)
finally:
return tasks # 返回结果
@@ -350,14 +298,7 @@ class WecomUser(models.Model):
"""
下载用户
"""
- user = self.sudo().search(
- [
- ("userid", "=", wecom_user["userid"].lower()),
- ("company_id", "=", company.id),
- ],
- limit=1,
- )
-
+ user = self.sudo().search([("userid", "=", wecom_user["userid"]), ("company_id", "=", company.id)], limit=1)
result = {}
if not user:
result = self.create_user(company, user, wecom_user)
@@ -370,52 +311,40 @@ class WecomUser(models.Model):
创建用户
"""
try:
- user.create(
- {
- "userid": wecom_user["userid"],
- "department": wecom_user["department"],
- "company_id": company.id,
- }
- )
+ user.create({"userid": wecom_user["userid"],
+ "department": wecom_user["department"],
+ "company_id": company.id,
+ })
+ download_single_user = user.download_single_user()
except Exception as e:
- result = _("Error creating company [%s]'s user [%s], error reason: %s") % (
- company.userid,
- wecom_user["userid"].lower(),
- repr(e),
- )
-
+ result = _("Error creating company [%s]'s user [%s], error reason: %s") % (company.userid,
+ wecom_user["userid"],
+ repr(e),)
_logger.warning(result)
- return {
- "name": "add_user",
- "state": False,
- "time": 0,
- "msg": result,
- }
+ return {"name": "add_user",
+ "state": False,
+ "time": 0,
+ "msg": result,
+ }
def update_user(self, company, user, wecom_user):
"""
更新用户
"""
try:
- user.sudo().write(
- {
- "department": wecom_user["department"],
- }
- )
-
+ user.sudo().write({"department": wecom_user["department"]})
+ if not user.name:
+ download_single_user = user.download_single_user()
except Exception as e:
- result = _("Error update company [%s]'s user [%s], error reason: %s") % (
- company.name,
- wecom_user["userid"].lower(),
- repr(e),
- )
+ result = _("Error update company [%s]'s user [%s], error reason: %s") % (company.name,
+ wecom_user["userid"],
+ repr(e),)
_logger.warning(result)
- return {
- "name": "update_user",
- "state": False,
- "time": 0,
- "msg": result,
- } # 返回失败结果
+ return {"name": "update_user",
+ "state": False,
+ "time": 0,
+ "msg": result,
+ } # 返回失败结果
def download_single_user(self):
"""
@@ -425,96 +354,76 @@ class WecomUser(models.Model):
params = {}
message = ""
try:
- wxapi = self.env["wecom.service_api"].InitServiceApi(
- company.corpid, company.contacts_app_id.secret
- )
- response = wxapi.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call("USER_GET"),
- {"userid": self.userid},
- )
+ # 改为只能使用默认的自建应用获取
+ wecom_app = self.env['wecom.apps'].search([('company_id', '=', company.id),
+ ('type', '=', 'self')], order='sequence Desc', limit=1)
+ wxapi = self.env["wecom.service_api"].InitServiceApi(company.corpid, wecom_app.secret)
+ response = wxapi.httpCall(self.env["wecom.service_api_list"].get_server_api_call("USER_GET"),
+ {"userid": self.userid}, )
for key in response.keys():
if type(response[key]) in (list, dict) and response[key]:
- json_str = json.dumps(
- response[key],
- sort_keys=False,
- indent=2,
- separators=(",", ":"),
- ensure_ascii=False,
- )
+ json_str = json.dumps(response[key],
+ sort_keys=False,
+ indent=2,
+ separators=(",", ":"),
+ ensure_ascii=False,
+ )
response[key] = json_str
- self.write(
- {
- "name": response["name"],
- "english_name": self.env[
- "wecomapi.tools.dictionary"
- ].check_dictionary_keywords(response, "english_name"),
- "mobile": response["mobile"],
- "department": response["department"],
- "main_department": response["main_department"],
- "order": response["order"],
- "position": response["position"],
- "gender": response["gender"],
- "email": response["email"],
- "biz_mail": response["biz_mail"],
- "is_leader_in_dept": response["is_leader_in_dept"],
- "direct_leader": response["direct_leader"],
- "avatar": response["avatar"],
- "thumb_avatar": response["thumb_avatar"],
- "telephone": response["telephone"],
- "alias": response["alias"],
- "extattr": response["extattr"],
- "external_profile": self.env[
- "wecomapi.tools.dictionary"
- ].check_dictionary_keywords(response, "external_profile"),
- "external_position": self.env[
- "wecomapi.tools.dictionary"
- ].check_dictionary_keywords(response, "external_position"),
- "status": response["status"],
- "qr_code": response["qr_code"],
- "address": self.env[
- "wecomapi.tools.dictionary"
- ].check_dictionary_keywords(response, "address"),
- "open_userid": self.env[
- "wecomapi.tools.dictionary"
- ].check_dictionary_keywords(response, "open_userid"),
- }
- )
+ self.write({"name": response["name"],
+ "english_name": self.env["wecomapi.tools.dictionary"].check_dictionary_keywords(response,
+ "english_name"),
+ # "mobile": response["mobile"],
+ "department": response["department"],
+ "main_department": response["main_department"],
+ "order": response["order"],
+ "position": response["position"],
+ # "gender": response["gender"],
+ # "email": response["email"],
+ # "biz_mail": response["biz_mail"],
+ "is_leader_in_dept": response["is_leader_in_dept"],
+ "direct_leader": response["direct_leader"],
+ # "avatar": response["avatar"],
+ # "thumb_avatar": response["thumb_avatar"],
+ "telephone": response["telephone"],
+ "alias": response["alias"],
+ "extattr": response["extattr"],
+ "external_profile": self.env["wecomapi.tools.dictionary"].check_dictionary_keywords(response,
+ "external_profile"),
+ "external_position": self.env["wecomapi.tools.dictionary"].check_dictionary_keywords(response,
+ "external_position"),
+ "status": response["status"],
+ # "qr_code": response["qr_code"],
+ "address": self.env["wecomapi.tools.dictionary"].check_dictionary_keywords(response, "address"),
+ "open_userid": self.env["wecomapi.tools.dictionary"].check_dictionary_keywords(response,
+ "open_userid")})
except ApiException as ex:
- message = _("User [id:%s, name:%s] failed to download,Reason: %s") % (
- self.userid,
- self.name,
- str(ex),
- )
+ message = _("User [id:%s, name:%s] failed to download,Reason: %s") % (self.userid,
+ self.name,
+ str(ex),
+ )
_logger.warning(message)
- params = {
- "title": _("Download failed!"),
- "message": message,
- "sticky": True, # 延时关闭
- "className": "bg-danger",
- "type": "danger",
- }
+ params = {"title": _("Download failed!"),
+ "message": message,
+ "sticky": True, # 延时关闭
+ "className": "bg-danger",
+ "type": "danger", }
else:
- message = _("User [id:%s, name:%s] downloaded successfully") % (
- self.userid,
- self.name,
- )
- params = {
- "title": _("Download Success!"),
- "message": message,
- "sticky": False, # 延时关闭
- "className": "bg-success",
- "type": "success",
- "next": {
- "type": "ir.actions.client",
- "tag": "reload",
- }, # 刷新窗体
- }
+ message = _("User [id:%s, name:%s] downloaded successfully") % (self.userid,
+ self.name,)
+ params = {"title": _("Download Success!"),
+ "message": message,
+ "sticky": False, # 延时关闭
+ "className": "bg-success",
+ "type": "success",
+ "next": {"type": "ir.actions.client",
+ "tag": "reload",
+ }, # 刷新窗体
+ }
finally:
- action = {
- "type": "ir.actions.client",
- "tag": "display_notification",
- "params": params,
- }
+ action = {"type": "ir.actions.client",
+ "tag": "display_notification",
+ "params": params,
+ }
return action
def get_open_userid(self):
@@ -523,22 +432,12 @@ class WecomUser(models.Model):
"""
for user in self:
try:
- wxapi = self.env["wecom.service_api"].InitServiceApi(
- user.company_id.corpid,
- user.company_id.contacts_app_id.secret,
- )
- response = wxapi.httpCall(
- self.env["wecom.service_api_list"].get_server_api_call(
- "USERID_TO_OPENID"
- ),
- {
- "userid": user.userid,
- },
- )
+ wxapi = self.env["wecom.service_api"].InitServiceApi(user.company_id.corpid,
+ user.company_id.contacts_app_id.secret, )
+ response = wxapi.httpCall(self.env["wecom.service_api_list"].get_server_api_call("USERID_TO_OPENID"),
+ {"userid": user.userid, }, )
except ApiException as ex:
- self.env["wecomapi.tools.action"].ApiExceptionDialog(
- ex, raise_exception=True
- )
+ self.env["wecomapi.tools.action"].ApiExceptionDialog(ex, raise_exception=True)
else:
user.open_userid = response["openid"]
@@ -553,17 +452,9 @@ class WecomUser(models.Model):
company_id = self.env.context.get("company_id")
user_dict = xmltodict.parse(xml_tree)["xml"]
# print("wecom_event_change_contact_user", user_dict)
- domain = [
- "|",
- ("active", "=", True),
- ("active", "=", False),
- ]
-
+ domain = ["|", ("active", "=", True), ("active", "=", False)]
users = self.sudo().search([("company_id", "=", company_id.id)] + domain)
- callback_user = users.search(
- [("userid", "=", user_dict["UserID"])],
- limit=1,
- )
+ callback_user = users.search([("userid", "=", user_dict["UserID"])], limit=1, )
if callback_user:
# 如果存在,则更新
@@ -595,8 +486,4 @@ class WecomUser(models.Model):
del update_dict["userid"]
callback_user.write(update_dict)
elif cmd == "delete":
- callback_user.write(
- {
- "active": False,
- }
- )
+ callback_user.write({"active": False})
diff --git a/wecom_contacts_sync/views/wecom_department_views.xml b/wecom_contacts_sync/views/wecom_department_views.xml
index 784fe718636d32ce20f05f5f936cb05356ab83ff..b0d73eafb9515cf1d3af8ffaa03353863a48eb48 100644
--- a/wecom_contacts_sync/views/wecom_department_views.xml
+++ b/wecom_contacts_sync/views/wecom_department_views.xml
@@ -7,6 +7,9 @@
+
+
+
@@ -15,6 +18,7 @@
+
@@ -42,6 +46,7 @@
+
@@ -61,4 +66,4 @@
-
\ No newline at end of file
+
diff --git a/wecom_contacts_sync/views/wecom_user_views.xml b/wecom_contacts_sync/views/wecom_user_views.xml
index 3b9edeafcdf2780c144b35fd0257c00cded4c6b1..4d625c0fd6059241cc9a05560356ba78ee415b63 100644
--- a/wecom_contacts_sync/views/wecom_user_views.xml
+++ b/wecom_contacts_sync/views/wecom_user_views.xml
@@ -7,11 +7,12 @@
wecom.user
-
-
+
+
-
+
@@ -28,21 +29,23 @@
-
+
-
-
-
+
+
+
+
-
+
@@ -53,35 +56,42 @@
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+