├── .gitignore ├── Changelog.txt ├── LICENSE ├── README.md ├── api ├── aio.py ├── ait.py ├── sqlite.py └── txt.py ├── caesium.def.cfg ├── caesium.py ├── docs ├── formats.md └── mailer.md ├── keys-vi.py ├── keys.py ├── keys_android.patch ├── keys_android.py ├── keys_vi.patch ├── template.txt └── themes ├── default.cfg ├── dos_navigator.cfg ├── norton.cfg ├── spring.cfg └── white.cfg /.gitignore: -------------------------------------------------------------------------------- 1 | caesium.cfg 2 | idec.db 3 | __pycache__ 4 | -------------------------------------------------------------------------------- /Changelog.txt: -------------------------------------------------------------------------------- 1 | Версия 0.4 2 | 3 | Нововведения: 4 | * Подсчёт количества сообщений в конференции ведётся, если её ещё нет в массиве счётчика сообщений при переключениями между нодами или после получения новых сообщений; 5 | * Модули работы с txt или aio базой перенесены в директорию api; 6 | * Добавлена возможность сохранять сообщение в черновики для последующего редактирования без отправке при обмене с нодой. 7 | 8 | Исправленные ошибки: 9 | * Исправлена ошибка в строках получения/отправки почты в умолчальном конфиге; 10 | * Исправлены баги в мейлерах, вызывающие некорректное поведение при их вызове без строки авторизации. 11 | 12 | Версия 0.3 (24.08.2016) 13 | 14 | Нововведения: 15 | * Добавлен скролл-бар, который отображается если сообщение не входит на экран; 16 | * README отформатирован с момощью markdown; 17 | * Добавлена подсветка URL. ВНИМАНИЕ! Необходимо добавить параметр url в файл цветовой схемы; 18 | * Теперь если в конфиге установлена несуществующая тема, то будет загружена тема по умолчанию; 19 | * Добавлена возможность скачивать отсутствующее в базе сообщение (клавиша G по-умолчанию); 20 | * Новый фетчер, максимально оптимизированный для работы с idec (стандарт ii так же поддерживается); 21 | * Отправкой сообщений теперь занимается отдельная утилита sender.py (для работы впаре с фетчером); 22 | * Добавлен мейлер, который совмещает отправку и получение сообщений в одну процедуру; 23 | * Команды вызова фетчера вынесены в конфигурационный файл; 24 | * Убраны вертикальные линии рамки на экране выбора конференции (на два символа больше для полезной информации); 25 | * Переработана статусная строка; 26 | * Количество сообщений теперь отображается в статусной строке, а на их месте располагается описание конференции; 27 | * Определение номера исходящего сообщения теперь основано на количестве исходящих сообщений, а не на счётчике; 28 | * Улучшена поддержка узких терминалов; 29 | * Добавлена поддержка формата базы aio (см. aio_readme.txt); 30 | * Подсчёт количества сообщений в эхах теперь производится только при старте клиента и после работы фетчера; 31 | * Добавлена возможность вызова редактирования конфигурационного файла с экрана выбора конференции (спасибо vit01 за идею); 32 | * Добавлена возможность просмотра msgid и адреса на узких терминалах (спасибо vit01 за патч); 33 | * Добавлен интерфейс для открывания URL в браузере (очередные благодарности vit01). 34 | 35 | Исправленные ошибки: 36 | * Исправлен баг с некорректной работой статичных эхоконференций; 37 | * Исправлен баг, приводивший к падению клиента во время просмотра пыстых сообщений; 38 | * Исправлен баг, приводивший к падению клиента при нажатии клавиши удаления сообщения во время чтения карбонки; 39 | * Исправлены баги с определением последних сообщений в эхоконференции в случае внешней чистки базы; 40 | * Исправлен баг, уводивший курсор за пределы экрана, если эхоконференция с непрочитанными сообщениями на экране выбора не п 41 | омещалась на экран; 42 | * Исправлен баг с применением цветовой схемы, приводивший к неправильному выбору цвета переднего плана курсора, стоящего на 43 | метаэхоконференции favorites; 44 | * Исправлен баг, приводивший к падению клиента, если номер последнего прочитанного сообщения превышал длину индекса эхоконфер 45 | енции; 46 | * Исправлен баг, приводивший к падению клиента при попытке просмотра отсутствующего в базе сообщения; 47 | * Исправлен баг, приводивший к падению клиента при попытке переключения между нодами на экране архивных конференций. 48 | 49 | Версия 0.2 (12.04.2016) 50 | 51 | Нововведения: 52 | * Splashscreen теперь не ждёт нажатия; 53 | * Добавлен параметр stat для конфигурационного файла, который блокирует создание сообщений в эхе и её синхронизацию с нодой, но не помещает эху в архив; 54 | * Цвет gray (grey) снова поддерживается в цветовых схемах; 55 | * Добавлена опция oldquote, включающая старый формат цитирования; 56 | * Добавлена возможность просмотра исходящих сообщений; 57 | * Увеличен отступ на экране отправки сообщений; 58 | * На экране выбора эхоконференции добавлены названия столбов с количеством сообщений и количеством непрочитанных сообщений; 59 | * Новое лого =); 60 | * Добавлено отображение msgid того сообщения, на которое отвечает текущее; 61 | * Добавлена возможность перемещаться по цепочке ответов; 62 | * Параметр to теперь позволяет вводить несколько значений (разделитель — запятая); 63 | * Стандартный конфигурационный файл теперь назван caseium.def.cfg и в случае отсуствия рабочего конфига, копируется этот; 64 | * Название текущей ноды теперь отображается внизу экрана. В правом верхнем углу теперь отображается название столбца "Описание"; 65 | * При ширине терминала < 80 описания эхоконференций скрываются; 66 | * Название ноды теперь отображается в нижнем левом углу при отправке и получении сообщений; 67 | * Добавлена возможность изменять клавиши управления. Все клавиши теперь вынесены в переменные и находятся в файле keys.py; 68 | * Размер сообщения при отображении теперь округляется до двух знаков после запятой; 69 | * Можно задавать несколько клавиш на одно действие; 70 | * В режиме чтения эхоконференции добавлена возможность просмотра темы сообщения в messagebox (в случае, если тема не входит на экран по ширине); 71 | * Messagebox теперь правильнее центрируется на экране; 72 | * Теперь сообщения не попадают в исходящие, если не изменялись в редакторе. 73 | * Удалён старый встроенный фетчер. Теперь используется фетчер из проекта iing. 74 | 75 | Исправленные ошибки: 76 | * Исправлен баг, приводивший к падению клиента при наличии архивных эх в конфиге; 77 | * Исправлен баг с carbonarea и favorites, приводивший к падению клиента; 78 | * Исправлена ошибка при нажатии Page Down в режиме чтения, приводившая к пропуску строки; 79 | * Splashscreen теперь очищает после себя экран; 80 | * При удалении сообщений из избранных, текущее сообщение перечитывается; 81 | * В случае, если нет ни одной архивной эхи, при нажатии Tab на экране выбора эхоконференции теперь цезий не падает; 82 | * Исправлен баг, связанный с использований слешей в параметре nodename; 83 | * Исправлен баг при сохранении новых сообщений, который мог приводить к падению клиента при использовании некоторых редакторов во время сохранения пустого сообщения. Попутно теперь обрезаются пустые строки в конце сообщений; 84 | * Исправлен баг, приводивший к падению при нажатии клавиши удаления в режиме чтения исходящих сообщений; 85 | * Исправлен баг, приводивший к падению клиента при чтении исходящих без указания параметра to в конфиге; 86 | 87 | 88 | Версия 0.1 (13.01.2016) 89 | * Первая фиксированная версия. 90 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Caesium (Цезий) 2 | =============== 3 | 4 | Клиент для ii, написанный на python3 с интерфейсом на ncurses. 5 | 6 | 7 | Конфигурационный файл 8 | --------------------- 9 | 10 | Файл caesium.cfg очень прост по своей структуре и содержит всего несколько параметров: 11 | 12 | * nodename - условное название ноды 13 | * editor - команда вызова текстового редактора 14 | * theme - имя цветовой схемы из директории themes/ без расширения 15 | * nosplash - указание этой опции отключает splash screen при старте клиента 16 | * oldquote - включает старый формат цитирования (не рекомендуется для использования) 17 | * db - формат базы сообщений (txt, aio, ait или sqlite; настоятельно рекомендуется формат ait; sqlite пока в экспериментальном режиме) 18 | * to - имя, по которому клиент будет определять сообщения для помещения в карбонку; имён может быть несколько, указывать их необходимо через запятую без пробела после неё 19 | * node - адрес для работы с нодой 20 | * auth - строка авторизации для отправки сообщений на ноду 21 | * echo - название эхоконференции и описание 22 | * stat - название эхоконференции и описание (эха не попадает в архив, но и не синхронизируется с нодой) 23 | * archive - название и описание эхоконференции в архиве (архивные эхоконференции доступны только для чтения и не синхронизируются с нодой). 24 | * browser - команда запуска веб-браузера для открытия ссылок в сообщениях. 25 | * depth - глубина получения индекса эхоконференций (по-умолчанию 50). 26 | * fdepth - глубина получения индекса файлэхоконференций (по-умолчанию 5). 27 | 28 | Клиент умеет работать с произвольным количеством нод. Описание каждой ноды в конфиге начинается с параметра nodename. Параметр editor можно указывать в произвольном месте конфигурационного файла. 29 | 30 | Пример caesium.cfg: 31 | 32 | ``` 33 | editor nano 34 | nosplash 35 | db aio 36 | 37 | nodename nodeN1 38 | node http://127.0.0.1:62220/ 39 | auth authkey1 40 | to anonymous 41 | 42 | echo im.15 43 | echo linux.15 44 | archive linux.14 45 | 46 | nodename nodeN2 47 | node http://some.node.example/ 48 | auth authkey2 49 | to John Doe 50 | 51 | echo pol.15 52 | echo humor.15 53 | archive pol.15 54 | archive humor.14 55 | ``` 56 | 57 | В этом примере, клиент настроен на работу с двумя нодами. 58 | 59 | 60 | Клавиши управления 61 | ------------------ 62 | 63 | Экран выбора эхоконференции: 64 | 65 | * Курсор вверх/Курсор вниз - выбор эхоконференции 66 | * Page Up - перевести курсор на экран вверх 67 | * Page Down - перевести курсор на экран вниз 68 | * Home - перевести курсор в начало списка 69 | * End - перевести курсор в конец списка 70 | * Enter - перейти к чтению выделенной эхоконференции 71 | * O - просмотр исходящих сообщений 72 | * D - просмотр черновиков 73 | * Tab - переключение между архивным и основным списком эхоконференций 74 | * . - переключение на работу со следующей нодой 75 | * , - переключение на работу с предыдущей нодой 76 | * C - пометить/снять поментку эху для клонирования (см. ниже) 77 | * G - получить новые сообщения с ноды 78 | * E - редактировать файл конфигурации 79 | * F10 - выход из клиента 80 | 81 | Экран чтения эхоконференции: 82 | 83 | * Курсор влево/Курсор вправо - переход между сообщениями 84 | * \- - вернуться на одно сообщение назад в цепочке ответов 85 | * = - вернуться на одно сообщение в цепочке 86 | * Курсор вверх/Курсор вниз - прокрутка сообщения 87 | * Page Up - прокрутка сообщения на экран вверх 88 | * Page Down - прокрутка сообщения на экран вниз 89 | * Home - прокрутка в начало сообщения 90 | * End - прокрутка в конец сообщения 91 | * < - перейти в начало эхоконференции 92 | * \> - перейти в конец эхоконференции 93 | * Esc - выход из режима чтения в режим выбора эхоконференции 94 | * F10 - выход из клиента 95 | * F - пометить сообщение как избранное 96 | * W - сохранить сообщение в файл 97 | * S - показать тему сообщения в messagebox (полезно, если тема не входит в ширину экрана) 98 | * M - показать id сообщения и адрес станции, с которой оно пришло 99 | * I, Ins - написать новое сообщение в текущую эхоконференцию 100 | * Q - ответить на текущее сообщение с цитированием 101 | * V - открыть ссылку или вызвать меню выбора ссылки 102 | * Del - удалить сообщение (работает только при просмотре избранных сообщений) 103 | * L - список сообщений 104 | 105 | Экран чтения исходящих сообщений: 106 | 107 | * E - Редактирование неотправленное сообщение 108 | * D - Перенести текущее сообщение в черновики, если оно не отправлено 109 | 110 | Экран чтения черновиков: 111 | 112 | * O - Перенести текущее сообщение в исходящие 113 | 114 | 115 | Если вы случайно вызвали функцию нового сообщения, то можно просто удалить весь текст, включая заголовок и сохранить файл либо просто закрыть текстовый редактор без сохранения файла. Тогда оно не попадёт в директорию out/. 116 | 117 | На экране выбора эхоконференции перед названием может отображаться знак "+". Он указывает на то, что после последнего сообщения, которое читал пользователь есть ещё сообщения в эхоконференции. 118 | 119 | По умолчанию клиент получает только последние сообщения в эхе (либо столько, сколько указано в параметре depth, если эхоконференции ещё нет в базе). В случае, если есть желание получить полную копию эхоконференции, можно пометить её на клонирование. В этом случае возле названия эхи появится символ "*" и при последующем получении почты клиент получит полную копию эхоконференции. 120 | -------------------------------------------------------------------------------- /api/aio.py: -------------------------------------------------------------------------------- 1 | import os, codecs, sys, time, base64, hashlib 2 | 3 | def get_echo_length(echo): 4 | if os.path.exists("aio/" + echo + ".aio"): 5 | echo_length = sum(1 for l in open("aio/" + echo + ".aio", "r", newline="\n")) 6 | else: 7 | echo_length = 0 8 | return echo_length 9 | 10 | def save_to_favorites(msgid, msg): 11 | if os.path.exists("aio/favorites.aio"): 12 | f = open("aio/favorites.aio", "r").read().split("\n") 13 | favorites = [] 14 | for line in f: 15 | favorites.append(line.split(":")[0]) 16 | else: 17 | favorites = [] 18 | if not msgid in favorites: 19 | codecs.open("aio/favorites.aio", "a", "utf-8").write(msgid + ":" + chr(15).join(msg) + "\n") 20 | return True 21 | else: 22 | return False 23 | 24 | def get_echo_msgids(echo): 25 | if os.path.exists("aio/" + echo + ".aio"): 26 | f = codecs.open("aio/" + echo + ".aio", "r", "utf-8").read().split("\n") 27 | msgids = [] 28 | for line in f: 29 | if len(line) > 0: 30 | msgids.append(line.split(":")[0]) 31 | else: 32 | msgids = [] 33 | return msgids 34 | 35 | def get_carbonarea(): 36 | try: 37 | f = open("aio/carbonarea.aio", "r").read().split("\n") 38 | carbonarea = [] 39 | for line in f: 40 | if len(line.split(":")[0]) == 20: 41 | carbonarea.append(line.split(":")[0]) 42 | return carbonarea 43 | except: 44 | return [] 45 | 46 | def add_to_carbonarea(msgid, msgbody): 47 | if os.path.exists("aio/carbonarea.aio"): 48 | return codecs.open("aio/carbonarea.aio", "a", "utf-8").write(msgid + ":" + chr(15).join(msgbody) + "\n") 49 | else: 50 | return [] 51 | 52 | def save_to_carbonarea(fr, subj, body): 53 | msgbody = ["ii/ok", "carbonarea", str(round(time.time())), fr, "local", "", subj, "", body.replace("\n", chr(15))] 54 | msgid = base64.urlsafe_b64encode(hashlib.sha256("\n".join(msgbody).encode()).digest()).decode("utf-8").replace("-", "A").replace("_", "z")[:20] 55 | codecs.open("aio/carbonarea.aio", "a", "utf-8").write(msgid + ":" + chr(15).join(msgbody) + "\n") 56 | 57 | def save_message(raw, node, to): 58 | for msg in raw: 59 | msgid = msg[0] 60 | msgbody = msg[1] 61 | codecs.open("aio/" + msgbody[1] + ".aio", "a", "utf-8").write(msgid + ":" + chr(15).join(msgbody) + "\n") 62 | if to: 63 | try: 64 | carbonarea = get_carbonarea() 65 | except: 66 | carbonarea = [] 67 | for name in to: 68 | if name in msgbody[5] and not msgid in carbonarea: 69 | add_to_carbonarea(msgid, msgbody) 70 | 71 | def get_favorites_list(): 72 | if os.path.exists("aio/favorites.aio"): 73 | return codecs.open("aio/favorites.aio", "r", "utf-8").read().split("\n") 74 | else: 75 | return [] 76 | 77 | def remove_from_favorites(msgid): 78 | favorites_list = get_favorites_list() 79 | favorites = [] 80 | for item in favorites_list: 81 | if not item.startswith(msgid): 82 | favorites.append(item) 83 | codecs.open("aio/favorites.aio", "w", "utf-8").write("\n".join(favorites)) 84 | 85 | def remove_echoarea(echoarea): 86 | try: 87 | os.remove("aio/%s.aio" % echoarea) 88 | except: 89 | None 90 | 91 | def get_msg_list_data(echoarea): 92 | f = codecs.open("aio/%s.aio" % echoarea, "r", "utf-8").read().split("\n") 93 | lst = [] 94 | for msg in f: 95 | if len(msg) > 1: 96 | rawmsg = msg.split(chr(15)) 97 | lst.append([rawmsg[0].split(":")[0], rawmsg[3], rawmsg[6], time.strftime("%Y.%m.%d", time.gmtime(int(rawmsg[2])))]) 98 | return lst 99 | 100 | def read_msg(msgid, echoarea): 101 | size = "0b" 102 | if os.path.exists("aio/" + echoarea + ".aio") and msgid != "": 103 | index = codecs.open("aio/" + echoarea + ".aio", "r", "utf-8").read().split("\n") 104 | msg = None 105 | for item in index: 106 | if item.startswith(msgid): 107 | msg = ":".join(item.split(":")[1:]).split(chr(15)) 108 | if msg: 109 | size = len ("\n".join(msg).encode("utf-8")) 110 | else: 111 | size = 0 112 | if size < 1024: 113 | size = str(size) + " B" 114 | else: 115 | size = str(format(size / 1024, ".2f")) + " KB" 116 | else: 117 | msg = ["", "", "", "", "", "", "", "", "Сообщение отсутствует в базе"] 118 | return msg, size 119 | -------------------------------------------------------------------------------- /api/ait.py: -------------------------------------------------------------------------------- 1 | import os, codecs, sys, time, base64, hashlib 2 | 3 | def get_echo_length(echo): 4 | if os.path.exists("ait/" + echo + ".iat"): 5 | echo_length = sum(1 for l in open("ait/" + echo + ".iat", "r", newline="\n")) 6 | else: 7 | echo_length = 0 8 | return echo_length 9 | 10 | def save_to_favorites(msgid, msg): 11 | if os.path.exists("ait/favorites.mat"): 12 | f = open("ait/favorites.mat", "r").read().split("\n") 13 | favorites = [] 14 | for line in f: 15 | favorites.append(line.split(":")[0]) 16 | else: 17 | favorites = [] 18 | if not msgid in favorites: 19 | codecs.open("ait/favorites.iat", "a", "utf-8").write(msgid + "\n") 20 | codecs.open("ait/favorites.mat", "a", "utf-8").write(msgid + ":" + chr(15).join(msg) + "\n") 21 | return True 22 | else: 23 | return False 24 | 25 | def get_echo_msgids(echo): 26 | if os.path.exists("ait/" + echo + ".iat"): 27 | f = codecs.open("ait/" + echo + ".iat", "r", "utf-8").read().split("\n") 28 | msgids = [] 29 | for line in f: 30 | if len(line) > 0: 31 | msgids.append(line) 32 | else: 33 | msgids = [] 34 | return msgids 35 | 36 | def get_carbonarea(): 37 | try: 38 | f = open("ait/carbonarea.iat", "r").read().split("\n") 39 | carbonarea = [] 40 | for line in f: 41 | if len(line) > 0: 42 | carbonarea.append(line) 43 | return carbonarea 44 | except: 45 | return [] 46 | 47 | def add_to_carbonarea(msgid, msgbody): 48 | codecs.open("ait/carbonarea.iat", "a", "utf-8").write(msgid + "\n") 49 | codecs.open("ait/carbonarea.mat", "a", "utf-8").write(msgid + ":" + chr(15).join(msgbody) + "\n") 50 | 51 | def save_to_carbonarea(fr, subj, body): 52 | msgbody = ["ii/ok", "carbonarea", str(round(time.time())), fr, "local", "", subj, "", body.replace("\n", chr(15))] 53 | msgid = base64.urlsafe_b64encode(hashlib.sha256("\n".join(msgbody).encode()).digest()).decode("utf-8").replace("-", "A").replace("_", "z")[:20] 54 | open("ait/carbonarea.iat", "a").write(msgid + "\n") 55 | codecs.open("ait/carbonarea.mat", "a", "utf-8").write(msgid + ":" + chr(15).join(msgbody) + "\n") 56 | 57 | def save_message(raw, node, to): 58 | for msg in raw: 59 | msgid = msg[0] 60 | msgbody = msg[1] 61 | codecs.open("ait/" + msgbody[1] + ".iat", "a", "utf-8").write(msgid + "\n") 62 | codecs.open("ait/" + msgbody[1] + ".mat", "a", "utf-8").write(msgid + ":" + chr(15).join(msgbody) + "\n") 63 | if to: 64 | try: 65 | carbonarea = get_carbonarea() 66 | except: 67 | carbonarea = [] 68 | for name in to: 69 | if name in msgbody[5] and not msgid in carbonarea: 70 | add_to_carbonarea(msgid, msgbody) 71 | 72 | def get_favorites_list(): 73 | if os.path.exists("ait/favorites.iat"): 74 | return codecs.open("ait/favorites.iat", "r", "utf-8").read().split("\n")[:-1] 75 | else: 76 | return [] 77 | 78 | def remove_from_favorites(msgid): 79 | favorites_list = get_favorites_list() 80 | favorites = [] 81 | favorites_index = [] 82 | for item in favorites_list: 83 | if not item.startswith(msgid): 84 | favorites.append(item) 85 | favorites_index.append(item.split(":")[0]) 86 | codecs.open("ait/favorites.iat", "w", "utf-8").write("\n".join(favorites_index)) 87 | codecs.open("ait/favorites.mat", "w", "utf-8").write("\n".join(favorites)) 88 | 89 | def remove_echoarea(echoarea): 90 | try: 91 | os.remove("ait/%s.iat" % echoarea) 92 | except: 93 | None 94 | try: 95 | os.remove("ait/%s.mat" % echoarea) 96 | except: 97 | None 98 | 99 | def get_msg_list_data(echoarea): 100 | f = codecs.open("ait/%s.mat" % echoarea, "r", "utf-8").read().split("\n") 101 | lst = [] 102 | for msg in f: 103 | if len(msg) > 1: 104 | rawmsg = msg.split(chr(15)) 105 | lst.append([rawmsg[0].split(":")[0], rawmsg[3], rawmsg[6], time.strftime("%Y.%m.%d", time.gmtime(int(rawmsg[2])))]) 106 | return lst 107 | 108 | def read_msg(msgid, echoarea): 109 | size = "0b" 110 | if os.path.exists("ait/" + echoarea + ".mat") and msgid != "": 111 | index = codecs.open("ait/" + echoarea + ".mat", "r", "utf-8").read().split("\n") 112 | msg = None 113 | for item in index: 114 | if item.startswith(msgid): 115 | msg = ":".join(item.split(":")[1:]).split(chr(15)) 116 | if msg: 117 | size = len ("\n".join(msg).encode("utf-8")) 118 | else: 119 | size = 0 120 | if size < 1024: 121 | size = str(size) + " B" 122 | else: 123 | size = str(format(size / 1024, ".2f")) + " KB" 124 | else: 125 | msg = ["", "", "", "", "", "", "", "", "Сообщение отсутствует в базе"] 126 | return msg, size 127 | -------------------------------------------------------------------------------- /api/sqlite.py: -------------------------------------------------------------------------------- 1 | import sqlite3, time, base64, hashlib 2 | 3 | con = sqlite3.connect("idec.db") 4 | c = con.cursor() 5 | 6 | def get_echo_length(echo): 7 | row = c.execute("SELECT COUNT(1) FROM msg WHERE echoarea = ?;", (echo,)).fetchone() 8 | return row[0] 9 | 10 | def get_echocount(echo): 11 | return get_echo_length(echo) 12 | 13 | def save_to_favorites(msgid, msg): 14 | favoritep = c.execute("SELECT COUNT(1) FROM msg WHERE msgid = ? AND favorites = 1", (msgid,)).fetchone()[0] 15 | if favoritep == 0: 16 | c.execute("UPDATE msg SET favorites = 1 WHERE msgid = ?;", (msgid,)) 17 | con.commit() 18 | return True 19 | else: 20 | return False 21 | 22 | def get_echo_msgids(echo): 23 | msgids = [] 24 | for row in c.execute("SELECT msgid FROM msg WHERE echoarea = ? ORDER BY id;", (echo,)): 25 | if len(row[0]) > 0: 26 | msgids.append(row[0]) 27 | return msgids 28 | 29 | def get_carbonarea(): 30 | msgids = [] 31 | for row in c.execute("SELECT msgid FROM msg WHERE carbonarea = 1 ORDER BY id"): 32 | msgids.append(row[0]) 33 | return msgids 34 | 35 | def add_to_carbonarea(msgid, msgbody): 36 | c.execute("UPDATE msg SET carbonarea = 1 WHERE msgid = ?;", (msgid,)) 37 | con.commit() 38 | 39 | def save_to_carbonarea(fr, subj, body): 40 | msgbody = ["ii/ok", "carbonarea", str(round(time.time())), fr, "local", "", subj, "", body] 41 | msgid = base64.urlsafe_b64encode(hashlib.sha256("\n".join(msgbody).encode()).digest()).decode("utf-8").replace("-", "A").replace("_", "z")[:20] 42 | c.execute("INSERT INTO msg (msgid, tags, echoarea, time, fr, addr, t, subject, body, carbonarea) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", (msgid, msgbody[0], msgbody[1], msgbody[2], msgbody[3], msgbody[4], msgbody[5], msgbody[6], "\n".join(msgbody[7:]), 1)) 43 | con.commit() 44 | 45 | def save_message(raw, node, to): 46 | for msg in raw: 47 | msgid = msg[0] 48 | msgbody = msg[1] 49 | c.execute("INSERT INTO msg (msgid, tags, echoarea, time, fr, addr, t, subject, body) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);", (msgid, msgbody[0], msgbody[1], msgbody[2], msgbody[3], msgbody[4], msgbody[5], msgbody[6], "\n".join(msgbody[7:]))) 50 | con.commit() 51 | for msg in raw: 52 | msgid = msg[0] 53 | msgbody = msg[1] 54 | if to: 55 | try: 56 | carbonarea = get_carbonarea() 57 | except: 58 | carbonarea = [] 59 | for name in to: 60 | if name in msgbody[5] and not msgid in carbonarea: 61 | add_to_carbonarea(msgid, msgbody) 62 | 63 | def get_favorites_list(): 64 | msgids = [] 65 | for row in c.execute("SELECT msgid FROM msg WHERE favorites = 1;"): 66 | msgids.append(row[0]) 67 | return msgids 68 | 69 | def remove_from_favorites(msgid): 70 | c.execute("UPDATE msg SET favorites = 0 WHERE msgid = ?;", (msgid,)) 71 | con.commit() 72 | 73 | def remove_echoarea(echoarea): 74 | c.execute("DELETE FROM msg WHERE echoarea = ?;", (echoarea,)) 75 | con.commit() 76 | 77 | def get_msg_list_data(echoarea): 78 | lst = [] 79 | for row in c.execute("SELECT msgid, fr, subject, time FROM msg WHERE echoarea = ? ORDER BY id;", (echoarea,)): 80 | lst.append([row[0], row[1], row[2], time.strftime("%Y.%m.%d", time.gmtime(int(row[3])))]) 81 | return lst 82 | 83 | def read_msg(msgid, echoarea): 84 | size = "0b" 85 | row = c.execute("SELECT tags, echoarea, time, fr, addr, t, subject, body FROM msg WHERE msgid = ?;", (msgid,)).fetchone() 86 | msg = row[0] + "\n" + row[1] + "\n" + str(row[2]) + "\n" + row[3] + "\n" + row[4] + "\n" + row[5] + "\n" + row[6] + "\n" + row[7] 87 | if msg: 88 | size = len(msg.encode("utf-8")) 89 | else: 90 | size = 0 91 | if size < 1024: 92 | size = str(size) + " B" 93 | else: 94 | size = str(format(size / 1024, ".2f")) + " KB" 95 | return msg.split("\n"), size 96 | 97 | # Create databse 98 | c.execute("""CREATE TABLE IF NOT EXISTS msg( 99 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 100 | msgid TEXT, 101 | favorites INTEGER DEFAULT 0, 102 | carbonarea INTEGER DEFAULT 0, 103 | tags TEXT, 104 | echoarea TEXT, 105 | time INTEGER, 106 | fr TEXT, 107 | addr TEXT, 108 | t TEXT, 109 | subject TEXT, 110 | body TEXT, 111 | UNIQUE (id));""") 112 | c.execute("CREATE INDEX IF NOT EXISTS msgid ON 'msg' ('msgid');") 113 | c.execute("CREATE INDEX IF NOT EXISTS echoarea ON 'msg' ('echoarea');") 114 | c.execute("CREATE INDEX IF NOT EXISTS time ON 'msg' ('time');") 115 | c.execute("CREATE INDEX IF NOT EXISTS subject ON 'msg' ('subject');") 116 | c.execute("CREATE INDEX IF NOT EXISTS body ON 'msg' ('body');") 117 | con.commit() 118 | -------------------------------------------------------------------------------- /api/txt.py: -------------------------------------------------------------------------------- 1 | import os, codecs, time, base64, hashlib 2 | 3 | def get_echo_length(echo): 4 | if os.path.exists("echo/" + echo): 5 | echo_length = len(open ("echo/" + echo, "r").read().split("\n")) - 1 6 | else: 7 | echo_length = 0 8 | return echo_length 9 | 10 | def get_echocount(echoarea): 11 | return len(open("echo/" + echoarea, "r").read().split("\n")) - 1 12 | 13 | def save_to_favorites(msgid, msg): 14 | if os.path.exists("echo/favorites"): 15 | favorites = open("echo/favorites", "r").read().split("\n") 16 | else: 17 | favorites = [] 18 | if not msgid in favorites: 19 | open("echo/favorites", "a").write(msgid + "\n") 20 | return True 21 | else: 22 | return False 23 | 24 | def get_echo_msgids(echo): 25 | if os.path.exists("echo/" + echo): 26 | msgids = open("echo/" + echo, "r").read().split("\n")[:-1] 27 | else: 28 | msgids = [] 29 | return msgids 30 | 31 | def get_carbonarea(): 32 | try: 33 | msgids = [] 34 | for msgid in open("echo/carbonarea", "r").read().split("\n"): 35 | if len(msgid) == 20: 36 | msgids.append(msgid) 37 | return msgids 38 | except: 39 | return [] 40 | 41 | def add_to_carbonarea(msgid, msgbody): 42 | if os.path.exists("echo/carbonarea"): 43 | return codecs.open("echo/carbonarea", "a", "utf-8").write(msgid + "\n") 44 | else: 45 | return [] 46 | 47 | def save_to_carbonarea(fr, subj, body): 48 | msgbody = ["ii/ok", "carbonarea", str(round(time.time())), fr, "local", "", subj, "", body] 49 | msgid = base64.urlsafe_b64encode(hashlib.sha256("\n".join(msgbody).encode()).digest()).decode("utf-8").replace("-", "A").replace("_", "z")[:20] 50 | codecs.open("msg/%s" % msgid, "w", "utf-8").write("\n".join(msgbody)) 51 | open("echo/carbonarea", "a").write(msgid + "\n") 52 | 53 | def save_message(raw, node, to): 54 | try: 55 | carbonarea = get_carbonarea() 56 | except: 57 | carbonarea = [] 58 | for msg in raw: 59 | msgid = msg[0] 60 | msgbody = msg[1] 61 | codecs.open("echo/" + msgbody[1], "a", "utf-8").write(msgid + "\n") 62 | codecs.open("msg/" + msgid, "w", "utf-8").write("\n".join(msgbody)) 63 | if to: 64 | for name in to: 65 | if name in msgbody[5] and not msgid in carbonarea: 66 | add_to_carbonarea(msgid, msgbody) 67 | 68 | def get_favorites_list(): 69 | try: 70 | msgids = [] 71 | for msgid in open("echo/favorites", "r").read().split("\n"): 72 | if len(msgid) == 20: 73 | msgids.append(msgid) 74 | return msgids 75 | except: 76 | return [] 77 | 78 | def remove_from_favorites(msgid): 79 | favorites_list = get_favorites_list() 80 | favorites_list.remove(msgid) 81 | open("echo/favorites", "w").write("\n".join(favorites_list)) 82 | 83 | def remove_echoarea(echoarea): 84 | try: 85 | echoarea = open("echo/%s" % echoarea, "r").read().split("\n") 86 | except: 87 | echoarea = [] 88 | for msgid in echoarea: 89 | try: 90 | os.remove("msg/%s" % msgid) 91 | except: 92 | None 93 | try: 94 | os.remove("echo/%s" % echoarea) 95 | except: 96 | None 97 | 98 | 99 | def read_msg(msgid, echoarea): 100 | size = "0b" 101 | if os.path.exists("msg/" + msgid) and msgid != "": 102 | msg = open("msg/" + msgid, "r").read().split("\n") 103 | size = os.stat("msg/" + msgid).st_size 104 | if size < 1024: 105 | size = str(size) + " B" 106 | else: 107 | size = str(format(size / 1024, ".2f")) + " KB" 108 | else: 109 | msg = ["", "", "", "", "", "", "", "", "Сообщение отсутствует в базе"] 110 | return msg, size 111 | -------------------------------------------------------------------------------- /caesium.def.cfg: -------------------------------------------------------------------------------- 1 | editor nano 2 | theme default 3 | depth 50 4 | 5 | nodename tavern 6 | node http://idec.spline-online.tk/ 7 | 8 | echo pipe.2032 Болталка 9 | echo ii.14 Обсуждение вопросов, связанных с ii 10 | echo newsru.com Новостная лента 11 | -------------------------------------------------------------------------------- /caesium.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import curses, os, urllib.request, urllib.parse, base64, codecs, pickle, time, subprocess, re, hashlib, webbrowser, locale 4 | from datetime import datetime 5 | from shutil import copyfile 6 | from keys import * 7 | 8 | lasts = {} 9 | color_theme = "default" 10 | bold = [False, False, False, False, False, False, False, False, False, False, False, False] 11 | counts = [] 12 | counts_rescan = True 13 | echo_counts = {} 14 | next_echoarea = False 15 | depth = 50 16 | fdepth = 5 17 | messages = [] 18 | twit = [] 19 | 20 | version = "Caesium/0.5 │" 21 | 22 | splash = [ "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀", 23 | "████████ ████████ ████████ ████████ ███ ███ ███ ██████████", 24 | "███ ███ ███ ███ ███ ███ ███ ███ ██ ███", 25 | "███ ████████ ████████ ████████ ███ ███ ███ ███ ██ ███", 26 | "███ ███ ███ ███ ███ ███ ███ ███ ███ ██ ███", 27 | "████████ ████████ ████████ ████████ ███ ████████ ███ ██ ███", 28 | "▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄", 29 | " ncurses ii/idec client v.0.5", 30 | " Andrew Lobanov 01.11.2024"] 31 | 32 | urltemplate=re.compile("((https?|ftp|file)://?[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])") 33 | 34 | def reset_config(): 35 | global nodes, node, editor, oldquote, db 36 | nodes = [] 37 | node = 0 38 | editor = "" 39 | oldquote = False 40 | db = 2 41 | 42 | def check_directories(): 43 | if not os.path.exists("out"): 44 | os.mkdir("out") 45 | for n in nodes: 46 | if not os.path.exists("out/" + n["nodename"]): 47 | os.mkdir("out/" + n["nodename"]) 48 | if db == 0: 49 | if not os.path.exists("echo"): 50 | os.mkdir("echo") 51 | if not os.path.exists("msg"): 52 | os.mkdir("msg") 53 | if not os.path.exists("echo/favorites"): 54 | open("echo/favorites", "w") 55 | if not os.path.exists("echo/carbonarea"): 56 | open("echo/carbonarea", "w") 57 | elif db == 1: 58 | if not os.path.exists("aio"): 59 | os.mkdir("aio") 60 | elif db == 2: 61 | if not os.path.exists("ait"): 62 | os.mkdir("ait") 63 | 64 | def check_config(): 65 | if not os.path.exists("caesium.cfg"): 66 | default_config = open("caesium.def.cfg", "r").read() 67 | open("caesium.cfg","w").write(default_config) 68 | 69 | # 70 | # Взаимодействие с нодой 71 | # 72 | 73 | def separate(l, step=20): 74 | for x in range(0, len(l), step): 75 | yield l[x:x+step] 76 | 77 | def load_config(): 78 | global nodes, editor, color_theme, show_splash, oldquote, db, browser, twit 79 | nodes = [] 80 | first = True 81 | node = {} 82 | echoareas = [] 83 | archive = [] 84 | browser = webbrowser 85 | 86 | config = open("caesium.cfg").read().split("\n") 87 | for line in config: 88 | param = line.split(" ") 89 | if param[0] == "nodename": 90 | if not first: 91 | node["echoareas"] = echoareas 92 | node["archive"] = archive 93 | if not "to" in node: 94 | node["to"] = [] 95 | nodes.append(node) 96 | else: 97 | first = False 98 | node = {} 99 | echoareas = [] 100 | archive = [] 101 | node["nodename"] = " ".join(param[1:]) 102 | elif param[0] == "node": 103 | node["node"] = param[1] 104 | if not node["node"].endswith("/"): 105 | node["node"] = node["node"] + "/" 106 | elif param[0] == "auth": 107 | node["auth"] = param[1] 108 | elif param[0] == "echo": 109 | if len(param) == 2: 110 | echoareas.append([param[1], "", False]) 111 | else: 112 | echoareas.append([param[1], " ".join(param[2:]), False]) 113 | elif param[0] == "stat": 114 | if len(param) == 2: 115 | echoareas.append([param[1], "", True]) 116 | else: 117 | echoareas.append([param[1], " ".join(param[2:]), True]) 118 | elif param[0] == "to": 119 | node["to"] = " ".join(param[1:]).split(",") 120 | elif param[0] == "archive": 121 | if len(param) == 2: 122 | archive.append([param[1], "", True]) 123 | else: 124 | archive.append([param[1], " ".join(param[2:]), True]) 125 | elif param[0] == "editor": 126 | editor = " ".join(param[1:]) 127 | elif param[0] == "theme": 128 | color_theme = param[1] 129 | elif param[0] == "nosplash": 130 | show_splash = False 131 | elif param[0] == "oldquote": 132 | oldquote = True 133 | elif param[0] == "db": 134 | if param[1] == "txt": 135 | db = 0 136 | elif param[1] == "aio": 137 | db = 1 138 | elif param[1] == "ait": 139 | db = 2 140 | elif param[1] == "sqlite": 141 | db = 3 142 | elif param[0] == "browser": 143 | browser = webbrowser.GenericBrowser(param[1]) 144 | elif param[0] == "twit": 145 | twit = param[1].split(",") 146 | 147 | if not "nodename" in node: 148 | node["nodename"] = "untitled node" 149 | if not "to" in node: 150 | node["to"] = [] 151 | node["echoareas"] = echoareas 152 | node["archive"] = archive 153 | nodes.append(node) 154 | for i in range(0, len(nodes)): 155 | nodes[i]["echoareas"].insert(0, ["favorites", "Избранные сообщения", True]) 156 | nodes[i]["echoareas"].insert(1, ["carbonarea", "Карбонка", True]) 157 | 158 | def load_colors(): 159 | global bold 160 | colors = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray"] 161 | params = ["border", "titles", "cursor", "text", "quote1", "quote2", "comment", "url", "header", "statusline", "scrollbar", "origin"] 162 | 163 | try: 164 | theme = open("themes/" + color_theme + ".cfg", "r").read().split("\n") 165 | except: 166 | theme = open("themes/default.cfg", "r").read().split("\n") 167 | for line in theme: 168 | param = line.split(" ") 169 | if len(param) > 1: 170 | if param[1] == "grey": 171 | param[1] = "gray" 172 | if param[0] in params: 173 | fg = colors.index(param[1]) 174 | if param[2] == "default": 175 | bg = -1 176 | else: 177 | bg = colors.index(param[2]) 178 | if param[0] == "border": 179 | curses.init_pair(1, fg, bg) 180 | if len(param) == 4: 181 | bold[0] = True 182 | else: 183 | bold[0] = False 184 | if param[0] == "titles": 185 | curses.init_pair(2, fg, bg) 186 | if len(param) == 4: 187 | bold[1] = True 188 | else: 189 | bold[1] = False 190 | if param[0] == "cursor": 191 | curses.init_pair(3, fg, bg) 192 | if len(param) == 4: 193 | bold[2] = True 194 | else: 195 | bold[2] = False 196 | if param[0] == "text": 197 | curses.init_pair(4, fg, bg) 198 | if len(param) == 4: 199 | bold[3] = True 200 | else: 201 | bold[3] = False 202 | if param[0] == "quote1": 203 | curses.init_pair(5, fg, bg) 204 | if len(param) == 4: 205 | bold[4] = True 206 | else: 207 | bold[4] = False 208 | if param[0] == "quote2": 209 | curses.init_pair(6, fg, bg) 210 | if len(param) == 4: 211 | bold[5] = True 212 | else: 213 | bold[5] = False 214 | if param[0] == "comment": 215 | curses.init_pair(7, fg, bg) 216 | if len(param) == 4: 217 | bold[6] = True 218 | else: 219 | bold[6] = False 220 | if param[0] == "url": 221 | curses.init_pair(8, fg, bg) 222 | if len(param) == 4: 223 | bold[7] = True 224 | else: 225 | bold[7] = False 226 | if param[0] == "statusline": 227 | curses.init_pair(9, fg, bg) 228 | if len(param) == 4: 229 | bold[8] = True 230 | else: 231 | bold[8] = False 232 | if param[0] == "header": 233 | curses.init_pair(10, fg, bg) 234 | if len(param) == 4: 235 | bold[9] = True 236 | else: 237 | bold[9] = False 238 | if param[0] == "scrollbar": 239 | curses.init_pair(11, fg, bg) 240 | if len(param) == 4: 241 | bold[10] = True 242 | else: 243 | bold[10] = False 244 | if param[0] == "origin": 245 | curses.init_pair(12, fg, bg) 246 | if len(param) == 4: 247 | bold[11] = True 248 | else: 249 | bold[11] = False 250 | 251 | def save_out(draft = False): 252 | new = codecs.open("temp", "r", "utf-8").read().strip().replace("\r", "").split("\n") 253 | if len(new) <= 1: 254 | os.remove("temp") 255 | else: 256 | header = new.index("") 257 | if header == 3: 258 | buf = new 259 | elif header == 4: 260 | buf = new[1:5] + ["@repto:%s" % new[0]] + new[5:] 261 | if draft: 262 | codecs.open(outcount() + ".draft", "w", "utf-8").write("\n".join(buf)) 263 | else: 264 | codecs.open(outcount() + ".out", "w", "utf-8").write("\n".join(buf)) 265 | os.remove("temp") 266 | 267 | def resave_out(filename, draft = False): 268 | new = codecs.open("temp", "r", "utf-8").read().strip().split("\n") 269 | if len(new) <= 1: 270 | os.remove("temp") 271 | else: 272 | if draft: 273 | codecs.open("out/" + nodes[node]["nodename"] + "/" + filename.replace(".out", ".draft"), "w", "utf-8").write("\n".join(new)) 274 | else: 275 | codecs.open("out/" + nodes[node]["nodename"] + "/" + filename, "w", "utf-8").write("\n".join(new)) 276 | os.remove("temp") 277 | 278 | def outcount(): 279 | outpath = "out/" + nodes[node]["nodename"] 280 | i = str(len([x for x in os.listdir(outpath) if not x.endswith(".toss")]) + 1) 281 | return outpath + "/%s" % i.zfill(5) 282 | 283 | def get_out_length(drafts = False): 284 | try: 285 | if drafts: 286 | return len([f for f in sorted(os.listdir("out/" + nodes[node]["nodename"])) if f.endswith(".draft")]) - 1 287 | else: 288 | return len([f for f in sorted(os.listdir("out/" + nodes[node]["nodename"])) if f.endswith(".out") or f.endswith(".outmsg")]) - 1 289 | except: 290 | return 0 291 | 292 | def make_toss(): 293 | lst = [x for x in os.listdir("out/" + nodes[node]["nodename"]) if x.endswith(".out")] 294 | for msg in lst: 295 | text = codecs.open("out/" + nodes[node]["nodename"] + "/%s" % msg, "r", "utf-8").read() 296 | coded_text = base64.b64encode(text.encode("utf-8")) 297 | codecs.open("out/" + nodes[node]["nodename"] + "/%s.toss" % msg, "w", "utf-8").write(coded_text.decode("utf-8")) 298 | os.rename("out/" + nodes[node]["nodename"] + "/%s" % msg, "out/" + nodes[node]["nodename"] + "/%s%s" % (msg, "msg")) 299 | 300 | def send_mail(): 301 | lst = [x for x in sorted(os.listdir("out/" + nodes[node]["nodename"])) if x.endswith(".toss")] 302 | max = len(lst) 303 | n = 1 304 | try: 305 | for msg in lst: 306 | print("\rОтправка сообщения: " + str(n) + "/" + str(max), end="") 307 | text = codecs.open("out/" + nodes[node]["nodename"] + "/%s" % msg, "r", "utf-8").read() 308 | data = urllib.parse.urlencode({"tmsg": text,"pauth": nodes[node]["auth"]}).encode("utf-8") 309 | request = urllib.request.Request(nodes[node]["node"] + "u/point") 310 | result = urllib.request.urlopen(request, data).read().decode("utf-8") 311 | if result.startswith("msg ok"): 312 | os.remove("out/" + nodes[node]["nodename"] + "/%s" % msg) 313 | n = n + 1 314 | elif result == "msg big!": 315 | print("\nERROR: very big message (limit 64K)!") 316 | elif result == "auth error!": 317 | print("\nERROR: unknown auth!") 318 | else: 319 | print("\nERROR: unknown error!") 320 | if len(lst) > 0: 321 | print() 322 | except: 323 | print("\nОшибка: не удаётся связаться с нодой.") 324 | 325 | def separate(l, step=40): 326 | for x in range(0, len(l), step): 327 | yield l[x:x+step] 328 | 329 | def get_msg_list(): 330 | msg_list = [] 331 | echoareas = [] 332 | for echoarea in nodes[node]["echoareas"]: 333 | if not echoarea[0] in ["favorites", "carbonarea"]: 334 | echoareas.append(echoarea[0]) 335 | if len(echoareas) > 0: 336 | r = urllib.request.Request(nodes[node]["node"] + "u/e/" + "/".join(echoareas)) 337 | with urllib.request.urlopen(r) as f: 338 | lines = f.read().decode("utf-8").split("\n") 339 | for line in lines: 340 | if len(line) > 0: 341 | msg_list.append(line) 342 | return msg_list 343 | 344 | def get_bundle(node, msgids): 345 | bundle = [] 346 | try: 347 | r = urllib.request.Request(node + "u/m/" + msgids) 348 | with urllib.request.urlopen(r) as f: 349 | bundle = f.read().decode("utf-8").split("\n") 350 | except: 351 | None 352 | return bundle 353 | 354 | def debundle(bundle): 355 | global messages 356 | for msg in bundle: 357 | if msg: 358 | m = msg.split(":") 359 | msgid = m[0] 360 | if len(msgid) == 20 and m[1]: 361 | msgbody = base64.b64decode(m[1].encode("ascii")).decode("utf8").split("\n") 362 | messages.append([msgid, msgbody]) 363 | 364 | if len(messages) >= 1000: 365 | save_message(messages, nodes[node]["node"], nodes[node]["to"]) 366 | messages = [] 367 | 368 | def echo_filter(ea): 369 | rr = re.compile(r'^[a-z0-9_!.-]{1,60}\.[a-z0-9_!.-]{1,60}$') 370 | if rr.match(ea): return True 371 | 372 | def get_mail(): 373 | fetch_msg_list = [] 374 | print("Получение индекса от ноды...") 375 | remote_msg_list = get_msg_list() 376 | print("Построение разностного индекса...") 377 | for line in remote_msg_list: 378 | if echo_filter(line): 379 | local_index = get_echo_msgids(line) 380 | else: 381 | if not line in local_index: 382 | fetch_msg_list.append(line) 383 | msg_list_len = str(len(fetch_msg_list)) 384 | if len(fetch_msg_list) > 0: 385 | count = 0 386 | for get_list in separate(fetch_msg_list): 387 | count = count + len(get_list) 388 | print("\rПолучение сообщений: " + str(count) + "/" + msg_list_len, end="") 389 | debundle(get_bundle(nodes[node]["node"], "/".join(get_list))) 390 | save_message(messages, node, nodes[node]["to"]) 391 | else: 392 | print("Новых сообщений не обнаружено.", end="") 393 | print() 394 | 395 | def mailer(): 396 | global depth, messages 397 | messages = [] 398 | print("Работа с " + nodes[node]["node"]) 399 | if "auth" in nodes[node]: 400 | make_toss() 401 | send_mail() 402 | try: 403 | get_mail() 404 | except: 405 | print("ОШИБКА") 406 | input("Нажмите Enter для продолжения.") 407 | 408 | # 409 | # Пользовательский интерфейс 410 | # 411 | 412 | echo_cursor = 0 413 | archive_cursor = 0 414 | width = 0 415 | height = 0 416 | show_splash = True 417 | 418 | def splash_screen(): 419 | stdscr.clear() 420 | x = int((width - len(splash[1])) / 2) - 1 421 | y = int((height - len(splash)) / 2) 422 | i = 0 423 | for line in splash: 424 | stdscr.addstr(y + i, x, line, curses.color_pair(4)) 425 | i = i + 1 426 | stdscr.refresh() 427 | curses.napms(2000) 428 | stdscr.clear() 429 | 430 | def get_term_size(): 431 | global width, height 432 | height, width = stdscr.getmaxyx() 433 | 434 | def draw_title(y, x, title): 435 | if bold[0]: 436 | color = curses.color_pair(1) + curses.A_BOLD 437 | else: 438 | color = curses.color_pair(1) 439 | stdscr.addstr(y, x, "[", color) 440 | stdscr.addstr(y, x + 1 + len(title), "]", color) 441 | if bold[1]: 442 | color = curses.color_pair(2) + curses.A_BOLD 443 | else: 444 | color = curses.color_pair(2) 445 | stdscr.addstr(y, x + 1, title, curses.color_pair(2) + curses.A_BOLD) 446 | 447 | def draw_status(x, title): 448 | if bold[8]: 449 | color = curses.color_pair(9) + curses.A_BOLD 450 | else: 451 | color = curses.color_pair(9) 452 | stdscr.addstr(height - 1, x, title, color) 453 | 454 | def draw_cursor(y, color): 455 | for i in range (0, width): 456 | stdscr.insstr(y + 1, i, " ", color) 457 | 458 | def current_time(): 459 | draw_status(width - 8, "│ " + datetime.now().strftime("%H:%M")) 460 | 461 | def get_counts(new = False, favorites = False): 462 | global echo_counts 463 | for echoarea in nodes[node]["echoareas"]: 464 | if not new: 465 | if not echoarea[0] in echo_counts: 466 | echo_counts[echoarea[0]] = get_echo_length(echoarea[0]) 467 | else: 468 | echo_counts[echoarea[0]] = get_echo_length(echoarea[0]) 469 | for echoarea in nodes[node]["archive"]: 470 | if not echoarea[0] in echo_counts: 471 | echo_counts[echoarea[0]] = get_echo_length(echoarea[0]) 472 | echo_counts["carbonarea"] = len(get_carbonarea()) 473 | echo_counts["favorites"] = len(get_favorites_list()) 474 | 475 | def rescan_counts(echoareas): 476 | counts = [] 477 | for echo in echoareas: 478 | try: 479 | echocount = echo_counts[echo[0]] 480 | if echo[0] in lasts: 481 | last = echocount - lasts[echo[0]] 482 | if echocount == 0 and lasts[echo[0]] == 0: 483 | last = 1 484 | else: 485 | last = echocount + 1 486 | except: 487 | echocount = 0 488 | last = 1 489 | if last - 1 < 0: 490 | last = 1 491 | counts.append([str(echocount), str(last - 1)]) 492 | return counts 493 | 494 | def draw_echo_selector(start, cursor, archive): 495 | global counts, counts_rescan 496 | dsc_lens = [] 497 | hidedsc = False 498 | m = 0 499 | if bold[0]: 500 | stdscr.attron(curses.color_pair(1)) 501 | stdscr.attron(curses.A_BOLD) 502 | else: 503 | stdscr.attron(curses.color_pair(1)) 504 | for i in range(0, width): 505 | if bold[0]: 506 | color = curses.color_pair(1) + curses.A_BOLD 507 | else: 508 | color = curses.color_pair(1) 509 | stdscr.insstr(0, i, "─", color) 510 | if bold[2]: 511 | color = curses.color_pair(9) + curses.A_BOLD 512 | else: 513 | color = curses.color_pair(9) 514 | stdscr.insstr(height - 1, i, " ", color) 515 | if archive: 516 | echoareas = nodes[node]["archive"] 517 | draw_title(0, 0, "Архив") 518 | else: 519 | echoareas = nodes[node]["echoareas"] 520 | draw_title(0, 0, "Конференция") 521 | draw_status(1, version) 522 | draw_status(len(version) + 2, nodes[node]["nodename"]) 523 | for echo in echoareas: 524 | l = len(echo[1]) 525 | if l > m: 526 | m = l 527 | if m > width - 38: 528 | m = width - 38 529 | dsc_lens.append(l) 530 | y = 0 531 | count = "Сообщений" 532 | unread = "Не прочитано" 533 | description = "Описание" 534 | if width < 80 or m == 0: 535 | m = len(unread) - 7 536 | hidedsc = True 537 | draw_title(0, width + 2 - m - len(count) - len(unread) - 1, count) 538 | draw_title(0, width - 8 - m - 1, unread) 539 | if not hidedsc: 540 | draw_title(0, width - len(description) - 2, description) 541 | for echo in echoareas: 542 | if y - start < height - 2: 543 | if y == cursor: 544 | if y >= start: 545 | if bold[2]: 546 | color = curses.color_pair(3) + curses.A_BOLD 547 | stdscr.attron (curses.color_pair(3)) 548 | stdscr.attron (curses.A_BOLD) 549 | else: 550 | color = curses.color_pair(3) 551 | stdscr.attron (curses.color_pair(3)) 552 | stdscr.attroff (curses.A_BOLD) 553 | draw_cursor(y - start, color) 554 | else: 555 | if y >= start: 556 | if bold[3]: 557 | color = curses.color_pair(4) + curses.A_BOLD 558 | else: 559 | color = curses.color_pair(4) 560 | draw_cursor(y - start, color) 561 | if bold[3]: 562 | stdscr.attron (curses.color_pair(4)) 563 | stdscr.attron (curses.A_BOLD) 564 | else: 565 | stdscr.attron (curses.color_pair(4)) 566 | stdscr.attroff (curses.A_BOLD) 567 | if y + 1 >= start + 1: 568 | if counts_rescan: 569 | counts = rescan_counts(echoareas) 570 | counts_rescan = False 571 | echo_length = int(counts[y][0]) 572 | if echo[0] in lasts: 573 | last = lasts[echo[0]] 574 | else: 575 | last = -1 576 | if last < echo_length - 1 or last == -1 and echo_length == 1: 577 | stdscr.addstr(y + 1 - start, 0, "+") 578 | if last < 0: 579 | last = 0 580 | stdscr.addstr(y + 1 - start, 2, echo[0]) 581 | if width >= 80: 582 | if width - 38 >= len(echo[1]): 583 | stdscr.addstr(y + 1 - start, width - 1 - dsc_lens[y], echo[1], color) 584 | else: 585 | cut_index = width - 38 - len(echo[1]) 586 | stdscr.addstr(y + 1 - start, width - 1 - len(echo[1][:cut_index]), echo[1][:cut_index]) 587 | stdscr.addstr(y + 1 - start, width - 10 - m - len(counts[y][0]), counts[y][0]) 588 | stdscr.addstr(y + 1 - start, width - 2 - m - len(counts[y][1]), counts[y][1]) 589 | y = y + 1 590 | current_time() 591 | stdscr.refresh() 592 | 593 | def find_new(cursor): 594 | ret = cursor 595 | n = 0 596 | lock = False 597 | for i in counts: 598 | n = n + 1 599 | if n > cursor and not lock and int(i[1]) > 0: 600 | ret = n - 1 601 | lock = True 602 | return ret 603 | 604 | def fetch_mail(): 605 | echoareas = [] 606 | to = "" 607 | if len(nodes[node]["to"]) > 0: 608 | to = "\"" + ",".join(nodes[node]["to"]) + "\"" 609 | else: 610 | to = False 611 | d = "txt" 612 | if db == 1: 613 | d = "aio" 614 | elif db == 2: 615 | d = "ait" 616 | elif db == 3: 617 | d = "sqlite" 618 | for echoarea in nodes[node]["echoareas"][2:]: 619 | if not echoarea[2]: 620 | echoareas.append(echoarea[0]) 621 | mailer() 622 | 623 | def load_lasts(): 624 | global lasts 625 | if os.path.exists("lasts.lst"): 626 | f = open("lasts.lst", "rb") 627 | lasts = pickle.load(f) 628 | f.close() 629 | 630 | def edit_config(out = False): 631 | curses.echo() 632 | curses.curs_set(True) 633 | curses.endwin() 634 | p = subprocess.Popen(editor + " ./caesium.cfg", shell=True) 635 | p.wait() 636 | reset_config() 637 | load_config() 638 | stdscr = curses.initscr() 639 | curses.start_color() 640 | curses.use_default_colors() 641 | curses.noecho() 642 | curses.curs_set(False) 643 | stdscr.keypad(True) 644 | get_term_size() 645 | 646 | def echo_selector(): 647 | global echo_cursor, archive_cursor, counts, counts_rescan, next_echoarea, node, stdscr 648 | archive = False 649 | echoareas = nodes[node]["echoareas"] 650 | key = 0 651 | go = True 652 | start = 0 653 | if archive: 654 | cursor = echo_cursor 655 | else: 656 | cursor = archive_cursor 657 | while go: 658 | draw_echo_selector(start, cursor, archive) 659 | key = stdscr.getch() 660 | if key == curses.KEY_RESIZE: 661 | get_term_size() 662 | if cursor >= height - 2: 663 | start = cursor - height + 3 664 | if cursor - start <= 0: 665 | start = cursor 666 | if start > 0 and height - 2 > len(echoareas): 667 | start = 0 668 | stdscr.clear() 669 | elif key in s_up and cursor > 0: 670 | cursor = cursor - 1 671 | if cursor - start < 0 and start > 0: 672 | start = start - 1 673 | elif key in s_down and cursor < len(echoareas) - 1: 674 | cursor = cursor + 1 675 | if cursor - start > height - 3 and start < len(echoareas) - height + 2: 676 | start = start + 1 677 | elif key in s_ppage: 678 | cursor = cursor - height + 2 679 | if cursor < 0: 680 | cursor = 0 681 | if cursor - start < 0 and start > 0: 682 | start = start - height + 2 683 | if start < 0: 684 | start = 0 685 | elif key in s_npage: 686 | cursor = cursor + height - 2 687 | if cursor >= len(echoareas): 688 | cursor = len(echoareas) - 1 689 | if cursor - start > height - 3: 690 | start = start + height - 2 691 | if start > len(echoareas) - height + 2: 692 | start = len(echoareas) - height + 2 693 | elif key in s_home: 694 | cursor = 0 695 | start = 0 696 | elif key in s_end: 697 | cursor = len(echoareas) - 1 698 | if len(echoareas) >= height - 2: 699 | start = len(echoareas) - height + 2 700 | elif key in s_get: 701 | curses.echo() 702 | curses.curs_set(True) 703 | curses.endwin() 704 | os.system('cls' if os.name == 'nt' else 'clear') 705 | fetch_mail() 706 | stdscr = curses.initscr() 707 | curses.start_color() 708 | curses.use_default_colors() 709 | curses.noecho() 710 | curses.curs_set(False) 711 | stdscr.keypad(True) 712 | get_term_size() 713 | draw_message_box("Подождите", False) 714 | get_counts(True) 715 | stdscr.clear() 716 | counts = rescan_counts(echoareas) 717 | cursor = find_new(0) 718 | if cursor >= height - 2: 719 | start = cursor - height + 3 720 | if cursor - start <= 0: 721 | start = cursor 722 | elif key in s_archive and len(nodes[node]["archive"]) > 0: 723 | if archive: 724 | archive = False 725 | archive_cursor = cursor 726 | cursor = echo_cursor 727 | echoareas = nodes[node]["echoareas"] 728 | stdscr.clear() 729 | counts_rescan = True 730 | else: 731 | archive = True 732 | echo_cursor = cursor 733 | cursor = archive_cursor 734 | echoareas = nodes[node]["archive"] 735 | stdscr.clear() 736 | counts_rescan = True 737 | elif key in s_enter: 738 | draw_message_box("Подождите", False) 739 | if echoareas[cursor][0] in lasts: 740 | last = lasts[echoareas[cursor][0]] 741 | else: 742 | last = 0 743 | if cursor == 0: 744 | echo_length = len(get_favorites_list()) 745 | elif cursor == 1: 746 | echo_length = len(get_carbonarea()) 747 | else: 748 | echo_length = get_echo_length(echoareas[cursor][0]) 749 | if last > 0 and last < echo_length: 750 | last = last + 1 751 | if last >= echo_length: 752 | last = echo_length 753 | if cursor == 1: 754 | go = not echo_reader(echoareas[cursor], last, archive, True, False, True) 755 | elif cursor == 0 or echoareas[cursor][2]: 756 | go = not echo_reader(echoareas[cursor], last, archive, True, False, False) 757 | else: 758 | go = not echo_reader(echoareas[cursor], last, archive, False, False, False) 759 | counts_rescan = True 760 | if next_echoarea: 761 | counts = rescan_counts(echoareas) 762 | cursor = find_new(cursor) 763 | if cursor - start > height - 3: 764 | start = cursor - height + 3 765 | next_echoarea = False 766 | elif key in s_out: 767 | out_length = get_out_length() 768 | if out_length > -1: 769 | go = not echo_reader("out", out_length, archive, False, True, False) 770 | elif key in s_drafts: 771 | out_length = get_out_length(True) 772 | if out_length > -1: 773 | go = not echo_reader("out", out_length, archive, False, True, False, True) 774 | elif key in s_nnode: 775 | archive = False 776 | node = node + 1 777 | if node == len(nodes): 778 | node = 0 779 | echoareas = nodes[node]["echoareas"] 780 | draw_message_box("Подождите", False) 781 | get_counts() 782 | stdscr.clear() 783 | counts_rescan = True 784 | cursor = 0 785 | start = 0 786 | elif key in s_pnode: 787 | archive = False 788 | node = node - 1 789 | if node == -1: 790 | node = len(nodes) - 1 791 | echoareas = nodes[node]["echoareas"] 792 | draw_message_box("Подождите", False) 793 | get_counts() 794 | stdscr.clear() 795 | counts_rescan = True 796 | cursor = 0 797 | start = 0 798 | elif key in s_config: 799 | edit_config() 800 | reset_config() 801 | load_config() 802 | load_colors() 803 | get_counts() 804 | stdscr.clear() 805 | counts_rescan = True 806 | node = 0 807 | archive = False 808 | echoareas = nodes[node]["echoareas"] 809 | cursor = 0 810 | elif key in g_quit: 811 | go = False 812 | if archive: 813 | archive_cursor = cursor 814 | else: 815 | echo_cursor = cursor 816 | 817 | def read_out_msg(msgid): 818 | size = "0b" 819 | temp = open("out/" + nodes[node]["nodename"] + "/" + msgid, "r").read().split("\n") 820 | msg = [] 821 | msg.append("") 822 | msg.append(temp[0]) 823 | msg.append("") 824 | msg.append("") 825 | msg.append("") 826 | msg.append(temp[1]) 827 | msg.append(temp[2]) 828 | for line in temp[3:]: 829 | if not(line.startswith("@repto:")): 830 | msg.append(line) 831 | size = os.stat("out/" + nodes[node]["nodename"] + "/" + msgid).st_size 832 | if size < 1024: 833 | size = str(size) + " B" 834 | else: 835 | size = str(int(size / 1024 * 10) / 10) + " KB" 836 | return msg, size 837 | 838 | def body_render(tbody): 839 | body = "" 840 | code = "" 841 | sep = "" 842 | for i in range(0, width - 1): 843 | sep += "─" 844 | for line in tbody: 845 | n = 0 846 | rr = re.compile(r"^[a-zA-Zа-яА-Я0-9_\-.\(\)]{0,20}>{1,20}") 847 | cc = re.compile(r"(^\s*)(PS|P.S|ps|ЗЫ|З.Ы|\/\/|#)") 848 | try: 849 | count = line[0:rr.match(line).span()[1]].count(">") 850 | except: 851 | count = 0 852 | if count > 0: 853 | if count % 2 == 1: 854 | code = chr(15) 855 | elif count % 2 == 0: 856 | code = chr(16) 857 | elif cc.match(line): 858 | code = chr(17) 859 | elif line.startswith("== "): 860 | code = chr(18) 861 | else: 862 | code = " " 863 | if line == "----": 864 | code = chr(17) 865 | line = sep 866 | if line.startswith("+++"): 867 | code = chr(19) 868 | if code != " " and code != chr(17) and code != chr(18) and code != chr(19): 869 | line = " " + line 870 | body = body + code 871 | for word in line.split(" "): 872 | if n + len(word) < width: 873 | n = n + len(word) 874 | body = body + word 875 | if not word[-1:] == "\n": 876 | n = n + 1 877 | body = body + " " 878 | else: 879 | body = body[:-1] 880 | if len(word) < width: 881 | body = body + "\n" + code + word 882 | n = len (word) 883 | else: 884 | chunks, chunksize = len(word), width - 1 885 | chunk_list = [ word[i:i+chunksize] for i in range(0, chunks, chunksize) ] 886 | for line in chunk_list: 887 | body = body + "\n" + code + line 888 | n = len(chunk_list[-1]) 889 | if not word[-1:] == "\n": 890 | n = n + 1 891 | body = body + " " 892 | if body.endswith(" "): 893 | body = body[:-1] 894 | body = body + "\n" 895 | return body.split("\n") 896 | 897 | def draw_reader(echo, msgid, out): 898 | for i in range(0, width): 899 | if bold[0]: 900 | color = curses.color_pair(1) + curses.A_BOLD 901 | else: 902 | color = curses.color_pair(1) 903 | stdscr.insstr(0, i, "─", color) 904 | stdscr.insstr(4, i, "─", color) 905 | if bold[2]: 906 | color = curses.color_pair(9) + curses.A_BOLD 907 | else: 908 | color = curses.color_pair(9) 909 | stdscr.insstr(height - 1, i, " ", color) 910 | if out: 911 | draw_title(0, 0, echo) 912 | if msgid.endswith(".out"): 913 | ns = "не отправлено" 914 | draw_title(4, width - len(ns) - 2, ns) 915 | else: 916 | if width >= 80: 917 | draw_title(0, 0, echo + " / " + msgid) 918 | else: 919 | draw_title(0, 0, echo) 920 | draw_status(1, version) 921 | current_time() 922 | for i in range(0, 3): 923 | draw_cursor(i, 1) 924 | if bold[1]: 925 | color = curses.color_pair(2) + curses.A_BOLD 926 | else: 927 | color = curses.color_pair(2) 928 | stdscr.addstr(1, 1, "От: ", color) 929 | stdscr.addstr(2, 1, "Кому: ", color) 930 | stdscr.addstr(3, 1, "Тема: ", color) 931 | 932 | 933 | def call_editor(out = False, draft = False): 934 | curses.echo() 935 | curses.curs_set(True) 936 | curses.endwin() 937 | h = hashlib.sha1(str.encode(open("temp", "r",).read())).hexdigest() 938 | p = subprocess.Popen(editor + " ./temp", shell=True) 939 | p.wait() 940 | stdscr = curses.initscr() 941 | curses.start_color() 942 | curses.use_default_colors() 943 | curses.noecho() 944 | curses.curs_set(False) 945 | stdscr.keypad(True) 946 | get_term_size() 947 | if h != hashlib.sha1(str.encode(open("temp", "r",).read())).hexdigest(): 948 | d = menu("Куда сохранить?", ["Сохранить в исходящие", "Сохранить как черновик"]) 949 | if d: 950 | if d == 2: 951 | if not out: 952 | save_out(True) 953 | else: 954 | if out.endswith(".out"): 955 | try: 956 | os.remove("out/" + nodes[node]["nodename"] + "/" + out) 957 | except: 958 | None 959 | resave_out(out, True) 960 | elif d == 1: 961 | if not out: 962 | save_out() 963 | else: 964 | if out.endswith(".draft"): 965 | try: 966 | os.remove("out/" + nodes[node]["nodename"] + "/" + out) 967 | except: 968 | None 969 | resave_out(out.replace(".draft", ".out")) 970 | else: 971 | os.remove("temp") 972 | 973 | def draw_message_box(smsg, wait): 974 | maxlen = 0 975 | msg = smsg.split("\n") 976 | for line in msg: 977 | if len(line) > maxlen: 978 | maxlen = len(line) 979 | if wait: 980 | msgwin = curses.newwin(len(msg) + 4, maxlen + 2, int(height / 2 - 2) , int(width / 2 - maxlen / 2 - 2)) 981 | else: 982 | msgwin = curses.newwin(len(msg) + 2, maxlen + 2, int(height / 2 - 2) , int(width / 2 - maxlen / 2 - 2)) 983 | if bold[0]: 984 | msgwin.attron(curses.color_pair(1)) 985 | msgwin.attron(curses.A_BOLD) 986 | else: 987 | msgwin.attron(curses.color_pair(1)) 988 | msgwin.bkgd(' ', curses.color_pair(1)) 989 | msgwin.border() 990 | 991 | i = 1 992 | if bold[3]: 993 | color = curses.color_pair(4) + curses.A_BOLD 994 | else: 995 | color = curses.color_pair(4) 996 | for line in msg: 997 | msgwin.addstr(i, 1, line, color) 998 | i = i + 1 999 | if bold[1]: 1000 | color = curses.color_pair(2) + curses.A_BOLD 1001 | else: 1002 | color = curses.color_pair(2) 1003 | if wait: 1004 | msgwin.addstr(len(msg) + 2, int((maxlen + 2 - 21) / 2), "Нажмите любую клавишу", color) 1005 | msgwin.refresh() 1006 | 1007 | def message_box(smsg): 1008 | draw_message_box(smsg, True) 1009 | stdscr.getch() 1010 | stdscr.clear() 1011 | 1012 | def save_message_to_file(msgid, echoarea): 1013 | msg, size = read_msg(msgid, echoarea) 1014 | f = open(msgid + ".txt", "w") 1015 | f.write("== " + msg[1] + " ==================== " + str(msgid) + "\n") 1016 | f.write("От: " + msg[3] + " (" + msg[4] + ")\n") 1017 | f.write("Кому: " + msg[5] + "\n") 1018 | f.write("Тема: " + msg[6] + "\n") 1019 | f.write("\n".join(msg[7:])) 1020 | f.close 1021 | message_box("Сообщение сохранено в файл\n" + str(msgid) + ".txt") 1022 | 1023 | def get_out_msgids(drafts = False): 1024 | msgids = [] 1025 | not_sended = [] 1026 | if os.path.exists("out/" + nodes[node]["nodename"]): 1027 | if drafts: 1028 | msgids = [f for f in sorted(os.listdir("out/" + nodes[node]["nodename"])) if f.endswith(".draft")] 1029 | else: 1030 | msgids = [f for f in sorted(os.listdir("out/" + nodes[node]["nodename"])) if f.endswith(".out") or f.endswith(".outmsg")] 1031 | return msgids 1032 | 1033 | def quote(to): 1034 | if oldquote == True: 1035 | return "" 1036 | else: 1037 | if len(to) == 1: 1038 | q = to[0] 1039 | else: 1040 | q = "" 1041 | for word in to: 1042 | q = q + word[0] 1043 | return q 1044 | 1045 | def show_subject(subject): 1046 | if len(subject) > width - 8: 1047 | msg = "" 1048 | line = "" 1049 | for word in subject.split(" "): 1050 | if len(line + word) <= width - 4: 1051 | line = line + word + " " 1052 | else: 1053 | msg = msg + line + "\n" 1054 | line = word + " " 1055 | msg = msg + line 1056 | message_box(msg) 1057 | 1058 | def calc_scrollbar_size(length): 1059 | if length > 0: 1060 | scrollbar_size = round((height - 6) * (height - 6) / length + 0.49) 1061 | if scrollbar_size < 1: 1062 | scrollbar_size = 1 1063 | else: 1064 | scrollbar_size = 1 1065 | return scrollbar_size 1066 | 1067 | def set_attr(str): 1068 | if str == chr(15): 1069 | stdscr.attron(curses.color_pair(5)) 1070 | if bold[4]: 1071 | stdscr.attron(curses.A_BOLD) 1072 | else: 1073 | stdscr.attroff(curses.A_BOLD) 1074 | elif str == chr(16): 1075 | stdscr.attron(curses.color_pair(6)) 1076 | if bold[5]: 1077 | stdscr.attron(curses.A_BOLD) 1078 | else: 1079 | stdscr.attroff(curses.A_BOLD) 1080 | elif str == chr(17): 1081 | stdscr.attron(curses.color_pair(7)) 1082 | if bold[6]: 1083 | stdscr.attron(curses.A_BOLD) 1084 | else: 1085 | stdscr.attroff(curses.A_BOLD) 1086 | elif str == chr(18): 1087 | stdscr.attron(curses.color_pair(10)) 1088 | if bold[9]: 1089 | stdscr.attron(curses.A_BOLD) 1090 | else: 1091 | stdscr.attroff(curses.A_BOLD) 1092 | elif str == chr(19): 1093 | stdscr.attron(curses.color_pair(12)) 1094 | if bold[11]: 1095 | stdscr.attron(curses.A_BOLD) 1096 | else: 1097 | stdscr.attroff(curses.A_BOLD) 1098 | else: 1099 | stdscr.attron(curses.color_pair(4)) 1100 | if bold[3]: 1101 | stdscr.attron(curses.A_BOLD) 1102 | else: 1103 | stdscr.attroff(curses.A_BOLD) 1104 | 1105 | def get_msg(msgid): 1106 | r = urllib.request.Request(nodes[node]["node"] + "u/m/" + msgid) 1107 | with urllib.request.urlopen(r) as f: 1108 | bundle = f.read().decode("utf-8").split("\n") 1109 | for msg in bundle: 1110 | if msg: 1111 | m = msg.split(":") 1112 | msgid = m[0] 1113 | if len(msgid) == 20 and m[1]: 1114 | msgbody = base64.b64decode(m[1].encode("ascii")).decode("utf8") 1115 | if len(nodes[node]["to"]) > 0: 1116 | carbonarea = get_carbonarea() 1117 | if msgbody.split("\n")[5] in nodes[node]["to"] and not msgid in carbonarea: 1118 | add_to_carbonarea(msgid, msbbody) 1119 | save_message(msgid, msgbody) 1120 | 1121 | def menu(title, items): 1122 | h = len(items) 1123 | w = 0 1124 | for item in items: 1125 | if len(item) > w: 1126 | w = len(item) 1127 | if len(item) > width - 2: 1128 | item = item[:width - 1] 1129 | if w >= width - 3: 1130 | w = width - 3 1131 | e = "Esc - отмена" 1132 | if w < len(title): 1133 | w = len(title) + 2 1134 | menu_win = curses.newwin(h + 2, w + 2, int(height / 2 - h / 2 - 2) , int(width / 2 - w / 2 - 2)) 1135 | if bold[0]: 1136 | menu_win.attron(curses.color_pair(1)) 1137 | menu_win.attron(curses.A_BOLD) 1138 | else: 1139 | menu_win.attron(curses.color_pair(1)) 1140 | menu_win.border() 1141 | if bold[0]: 1142 | color = curses.color_pair(1) + curses.A_BOLD 1143 | else: 1144 | color = curses.color_pair(1) 1145 | menu_win.addstr(0, 1, "[", color) 1146 | menu_win.addstr(0, 2 + len(title), "]", color) 1147 | menu_win.addstr(h + 1, 1, "[", color) 1148 | menu_win.addstr(h + 1, 2 + len(e), "]", color) 1149 | if bold[1]: 1150 | color = curses.color_pair(2) + curses.A_BOLD 1151 | else: 1152 | color = curses.color_pair(2) 1153 | menu_win.addstr(0, 2, title, curses.color_pair(2) + curses.A_BOLD) 1154 | menu_win.addstr(h + 1, 2, e, curses.color_pair(2) + curses.A_BOLD) 1155 | if bold[0]: 1156 | color = curses.color_pair(1) + curses.A_BOLD 1157 | else: 1158 | color = curses.color_pair(1) 1159 | y = 1 1160 | quit = False 1161 | cancel = False 1162 | while not quit: 1163 | i = 1 1164 | for item in items: 1165 | if i == y : 1166 | if bold[2]: 1167 | color = curses.color_pair(3) + curses.A_BOLD 1168 | else: 1169 | color = curses.color_pair(3) 1170 | for x in range(1, w + 1): 1171 | menu_win.addstr(i, x, " ", color) 1172 | else: 1173 | if bold[3]: 1174 | color = curses.color_pair(4) + curses.A_BOLD 1175 | else: 1176 | color = curses.color_pair(4) 1177 | for x in range(1, w + 1): 1178 | menu_win.addstr(i, x, " ", color) 1179 | if len(item) < w - 2: 1180 | menu_win.addstr(i, 1, item, color) 1181 | else: 1182 | menu_win.addstr(i, 1, item[:w], color) 1183 | i = i + 1 1184 | menu_win.refresh() 1185 | key = stdscr.getch() 1186 | if key in r_up: 1187 | if y > 1: 1188 | y -= 1 1189 | else: 1190 | y = h 1191 | elif key in r_down: 1192 | if y < h: 1193 | y += 1 1194 | else: 1195 | y = 1 1196 | elif key in s_enter: 1197 | quit = True 1198 | elif key in r_quit: 1199 | cancel = True 1200 | quit = True 1201 | if cancel: 1202 | return False 1203 | else: 1204 | return y 1205 | 1206 | def open_link(link): 1207 | global browser 1208 | browser.open(link) 1209 | 1210 | def get_out(drafts=False): 1211 | if drafts: 1212 | return get_out_msgids(True) 1213 | else: 1214 | return get_out_msgids() 1215 | 1216 | def echo_reader(echo, last, archive, favorites, out, carbonarea, drafts = False): 1217 | global lasts, next_echoarea 1218 | stdscr.clear() 1219 | if bold[0]: 1220 | stdscr.attron(curses.color_pair(1)) 1221 | stdscr.attron(curses.A_BOLD) 1222 | else: 1223 | stdscr.attron(curses.color_pair(1)) 1224 | y = 0 1225 | msgn = last 1226 | key = 0 1227 | if drafts: 1228 | msgids = get_out_msgids(True) 1229 | elif out: 1230 | msgids = get_out_msgids() 1231 | elif favorites and not carbonarea: 1232 | msgids = get_favorites_list() 1233 | elif carbonarea: 1234 | msgids = get_carbonarea() 1235 | else: 1236 | msgids = get_echo_msgids(echo[0]) 1237 | if msgn > len(msgids) - 1: 1238 | msgn = len(msgids) - 1 1239 | if len(msgids) > 0: 1240 | if drafts: 1241 | msg, size = read_out_msg(msgids[msgn]) 1242 | elif out: 1243 | msg, size = read_out_msg(msgids[msgn]) 1244 | else: 1245 | msg, size = read_msg(msgids[msgn], echo[0]) 1246 | while msg[3] in twit or msg[5] in twit: 1247 | msgn -= 1 1248 | if msgn < 0: 1249 | go = False 1250 | quit = False 1251 | next_echoarea = True 1252 | break 1253 | msg, size = read_msg(msgids[msgn], echo[0]) 1254 | 1255 | else: 1256 | msg = ["", "", "", "", "", "", "", "", "Сообщение отсутствует в базе"] 1257 | size = "0b" 1258 | msgbody = body_render(msg[8:]) 1259 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1260 | go = True 1261 | stack = [] 1262 | while go: 1263 | if len(msgids) > 0: 1264 | draw_reader(msg[1], msgids[msgn], out) 1265 | if width >= 80: 1266 | msg_string = "Сообщение " + str(msgn + 1) + " из " + str(len(msgids)) + " (" + str(len(msgids) - msgn - 1) + " осталось)" 1267 | else: 1268 | msg_string = str(msgn + 1) + "/" + str(len(msgids)) + " [" + str(len(msgids) - msgn - 1) + "]" 1269 | draw_status(len(version) + 2, msg_string) 1270 | if drafts: 1271 | dsc = "Черновики" 1272 | elif out: 1273 | dsc = "Исходящие" 1274 | else: 1275 | dsc = echo[1] 1276 | if len(dsc) > 0 and width >= 80: 1277 | draw_title(0, width - 2 - len(dsc), dsc) 1278 | if not(out): 1279 | try: 1280 | if width >= 80: 1281 | msgtime = time.strftime("%d %b %Y %H:%M UTC", time.gmtime(int(msg[2]))) 1282 | else: 1283 | msgtime = time.strftime("%d.%m.%y %H:%M", time.gmtime(int(msg[2]))) 1284 | except: 1285 | msgtime = "" 1286 | if bold[3]: 1287 | color = curses.color_pair(4) + curses.A_BOLD 1288 | else: 1289 | color = curses.color_pair(4) 1290 | if not(out): 1291 | if width >= 80: 1292 | stdscr.addstr(1, 7, msg[3] + " (" + msg[4] + ")", color) 1293 | else: 1294 | stdscr.addstr(1, 7, msg[3], color) 1295 | stdscr.addstr(1, width - len(msgtime) - 1, msgtime, color) 1296 | else: 1297 | if len(nodes[node]["to"]) > 0: 1298 | stdscr.addstr(1, 7, nodes[node]["to"][0], color) 1299 | stdscr.addstr(2, 7, msg[5], color) 1300 | stdscr.addstr(3, 7, msg[6][:width - 8], color) 1301 | draw_title(4, 0, size) 1302 | tags = msg[0].split("/") 1303 | if "repto" in tags and 36 + len(size) < width: 1304 | repto = tags[tags.index("repto") + 1] 1305 | draw_title(4, len(size) + 3, "Ответ на " + repto) 1306 | else: 1307 | repto = False 1308 | for i in range (0, height - 6): 1309 | for x in range (0, width): 1310 | stdscr.addstr(i + 5, x, " ", 1) 1311 | if i < len(msgbody) - 1: 1312 | if y + i < len(msgbody) and len(msgbody[y+i]) > 0: 1313 | set_attr(msgbody[y + i][0]) 1314 | x = 0 1315 | for word in msgbody[y + i][1:].split(" "): 1316 | if word.startswith("http://") or word.startswith("https://") or word.startswith("ftp://"): 1317 | stdscr.attron(curses.color_pair(8)) 1318 | if bold[7]: 1319 | stdscr.attron(curses.A_BOLD) 1320 | else: 1321 | stdscr.attroff(curses.A_BOLD) 1322 | stdscr.addstr(i + 5, x, word) 1323 | set_attr(msgbody[y + i][0]) 1324 | else: 1325 | stdscr.addstr(i + 5, x, word) 1326 | x += len(word) + 1 1327 | stdscr.attron(curses.color_pair(11)) 1328 | if bold[10]: 1329 | stdscr.attron(curses.A_BOLD) 1330 | else: 1331 | stdscr.attroff(curses.A_BOLD) 1332 | if len(msgbody) > height - 5: 1333 | for i in range(5, height - 1): 1334 | stdscr.addstr(i, width - 1, "░") 1335 | scrollbar_y = round(y * (height - 6) / len(msgbody) + 0.49) 1336 | if scrollbar_y < 0: 1337 | scrollbar_y = 0 1338 | elif scrollbar_y > height - 6 - scrollbar_size or y >= len(msgbody) - (height - 6): 1339 | scrollbar_y = height - 6 - scrollbar_size 1340 | for i in range(scrollbar_y + 5, scrollbar_y + 5 + scrollbar_size): 1341 | if i < height - 1: 1342 | stdscr.addstr(i, width - 1, "█") 1343 | else: 1344 | draw_reader(echo[0], "", out) 1345 | stdscr.attron(curses.color_pair(1)) 1346 | if bold[0]: 1347 | stdscr.attron(curses.A_BOLD) 1348 | else: 1349 | stdscr.attroff(curses.A_BOLD) 1350 | stdscr.refresh() 1351 | key = stdscr.getch() 1352 | if key == curses.KEY_RESIZE: 1353 | y = 0 1354 | get_term_size() 1355 | if len(msgids) > 0: 1356 | msgbody = body_render(msg[8:]) 1357 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1358 | stdscr.clear() 1359 | elif key in r_prev and msgn > 0: 1360 | y = 0 1361 | if len(msgids) > 0: 1362 | msgn = msgn - 1 1363 | if len(stack) > 0: 1364 | stack = [] 1365 | if out: 1366 | msg, size = read_out_msg(msgids[msgn]) 1367 | else: 1368 | msg, size = read_msg(msgids[msgn], echo[0]) 1369 | tmp = msgn 1370 | while msg[3] in twit or msg[5] in twit: 1371 | msgn -= 1 1372 | if msgn < 0: 1373 | msgn = tmp + 1 1374 | break 1375 | msg, size = read_msg(msgids[msgn], echo[0]) 1376 | msgbody = body_render(msg[8:]) 1377 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1378 | elif key in r_next and msgn < len(msgids) - 1: 1379 | y = 0 1380 | if len(msgids) > 0: 1381 | msgn = msgn +1 1382 | if len(stack) > 0: 1383 | stack = [] 1384 | if out: 1385 | msg, size = read_out_msg(msgids[msgn]) 1386 | else: 1387 | msg, size = read_msg(msgids[msgn], echo[0]) 1388 | while msg[3] in twit or msg[5] in twit: 1389 | msgn += 1 1390 | if msgn >= len(msgids) or len(msgids) == 0: 1391 | go = False 1392 | quit = False 1393 | next_echoarea = True 1394 | break 1395 | msg, size = read_msg(msgids[msgn], echo[0]) 1396 | msgbody = body_render(msg[8:]) 1397 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1398 | elif key in r_next and (msgn == len(msgids) - 1 or len(msgids) == 0): 1399 | go = False 1400 | quit = False 1401 | next_echoarea = True 1402 | elif key in r_prep and not echo[0] == "carbonarea" and not echo[0] == "favorites" and not out and repto: 1403 | if repto in msgids: 1404 | stack.append(msgn) 1405 | msgn = msgids.index(repto) 1406 | msg, size = read_msg(msgids[msgn], echo[0]) 1407 | msgbody = body_render(msg[8:]) 1408 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1409 | elif key in r_nrep and not out and len(stack) > 0: 1410 | msgn = stack.pop() 1411 | msg, size = read_msg(msgids[msgn], echo[0]) 1412 | msgbody = body_render(msg[8:]) 1413 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1414 | elif key in r_up and y > 0: 1415 | if len(msgids) > 0: 1416 | y = y - 1 1417 | elif key in r_ppage: 1418 | if len(msgids) > 0: 1419 | y = y - height + 6 1420 | if y < 0: 1421 | y = 0 1422 | elif key in r_npage: 1423 | if y < len(msgbody) - height + 5: 1424 | if len(msgids) > 0 and len(msgbody) > height - 5: 1425 | y = y + height - 6 1426 | elif key in r_home: 1427 | if len(msgids) > 0: 1428 | y = 0 1429 | elif key in r_mend: 1430 | if len(msgids) > 0 and len(msgbody) > height - 5: 1431 | y = len(msgbody) - height + 5 1432 | elif key in r_ukeys: 1433 | if len(msgids) == 0 or y >= len(msgbody) - height + 5: 1434 | y = 0 1435 | if msgn == len(msgids) - 1 or len(msgids) == 0: 1436 | next_echoarea = True 1437 | go = False 1438 | quit = False 1439 | else: 1440 | msgn = msgn +1 1441 | if len(stack) > 0: 1442 | stack = [] 1443 | if out: 1444 | msg, size = read_out_msg(msgids[msgn]) 1445 | else: 1446 | msg, size = read_msg(msgids[msgn], echo[0]) 1447 | msgbody = body_render(msg[8:]) 1448 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1449 | else: 1450 | if len(msgids) > 0 and len(msgbody) > height - 5: 1451 | y = y + height - 6 1452 | elif key in r_down: 1453 | if len(msgids) > 0: 1454 | if y + height - 5 < len(msgbody): 1455 | y = y + 1 1456 | elif key in r_begin: 1457 | if len(msgids) > 0: 1458 | y = 0 1459 | msgn = 0 1460 | if len(stack) > 0: 1461 | stack = [] 1462 | if out: 1463 | msg, size = read_out_msg(msgids[msgn]) 1464 | else: 1465 | msg, size = read_msg(msgids[msgn], echo[0]) 1466 | msgbody = body_render(msg[8:]) 1467 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1468 | elif key in r_end: 1469 | if len(msgids) > 0: 1470 | y = 0 1471 | msgn = len(msgids) - 1 1472 | if len(stack) > 0: 1473 | stack = [] 1474 | if out: 1475 | msg, size = read_out_msg(msgids[msgn]) 1476 | else: 1477 | msg, size = read_msg(msgids[msgn], echo[0]) 1478 | msgbody = body_render(msg[8:]) 1479 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1480 | elif (key in r_ins) and not archive and not out: 1481 | if not favorites: 1482 | t = open("template.txt", "r") 1483 | f = open("temp", "w") 1484 | f.write(echo[0] + "\n") 1485 | f.write("All\n") 1486 | f.write("No subject\n\n") 1487 | f.write(t.read()) 1488 | f.close() 1489 | t.close() 1490 | call_editor() 1491 | stdscr.clear() 1492 | elif key in r_save and not out: 1493 | save_message_to_file(msgids[msgn], echo[0]) 1494 | elif key in r_favorites and not out: 1495 | saved = save_to_favorites(msgids[msgn], msg) 1496 | draw_message_box("Подождите", False) 1497 | get_counts(False, True) 1498 | if saved: 1499 | message_box("Собщение добавлено в избранные") 1500 | else: 1501 | message_box("Собщение уже есть в избранных") 1502 | elif (key in r_quote) and not archive and not out: 1503 | if len(msgids) > 0: 1504 | t = open("template.txt", "r") 1505 | f = open("temp", "w") 1506 | f.write(msgids[msgn] + "\n") 1507 | f.write(msg[1] + "\n") 1508 | f.write(msg[3] + "\n") 1509 | to = msg[3].split(" ") 1510 | q = quote(to) 1511 | if not msg[6].startswith("Re:"): 1512 | f.write("Re: " + msg[6] + "\n") 1513 | else: 1514 | f.write(msg[6] + "\n") 1515 | rr = re.compile(r"^[a-zA-Zа-яА-Я0-9_\(\)-]{0,20}>{1,20}") 1516 | for line in msg[8:]: 1517 | if not line.startswith("+++"): 1518 | if line.strip() != "": 1519 | if rr.match(line): 1520 | if line[rr.match(line).span()[1]] == " ": 1521 | quoter = ">" 1522 | else: 1523 | quoter = "> " 1524 | f.write("\n" + line[:rr.match(line).span()[1]] + quoter + line[rr.match(line).span()[1]:]) 1525 | else: 1526 | f.write("\n" + q + "> " + line) 1527 | # else: 1528 | # f.write("\n" + line) 1529 | f.write(t.read()) 1530 | f.close() 1531 | t.close() 1532 | call_editor() 1533 | elif key in r_subj: 1534 | show_subject(msg[6]) 1535 | elif key in r_info and not out and width < 80: 1536 | message_box("id : " + msgids[msgn] + "\naddr: " + msg[4]) 1537 | elif key in o_edit and out: 1538 | if msgids[msgn].endswith(".out") or msgids[msgn].endswith(".draft"): 1539 | copyfile("out/" + nodes[node]["nodename"] + "/" + msgids[msgn], "temp") 1540 | if drafts: 1541 | call_editor(msgids[msgn], drafts) 1542 | msgids = get_out(True) 1543 | else: 1544 | call_editor(msgids[msgn]) 1545 | msgids = get_out() 1546 | if msgn > len(msgids) - 1: 1547 | msgn = len(msgids) -1 1548 | if len(msgids) > 0: 1549 | msg, size = read_out_msg(msgids[msgn]) 1550 | msgbody = body_render(msg[8:]) 1551 | else: 1552 | go = False 1553 | quit = False 1554 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1555 | stdscr.clear() 1556 | else: 1557 | message_box("Сообщение уже отправлено") 1558 | stdscr.clear() 1559 | elif key in f_delete and favorites and not carbonarea: 1560 | if len(msgids) > 0: 1561 | remove_from_favorites(msgids[msgn]) 1562 | draw_message_box("Подождите", False) 1563 | get_counts(False, True) 1564 | msgids = get_echo_msgids(echo[0]) 1565 | if len(msgids) > 0: 1566 | if msgn >= len(msgids): 1567 | msgn = len(msgids) - 1 1568 | msg, size = read_msg(msgids[msgn], echo[0]) 1569 | msgbody = body_render(msg[8:]) 1570 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1571 | else: 1572 | msgbody = [] 1573 | stdscr.clear() 1574 | elif key in r_getmsg and size == "0b": 1575 | try: 1576 | get_msg(msgids[msgn]) 1577 | draw_message_box("Подождите", False) 1578 | get_counts(True, False) 1579 | stdscr.clear() 1580 | msg, size = read_msg(msgids[msgn], echo[0]) 1581 | msgbody = body_render(msg[8:]) 1582 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1583 | except: 1584 | message_box("Не удалось определить msgid.") 1585 | stdscr.clear() 1586 | elif key in r_links: 1587 | results = urltemplate.findall("\n".join(msg[8:])) 1588 | links = [] 1589 | for item in results: 1590 | links.append(item[0]) 1591 | if len(links) == 1: 1592 | open_link(links[0]) 1593 | else: 1594 | i = menu("Выберите ссылку", links) 1595 | if i: 1596 | open_link(links[i - 1]) 1597 | stdscr.clear() 1598 | elif key in r_to_out and drafts: 1599 | copyfile("out/" + nodes[node]["nodename"] + "/" + msgids[msgn], "out/" + nodes[node]["nodename"] + "/" + msgids[msgn].replace(".draft", ".out")) 1600 | os.remove("out/" + nodes[node]["nodename"] + "/" + msgids[msgn]) 1601 | if drafts: 1602 | msgids = get_out(True) 1603 | else: 1604 | msgids = get_out() 1605 | if msgn > len(msgids) - 1: 1606 | msgn = len(msgids) -1 1607 | if len(msgids) > 0: 1608 | msg, size = read_out_msg(msgids[msgn]) 1609 | msgbody = body_render(msg[8:]) 1610 | else: 1611 | go = False 1612 | quit = False 1613 | elif key in r_to_drafts and out and not drafts and msgids[msgn].endswith(".out"): 1614 | copyfile("out/" + nodes[node]["nodename"] + "/" + msgids[msgn], "out/" + nodes[node]["nodename"] + "/" + msgids[msgn].replace(".out", ".draft")) 1615 | os.remove("out/" + nodes[node]["nodename"] + "/" + msgids[msgn]) 1616 | if drafts: 1617 | msgids = get_out(True) 1618 | else: 1619 | msgids = get_out() 1620 | if msgn > len(msgids) - 1: 1621 | msgn = len(msgids) -1 1622 | if len(msgids) > 0: 1623 | msg, size = read_out_msg(msgids[msgn]) 1624 | msgbody = body_render(msg[8:]) 1625 | else: 1626 | go = False 1627 | quit = False 1628 | elif key in r_list and not out and not drafts: 1629 | if db == 0: 1630 | message_box("Функция не поддерживается текстовой базой.") 1631 | else: 1632 | l = msg_list(echo, msgids, msgn) 1633 | if l > -1: 1634 | y = 0 1635 | msgn = l 1636 | if len(stack) > 0: 1637 | stack = [] 1638 | msg, size = read_msg(msgids[msgn], echo[0]) 1639 | msgbody = body_render(msg[8:]) 1640 | scrollbar_size = calc_scrollbar_size(len(msgbody)) 1641 | elif key in r_quit: 1642 | go = False 1643 | quit = False 1644 | next_echoarea = False 1645 | elif key in g_quit: 1646 | go = False 1647 | quit = True 1648 | lasts[echo[0]] = msgn 1649 | f = open("lasts.lst", "wb") 1650 | pickle.dump(lasts, f) 1651 | f.close() 1652 | stdscr.clear() 1653 | return quit 1654 | 1655 | def draw_msg_list(echo, lst, msgn): 1656 | stdscr.clear() 1657 | for i in range(0, width): 1658 | if bold[0]: 1659 | color = curses.color_pair(1) + curses.A_BOLD 1660 | else: 1661 | color = curses.color_pair(1) 1662 | stdscr.insstr(0, i, "─", color) 1663 | if width >= 80: 1664 | draw_title(0, 0, "Список сообщений в конференции " + echo) 1665 | else: 1666 | draw_title(0, 0, echo) 1667 | 1668 | def msg_list(echoarea, msgids, msgn): 1669 | lst = [] 1670 | lst = get_msg_list_data(echoarea[0]) 1671 | draw_msg_list(echoarea[0], lst, msgn) 1672 | echo_length = len(lst) 1673 | if echo_length <= height - 1: 1674 | start = 0 1675 | end = echo_length - 1 1676 | elif msgn + height - 1 < echo_length: 1677 | start = msgn 1678 | end = msgn + height - 1 1679 | else: 1680 | start = echo_length - height + 1 1681 | end = start + height - 1 1682 | quit = False 1683 | cancel = False 1684 | y = msgn - start 1685 | while not quit: 1686 | n = 1 1687 | for i in range(start, end): 1688 | if i == y + start: 1689 | if bold[2]: 1690 | color = curses.color_pair(3) + curses.A_BOLD 1691 | else: 1692 | color = curses.color_pair(3) 1693 | else: 1694 | if bold[3]: 1695 | color = curses.color_pair(4) + curses.A_BOLD 1696 | else: 1697 | color = curses.color_pair(4) 1698 | draw_cursor(n - 1, color) 1699 | stdscr.addstr(n, 0, lst[i][1], color) 1700 | stdscr.addstr(n, 16, lst[i][2][:width-26], color) 1701 | stdscr.insstr(n, width - 10, lst[i][3], color) 1702 | n += 1 1703 | key = stdscr.getch() 1704 | if key in s_up: 1705 | y = y - 1 1706 | if start > 0 and y + start < start: 1707 | start -= 1 1708 | end -= 1 1709 | if y == -1: 1710 | y = 0 1711 | elif key in s_down: 1712 | y = y + 1 1713 | if y + start + 1 > end and y + start < echo_length: 1714 | start += 1 1715 | end += 1 1716 | if y > height - 2: 1717 | y = height - 2 1718 | elif key in s_ppage: 1719 | if y == 0: 1720 | start = start - height + 1 1721 | if start < 0: 1722 | start = 0 1723 | end = start + height - 1 1724 | if y > 0: 1725 | y = 0 1726 | elif key in s_npage: 1727 | if y == height - 2: 1728 | start = start + height - 1 1729 | if start > echo_length - height + 1: 1730 | start = echo_length - height + 1 1731 | end = start + height - 1 1732 | if y < height - 2: 1733 | y = height - 2 1734 | elif key in s_home: 1735 | y = 0 1736 | start = 0 1737 | end = height - 1 1738 | elif key in s_end: 1739 | y = height - 2 1740 | start = echo_length - height + 1 1741 | end = start + height - 1 1742 | elif key in s_enter: 1743 | quit = True 1744 | elif key in r_quit: 1745 | quit = True 1746 | cancel = True 1747 | if cancel: 1748 | return -1 1749 | else: 1750 | return y + start 1751 | 1752 | loc = locale.getdefaultlocale() 1753 | locale.setlocale(locale.LC_ALL, loc[0] + "." + loc[1]) 1754 | 1755 | check_config() 1756 | reset_config() 1757 | load_config() 1758 | if db == 0: 1759 | from api.txt import * 1760 | elif db == 1: 1761 | from api.aio import * 1762 | elif db == 2: 1763 | from api.ait import * 1764 | elif db == 3: 1765 | from api.sqlite import * 1766 | check_directories() 1767 | load_lasts() 1768 | stdscr = curses.initscr() 1769 | curses.start_color() 1770 | curses.use_default_colors() 1771 | load_colors() 1772 | curses.noecho() 1773 | curses.curs_set(False) 1774 | stdscr.keypad(True) 1775 | 1776 | stdscr.bkgd(" ", curses.color_pair(1)) 1777 | get_term_size() 1778 | if show_splash: 1779 | splash_screen() 1780 | draw_message_box("Подождите", False) 1781 | get_counts() 1782 | stdscr.clear() 1783 | echo_selector() 1784 | curses.echo() 1785 | curses.curs_set(True) 1786 | curses.endwin() 1787 | -------------------------------------------------------------------------------- /docs/formats.md: -------------------------------------------------------------------------------- 1 | Форматы базы сообщений 2 | ====================== 3 | 4 | txt 5 | --- 6 | 7 | Классический для ii/idec формат. Каждое сообщение хранится в отдельном файле в директории msg/. Индексы конференций хранятся в директории echo/ и представляют собой текстовые файлы со списком сообщений в конференции. Каждый msgid хранится в отдельной строке. 8 | 9 | aio 10 | --- 11 | 12 | Формат txt имеет недостаток в виде множества маленьких файлов, приводящий к долгому копированию базы, её анализу, затруднённому копированию или удалению отдельной конференции. Для решения этих проблем был придуман формат aio (all in one). 13 | 14 | Каждая конференция хранится в отдельном .aio-файле. Каждое сообщение хранится в отдельной строке следующего формата: 15 | 16 | msgid:текст сообщения, с заменённым симполом перевода строки на символ с кодом 15 17 | 18 | Такую базу можно легко обрабатывать и анализировать. Скорость работы с базой достаточно высокая за счёт резкого сокращения времени дисковых операций. Но для работы на ноде или клиенте она недостаточно быстрая, так как резко увеличивается время построения индекса. 19 | 20 | ait 21 | --- 22 | 23 | Этот формат является результатом "скрещивания" форматов txt и aio. Каждая конференция хранится в двух файлах: .mat, совпадающий по формату с .aio и .iat, представляющий собой индексный файл из txt-базы. Таким образом достигнута скорость построения индекса как в txt и скорость доступа к сообщениям как в aio базах. 24 | -------------------------------------------------------------------------------- /docs/mailer.md: -------------------------------------------------------------------------------- 1 | mailer 2 | ====== 3 | 4 | Мейлер — отдельная программа для обмена сообщениями с нодой. В цезии отправка и получение почты осуществляется посредством вызоава мейлера. 5 | 6 | mailer.py позволяет совмещать отправку и получение сообщений либо же провоизводить их раздельно. Для работы требует наличия в своей директории копии api/. 7 | 8 | Задавать параметры работы мейлера можно как через параметры командной строки, так и через конфигурационный файл. 9 | 10 | Параметры конфигурационного файла: 11 | 12 | * node — адрес ноды с учётом схем u/. Например node http://idec.spline-online.tk/u/ 13 | * nodename — название ноды. Необходимо для отправки сообщения, так как все исходящие находятся в директории out/. Для адекватной работы с цезием параметр должен совпадать с одноимённым параметром из конфигурационного файла цезия. 14 | * auth — строка авторизации. Необходима для отправки сообщений. 15 | * depth — глубина сканирования индекса на ноде. Позволяет экономить трафик при обмене с нодой. Работает только с узлами idec-сетей, так как требует поддержку расширенной схемы u/e на их стороне. 16 | * echo — имя эхоконференции для фетчинга. 17 | * db — тип базы сообщений (txt, aio, ait). Для подробной информации см. файл formats.md. 18 | * oldmode — принудительное игнорирование расширенной схемы u/e. Может быть полезно для ускорения обмена с узлами ii-сетей. 19 | * to — имя для определения сообщений, попадающих в карбонку. 20 | * fetchonly — заставляет мейлер пропускать поиск исходящих сообщений и их отправку. 21 | * sendonly — заставляет мейлер пропускать поиск новых сообщений у аплинка и их получение. 22 | 23 | Параметры командной строки, можно узнать, вызвав мейлер с опцией -h. 24 | -------------------------------------------------------------------------------- /keys-vi.py: -------------------------------------------------------------------------------- 1 | import curses 2 | 3 | # Клавиши для экрана выбора эхоконференции 4 | s_up = [curses.KEY_UP, ord("k"), ord("K")] # курсор вверх 5 | s_down = [curses.KEY_DOWN, ord("j"), ord("J")] # курсор вниз 6 | s_ppage = [curses.KEY_PPAGE, ord("l"), ord("L")] # страница вверх 7 | s_npage = [curses.KEY_NPAGE, ord("h"), ord("H")] # страница вниз 8 | s_home = [curses.KEY_HOME, ord("^")] # в начало 9 | s_end = [curses.KEY_END, ord("$")] # в конец 10 | s_get = [ord("g"), ord("G")] # получить сообщения 11 | s_send = [ord("s"), ord("S")] # отправить сообщения 12 | s_archive = [9] # переключение в архив и обратно 13 | s_enter = [10, curses.KEY_RIGHT, ord(" ")] # открыть эху 14 | s_out = [ord("o"), ord("O")] # исходящие сообщения 15 | s_drafts = [ord("d"), ord("D")] # черновики 16 | s_nnode = [ord(".")] # следующая нода 17 | s_pnode = [ord(",")] # предыдущая нода 18 | s_clone = [ord("c"), ord("C")] # клонировать эху 19 | s_config = [ord("e"), ord("E")] # редактировать конфиг 20 | 21 | # Клавиши для экрана чтения 22 | r_prev = [curses.KEY_LEFT, ord("h"), ord("H")] # предыдущее сообщение 23 | r_next = [curses.KEY_RIGHT, ord("l"), ord("L")] # следующее сообщение 24 | r_prep = [ord("-")] # перейти ниже по цепочке ответов 25 | r_nrep = [ord("=")] # вернуться по цепочке ответов 26 | r_up = [curses.KEY_UP, ord("k"), ord("K")] # прокрутка вверх 27 | r_down = [curses.KEY_DOWN, ord("j"), ord("J")] # прокрутка вниз 28 | r_ppage = [curses.KEY_PPAGE] # страница вверх 29 | r_npage = [curses.KEY_NPAGE] # страница вниз 30 | r_ukeys = [10, ord(" ")] # клавиша прокрутки или перехода к следующему сообщению 31 | r_home = [curses.KEY_HOME, ord("^")] # в начало сообщения 32 | r_mend = [curses.KEY_END, ord("$")] # в конец сообщения 33 | r_begin = [ord("<")] # в начало эхоконференции 34 | r_end = [ord(">")] # в конце эхоконференции 35 | r_ins = [ord("i"), ord("I"), curses.KEY_IC] # добавить сообщение 36 | r_save = [ord("w"), ord("W")] # сохранить сообщение в файл 37 | r_favorites = [ord("f"), ord("F")] # добавить сообщение в избранные 38 | r_quote = [ord("a"), ord("A")] # ответить с цитированием (answer) 39 | r_subj = [ord("s"), ord("S")] # показать messagebox с темой сообщения 40 | r_info = [ord("m"), ord("M")] # показать msgid и адрес 41 | r_links = [ord("v"), ord("V")] # работа со ссылками 42 | r_getmsg = [ord("g"), ord("G")] # получить текущее сообщение с ноды 43 | r_to_out = [ord("o"), ord("O")] # перенести неотправленное исходящее сообщение в черновики 44 | r_to_drafts = [ord("d"), ord("D")] # перенести черновик в исходящие сообщения 45 | r_list = [] 46 | r_quit = [ord("q"), ord("Q"), 27] # вернуться на экран выбора эхоконференции 47 | 48 | # Клавиши для просмотра исходящих 49 | o_edit = [ord("e"), ord("E")] # редактировать сообщение 50 | 51 | # Клавиши для просмотра избранных сообщений 52 | f_delete = [curses.KEY_DC] # удалить из избранных 53 | 54 | g_quit = [ord("z"), ord("Z"), curses.KEY_F10] # закрыть клиент 55 | -------------------------------------------------------------------------------- /keys.py: -------------------------------------------------------------------------------- 1 | import curses 2 | 3 | ## Клавиши для экрана выбора эхоконференции 4 | # курсор вверх 5 | s_up = [curses.KEY_UP] 6 | # курсор вниз 7 | s_down = [curses.KEY_DOWN] 8 | # страница вверх 9 | s_ppage = [curses.KEY_PPAGE] 10 | # страница вниз 11 | s_npage = [curses.KEY_NPAGE] 12 | # в начало 13 | s_home = [curses.KEY_HOME] 14 | # в конец 15 | s_end = [curses.KEY_END] 16 | # получить сообщения 17 | s_get = [ord("g"), ord("G")] 18 | # переключение в архив и обратно 19 | s_archive = [9] 20 | # открыть эху 21 | s_enter = [10, curses.KEY_RIGHT, ord(" ")] 22 | # исходящие сообщения 23 | s_out = [ord("o"), ord("O")] 24 | # черновики 25 | s_drafts = [ord("d"), ord("D")] 26 | # следующая нода 27 | s_nnode = [ord(".")] 28 | # предыдущая нода 29 | s_pnode = [ord(",")] 30 | # клонировать эху 31 | s_clone = [ord("c"), ord("C")] 32 | # редактировать конфиг 33 | s_config = [ord("e"), ord("E")] 34 | 35 | ## Клавиши для экрана чтения 36 | # предыдущее сообщение 37 | r_prev = [curses.KEY_LEFT] 38 | # следующее сообщение 39 | r_next = [curses.KEY_RIGHT] 40 | # перейти ниже по цепочке ответов 41 | r_prep = [ord("-")] 42 | # вернуться по цепочке ответов 43 | r_nrep = [ord("=")] 44 | # прокрутка вверх 45 | r_up = [curses.KEY_UP] 46 | # прокрутка вниз 47 | r_down = [curses.KEY_DOWN] 48 | # страница вверх 49 | r_ppage = [curses.KEY_PPAGE] 50 | # страница вниз 51 | r_npage = [curses.KEY_NPAGE] 52 | # клавиша прокрутки или перехода к следующему сообщению 53 | r_ukeys = [10, ord(" ")] 54 | #в начало сообщения 55 | r_home = [curses.KEY_HOME] 56 | # в конец сообщения 57 | r_mend = [curses.KEY_END] 58 | # в начало эхоконференции 59 | r_begin = [ord("<")] 60 | # в конце эхоконференции 61 | r_end = [ord(">")] 62 | # добавить сообщение 63 | r_ins = [ord("i"), ord("I"), curses.KEY_IC] 64 | # сохранить сообщение в файл 65 | r_save = [ord("w"), ord("W")] 66 | # добавить сообщение в избранные 67 | r_favorites = [ord("f"), ord("F")] 68 | # ответить с цитированием 69 | r_quote = [ord("q"), ord("Q")] 70 | # показать messagebox с темой сообщения 71 | r_subj = [ord("s"), ord("S")] 72 | # показать msgid и адрес 73 | r_info = [ord("m"), ord("M")] 74 | # работа со ссылками 75 | r_links = [ord("v"), ord("V")] 76 | # получить текущее сообщение с ноды 77 | r_getmsg = [ord("g"), ord("G")] 78 | # перенести неотправленное исходящее сообщение в черновики 79 | r_to_out = [ord("o"), ord("O")] 80 | # перенести черновик в исходящие сообщения 81 | r_to_drafts = [ord("d"), ord("D")] 82 | # список сообщений 83 | r_list = [ord("l"), ord("L")] 84 | # вернуться на экран выбора эхоконференции 85 | r_quit = [27] 86 | 87 | ## Клавиши для просмотра исходящих и черновиков 88 | # редактировать сообщение 89 | o_edit = [ord("e"), ord("E")] 90 | 91 | ## Клавиши для просмотра избранных сообщений 92 | # удалить из избранных 93 | f_delete = [curses.KEY_DC] 94 | 95 | ## закрыть клиент 96 | g_quit = [curses.KEY_F10] 97 | -------------------------------------------------------------------------------- /keys_android.patch: -------------------------------------------------------------------------------- 1 | 6c6 2 | < from keys import * 3 | --- 4 | > from keys_android import * 5 | -------------------------------------------------------------------------------- /keys_android.py: -------------------------------------------------------------------------------- 1 | import curses 2 | 3 | ## Клавиши для экрана выбора эхоконференции 4 | # курсор вверх 5 | s_up = [curses.KEY_UP, ord("k")] 6 | # курсор вниз 7 | s_down = [curses.KEY_DOWN, ord("j")] 8 | # страница вверх 9 | s_ppage = [curses.KEY_PPAGE, ord("K")] 10 | # страница вниз 11 | s_npage = [curses.KEY_NPAGE, ord("J")] 12 | # в начало 13 | s_home = [curses.KEY_HOME, ord("H")] 14 | # в конец 15 | s_end = [curses.KEY_END, ord("L")] 16 | # получить сообщения 17 | s_get = [ord("g"), ord("G")] 18 | # переключение в архив и обратно 19 | s_archive = [9, ord("t")] 20 | # открыть эху 21 | s_enter = [10, curses.KEY_RIGHT, ord(" "), ord("l")] 22 | # исходящие сообщения 23 | s_out = [ord("o"), ord("O")] 24 | # черновики 25 | s_drafts = [ord("d"), ord("D")] 26 | # следующая нода 27 | s_nnode = [ord(".")] 28 | # предыдущая нода 29 | s_pnode = [ord(",")] 30 | # клонировать эху 31 | s_clone = [ord("c")] 32 | # редактировать конфиг 33 | s_config = [ord("e"), ord("E")] 34 | 35 | ## Клавиши для экрана чтения 36 | # предыдущее сообщение 37 | r_prev = [curses.KEY_LEFT, ord("h")] 38 | # следующее сообщение 39 | r_next = [curses.KEY_RIGHT, ord("l")] 40 | # перейти ниже по цепочке ответов 41 | r_prep = [ord("N")] 42 | # вернуться по цепочке ответов 43 | r_nrep = [ord("n")] 44 | # прокрутка вверх 45 | r_up = [curses.KEY_UP, ord("k")] 46 | # прокрутка вниз 47 | r_down = [curses.KEY_DOWN, ord("j")] 48 | # страница вверх 49 | r_ppage = [curses.KEY_PPAGE, ord("B")] 50 | # страница вниз 51 | r_npage = [curses.KEY_NPAGE, ord("F")] 52 | # клавиша прокрутки или перехода к следующему сообщению 53 | r_ukeys = [10, ord(" ")] 54 | # в начало сообщения 55 | r_home = [curses.KEY_HOME, ord("K")] 56 | # в конец сообщения 57 | r_mend = [curses.KEY_END, ord("J")] 58 | # в начало эхоконференции 59 | r_begin = [ord("H")] 60 | # в конец эхоконференции 61 | r_end = [ord("L")] 62 | # добавить сообщение 63 | r_ins = [ord("i"), ord("I")] 64 | # сохранить сообщение в файл 65 | r_save = [ord("w"), ord("W")] 66 | # добавить сообщение в избранные 67 | r_favorites = [ord("f")] 68 | # ответить с цитированием 69 | r_quote = [ord("r"), ord("R")] 70 | # показать messagebox с темой сообщения 71 | r_subj = [ord("s"), ord("S")] 72 | # показать msgid и адрес 73 | r_info = [ord("m"), ord("M")] 74 | # работа со ссылками 75 | r_links = [ord("v"), ord("V")] 76 | # получить текущее сообщение с ноды 77 | r_getmsg = [ord("g"), ord("G")] 78 | # перенести неотправленное исходящее сообщение в черновики 79 | r_to_out = [ord("o"), ord("O")] 80 | # перенести черновик в исходящие сообщения 81 | r_to_drafts = [ord("d"), ord("D")] 82 | # список сообщений 83 | r_list = [ord("t"), ord("t")] 84 | # вернуться на экран выбора эхоконференции 85 | r_quit = [27, ord("b"), ord("B")] 86 | 87 | ## Клавиши для просмотра исходящих и черновиков 88 | # редактировать сообщение 89 | o_edit = [ord("e"), ord("E")] 90 | 91 | # Клавиши для просмотра избранных сообщений 92 | # удалить из избранных 93 | f_delete = [curses.KEY_DC, ord("x"), ord("X")] 94 | 95 | # закрыть клиент 96 | g_quit = [curses.KEY_F10, ord("q"), ord("Q")] 97 | -------------------------------------------------------------------------------- /keys_vi.patch: -------------------------------------------------------------------------------- 1 | --- ./keys.py 2020-01-10 00:48:34.802136937 +0700 2 | +++ ./keys-vi.py 2020-01-10 00:48:59.242249131 +0700 3 | @@ -1,96 +1,54 @@ 4 | import curses 5 | 6 | -## Клавиши для экрана выбора эхоконференции 7 | -# курсор вверх 8 | -s_up = [curses.KEY_UP] 9 | -# курсор вниз 10 | -s_down = [curses.KEY_DOWN] 11 | -# страница вверх 12 | -s_ppage = [curses.KEY_PPAGE] 13 | -# страница вниз 14 | -s_npage = [curses.KEY_NPAGE] 15 | -# в начало 16 | -s_home = [curses.KEY_HOME] 17 | -# в конец 18 | -s_end = [curses.KEY_END] 19 | -# получить сообщения 20 | -s_get = [ord("g"), ord("G")] 21 | -# переключение в архив и обратно 22 | -s_archive = [9] 23 | -# открыть эху 24 | -s_enter = [10, curses.KEY_RIGHT, ord(" ")] 25 | -# исходящие сообщения 26 | -s_out = [ord("o"), ord("O")] 27 | -# черновики 28 | -s_drafts = [ord("d"), ord("D")] 29 | -# следующая нода 30 | -s_nnode = [ord(".")] 31 | -# предыдущая нода 32 | -s_pnode = [ord(",")] 33 | -# клонировать эху 34 | -s_clone = [ord("c"), ord("C")] 35 | -# редактировать конфиг 36 | -s_config = [ord("e"), ord("E")] 37 | +# Клавиши для экрана выбора эхоконференции 38 | +s_up = [curses.KEY_UP, ord("k"), ord("K")] # курсор вверх 39 | +s_down = [curses.KEY_DOWN, ord("j"), ord("J")] # курсор вниз 40 | +s_ppage = [curses.KEY_PPAGE, ord("l"), ord("L")] # страница вверх 41 | +s_npage = [curses.KEY_NPAGE, ord("h"), ord("H")] # страница вниз 42 | +s_home = [curses.KEY_HOME, ord("^")] # в начало 43 | +s_end = [curses.KEY_END, ord("$")] # в конец 44 | +s_get = [ord("g"), ord("G")] # получить сообщения 45 | +s_send = [ord("s"), ord("S")] # отправить сообщения 46 | +s_archive = [9] # переключение в архив и обратно 47 | +s_enter = [10, curses.KEY_RIGHT, ord(" ")] # открыть эху 48 | +s_out = [ord("o"), ord("O")] # исходящие сообщения 49 | +s_drafts = [ord("d"), ord("D")] # черновики 50 | +s_nnode = [ord(".")] # следующая нода 51 | +s_pnode = [ord(",")] # предыдущая нода 52 | +s_clone = [ord("c"), ord("C")] # клонировать эху 53 | +s_config = [ord("e"), ord("E")] # редактировать конфиг 54 | 55 | -## Клавиши для экрана чтения 56 | -# предыдущее сообщение 57 | -r_prev = [curses.KEY_LEFT] 58 | -# следующее сообщение 59 | -r_next = [curses.KEY_RIGHT] 60 | -# перейти ниже по цепочке ответов 61 | -r_prep = [ord("-")] 62 | -# вернуться по цепочке ответов 63 | -r_nrep = [ord("=")] 64 | -# прокрутка вверх 65 | -r_up = [curses.KEY_UP] 66 | -# прокрутка вниз 67 | -r_down = [curses.KEY_DOWN] 68 | -# страница вверх 69 | -r_ppage = [curses.KEY_PPAGE] 70 | -# страница вниз 71 | -r_npage = [curses.KEY_NPAGE] 72 | -# клавиша прокрутки или перехода к следующему сообщению 73 | -r_ukeys = [10, ord(" ")] 74 | -#в начало сообщения 75 | -r_home = [curses.KEY_HOME] 76 | -# в конец сообщения 77 | -r_mend = [curses.KEY_END] 78 | -# в начало эхоконференции 79 | -r_begin = [ord("<")] 80 | -# в конце эхоконференции 81 | -r_end = [ord(">")] 82 | -# добавить сообщение 83 | -r_ins = [ord("i"), ord("I"), curses.KEY_IC] 84 | -# сохранить сообщение в файл 85 | -r_save = [ord("w"), ord("W")] 86 | -# добавить сообщение в избранные 87 | -r_favorites = [ord("f"), ord("F")] 88 | -# ответить с цитированием 89 | -r_quote = [ord("q"), ord("Q")] 90 | -# показать messagebox с темой сообщения 91 | -r_subj = [ord("s"), ord("S")] 92 | -# показать msgid и адрес 93 | -r_info = [ord("m"), ord("M")] 94 | -# работа со ссылками 95 | -r_links = [ord("v"), ord("V")] 96 | -# получить текущее сообщение с ноды 97 | -r_getmsg = [ord("g"), ord("G")] 98 | -# перенести неотправленное исходящее сообщение в черновики 99 | -r_to_out = [ord("o"), ord("O")] 100 | -# перенести черновик в исходящие сообщения 101 | -r_to_drafts = [ord("d"), ord("D")] 102 | -# список сообщений 103 | -r_list = [ord("l"), ord("L")] 104 | -# вернуться на экран выбора эхоконференции 105 | -r_quit = [27] 106 | +# Клавиши для экрана чтения 107 | +r_prev = [curses.KEY_LEFT, ord("h"), ord("H")] # предыдущее сообщение 108 | +r_next = [curses.KEY_RIGHT, ord("l"), ord("L")] # следующее сообщение 109 | +r_prep = [ord("-")] # перейти ниже по цепочке ответов 110 | +r_nrep = [ord("=")] # вернуться по цепочке ответов 111 | +r_up = [curses.KEY_UP, ord("k"), ord("K")] # прокрутка вверх 112 | +r_down = [curses.KEY_DOWN, ord("j"), ord("J")] # прокрутка вниз 113 | +r_ppage = [curses.KEY_PPAGE] # страница вверх 114 | +r_npage = [curses.KEY_NPAGE] # страница вниз 115 | +r_ukeys = [10, ord(" ")] # клавиша прокрутки или перехода к следующему сообщению 116 | +r_home = [curses.KEY_HOME, ord("^")] # в начало сообщения 117 | +r_mend = [curses.KEY_END, ord("$")] # в конец сообщения 118 | +r_begin = [ord("<")] # в начало эхоконференции 119 | +r_end = [ord(">")] # в конце эхоконференции 120 | +r_ins = [ord("i"), ord("I"), curses.KEY_IC] # добавить сообщение 121 | +r_save = [ord("w"), ord("W")] # сохранить сообщение в файл 122 | +r_favorites = [ord("f"), ord("F")] # добавить сообщение в избранные 123 | +r_quote = [ord("a"), ord("A")] # ответить с цитированием (answer) 124 | +r_subj = [ord("s"), ord("S")] # показать messagebox с темой сообщения 125 | +r_info = [ord("m"), ord("M")] # показать msgid и адрес 126 | +r_links = [ord("v"), ord("V")] # работа со ссылками 127 | +r_getmsg = [ord("g"), ord("G")] # получить текущее сообщение с ноды 128 | +r_to_out = [ord("o"), ord("O")] # перенести неотправленное исходящее сообщение в черновики 129 | +r_to_drafts = [ord("d"), ord("D")] # перенести черновик в исходящие сообщения 130 | +r_list = [] 131 | +r_quit = [ord("q"), ord("Q"), 27] # вернуться на экран выбора эхоконференции 132 | 133 | -## Клавиши для просмотра исходящих и черновиков 134 | -# редактировать сообщение 135 | -o_edit = [ord("e"), ord("E")] 136 | +# Клавиши для просмотра исходящих 137 | +o_edit = [ord("e"), ord("E")] # редактировать сообщение 138 | 139 | -## Клавиши для просмотра избранных сообщений 140 | -# удалить из избранных 141 | -f_delete = [curses.KEY_DC] 142 | +# Клавиши для просмотра избранных сообщений 143 | +f_delete = [curses.KEY_DC] # удалить из избранных 144 | 145 | -## закрыть клиент 146 | -g_quit = [curses.KEY_F10] 147 | +g_quit = [ord("z"), ord("Z"), curses.KEY_F10] # закрыть клиент 148 | -------------------------------------------------------------------------------- /template.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | +++ Caesium/0.4 RC1 4 | -------------------------------------------------------------------------------- /themes/default.cfg: -------------------------------------------------------------------------------- 1 | # Доступные для использования цвета: 2 | # black, red, green, yellow, blue, magenta, cyan, white, gray 3 | # 4 | # Добавление в конце строки bold включает признак яркости 5 | 6 | border blue default 7 | titles yellow default bold 8 | cursor white blue bold 9 | text white default 10 | quote1 yellow default 11 | quote2 green default 12 | comment black default bold 13 | url blue default bold 14 | header red default 15 | statusline black cyan 16 | scrollbar white default 17 | origin blue default bold -------------------------------------------------------------------------------- /themes/dos_navigator.cfg: -------------------------------------------------------------------------------- 1 | # Доступные для использования цвета: 2 | # black, red, green, yellow, blue, magenta, cyan, white, gray 3 | # 4 | # Добавление в конце строки bold включает признак яркости 5 | 6 | border white gray bold 7 | titles yellow gray bold 8 | cursor black cyan 9 | text white gray 10 | quote1 cyan gray bold 11 | quote2 green gray bold 12 | comment green gray 13 | url cyan gray 14 | header white gray bold 15 | statusline black white 16 | scrollbar white gray bold 17 | origin yellow gray bold -------------------------------------------------------------------------------- /themes/norton.cfg: -------------------------------------------------------------------------------- 1 | # Доступные для использования цвета: 2 | # black, red, green, yellow, blue, magenta, cyan, white, gray 3 | # 4 | # Добавление в конце строки bold включает признак яркости 5 | 6 | border cyan blue bold 7 | titles cyan blue bold 8 | cursor black cyan 9 | text white blue 10 | quote1 cyan blue 11 | quote2 green blue 12 | comment gray blue 13 | url yellow blue bold 14 | header white blue bold 15 | statusline black cyan 16 | scrollbar cyan blue 17 | origin magenta blue bold -------------------------------------------------------------------------------- /themes/spring.cfg: -------------------------------------------------------------------------------- 1 | # Доступные для использования цвета: 2 | # black, red, green, yellow, blue, magenta, cyan, white, gray 3 | # 4 | # Добавление в конце строки bold включает признак яркости 5 | 6 | border green default 7 | titles yellow default bold 8 | cursor black green 9 | text white default 10 | quote1 yellow default bold 11 | quote2 green default bold 12 | comment black default bold 13 | url green default 14 | header red default 15 | statusline black green 16 | scrollbar green default 17 | origin red default bold -------------------------------------------------------------------------------- /themes/white.cfg: -------------------------------------------------------------------------------- 1 | # Доступные для использования цвета: 2 | # black, red, green, yellow, blue, magenta, cyan, white, gray 3 | # 4 | # Добавление в конце строки bold включает признак яркости 5 | 6 | border blue white 7 | titles blue white bold 8 | cursor white blue bold 9 | text black white 10 | quote1 green white 11 | quote2 blue white 12 | comment gray white 13 | url blue white 14 | header red white 15 | statusline white cyan 16 | scrollbar cyan white 17 | origin blue whie --------------------------------------------------------------------------------