├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── archiver ├── archiver.go ├── channel.go ├── discord.go ├── export.go ├── export_test.go ├── guild.go ├── message.go └── structure.go ├── common ├── logger.go └── util.go ├── db ├── db.go ├── queries.go ├── queries_test.go ├── schema.go ├── statements.go ├── structure_test.go └── tables.go ├── ddl.png ├── go.mod ├── go.sum ├── job └── job.go ├── main.go ├── models ├── args.go ├── attachment.go ├── channel.go ├── edit.go ├── embed.go ├── guild.go ├── message.go └── messages.go ├── sample_config.toml └── web ├── deploy.go ├── job.go └── static ├── channel.html ├── channels.html ├── index.html └── job.html /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/* 2 | *.db 3 | .png 4 | *.txt 5 | /media*/* 6 | bigbrother.* 7 | /.vscode/* 8 | *.xcf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BINARY_NAME=discord-dl 2 | 3 | build: 4 | go build -o bin/${BINARY_NAME} 5 | 6 | run: 7 | go build -o bin/${BINARY_NAME} 8 | ./bin/${BINARY_NAME} 9 | clean: 10 | go clean 11 | rm bin/${BINARY_NAME} 12 | rm bigbrother.db 13 | rm -r media/* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ![logo](ddl.png) 3 | 4 | **Discord-dl** is an utility that can be used to archive Discord channels and guilds. 5 | 6 | *** 7 | 8 | It's safe to say that forums, the medium that has once acted as the internet's primary knowledge center, are dead. Communities are moving en-masse to information blackholes like Discord that cannot be indexed by search engines and are completely inaccesible by those who are not registered users. It is vital to have a way of preserving these communities so its content can remain openly accessible. 9 | 10 | *** 11 | 12 | **Note:** While I recognize that there is no alternative to selfbots especially when it comes to archiving, it is unfortunately against Discord TOS. Use at your own discretion. 13 | 14 | **Master branch is experimental and unstable. Please use a stable release. The stable release is also highly experimental, unfortunately :^)** 15 | 16 | ## Installation 17 | 18 | 1) Install Go 19 | 20 | 2) Make a Bot account: https://discord.com/developers/applications 21 | 22 | 3) ```git clone https://github.com/Yakabuff/discord-dl.git``` 23 | 24 | ```cd discord-dl``` 25 | 26 | ```make build``` 27 | 28 | ```cd bin``` 29 | 30 | ```go install discord-dl``` 31 | 32 | 4) Invite the bot to the server: https://discordpy.readthedocs.io/en/stable/discord.html 33 | 34 | 5) Daemonize the bot (optional) or run the bot 35 | 36 | ## Features 37 | 38 | - Archives messages, edits, embeds, threads and attachments 39 | - Storing message history in an SQLite database 40 | - Listens for messages to archive in real time 41 | - Simple web API/frontend to display and query messages 42 | - Job queue for improved concurrency and the ability to pause/stop jobs/see progress 43 | 44 | ## To-do 45 | 46 | - Ability to 'rebuild' the server in the event of deletion 47 | - Cloud object storage support 48 | - Postgres support 49 | 50 | ## Instructions 51 | 52 | - ## Flags: 53 | - `--t=token` 54 | - Specify the token of your user agent. Prepend `Bot ` to the token for bot tokens. 55 | - eg: `--t='Bot '` or `--t=` 56 | - `--channel=channel_id` 57 | - Mode that archives the specified channel ID 58 | - `--guild=guild_id` 59 | - Mode that archives the specified guild ID 60 | - `--before=YYYY-MM-DD` or `--before=message_id` 61 | - Specify the date or message ID to get messages before 62 | - `--after=YYYY-MM-DD` or `--after=message_id` 63 | - Specify the date or message ID to get messages after 64 | - `--progress` 65 | - Output your progress. (Not implemented) 66 | - `--fast-update` 67 | - Fetches messages until it reaches an already archived message 68 | - `--listen` 69 | - Listens for new messages (BOT only) in selected channels and guilds. Can be used in conjunction with other modes 70 | - Usage: `--listen` 71 | - `--listen-guilds` 72 | - Only listen for messages from specific guilds 73 | - Usage: `--listen-guilds=guild1,guild2,guild3` 74 | - `--listen-channels` 75 | - Only listen for messages from specific channels 76 | - Usage: `--listen-channels=channelid1,channelid2` 77 | - `--download-media` 78 | - Enable this flag to download attachments/files (Includes embedded files) 79 | - `--deploy` 80 | - Mode to start the web server. Can be used by itself or in conjunction with other modes. 81 | - `--input="config_path"` 82 | - Specify path to config file. Values from the input file (TOML) will precedence over values from CLI flags. 83 | - `--output="path"` 84 | - Specify path to database. Will fallback to default value (archive.db) if empty. 85 | - `--media-location` 86 | - Specify location where you want images, videos and attachments to be saved 87 | - `--deployPort` 88 | - Specify port you want the webserver to run on. Will default to 8080 if empty 89 | - `--blacklisted-channels` 90 | - Specify channels you which to exclude. Delimit the channels by a comma. 91 | - ex: `--blacklisted-channels=channel1id,channel2id,channel3id` 92 | - `--export` 93 | - Export channel to json if set to true. Defaults to false 94 | - Cannot be used in conjunction with a database connection 95 | - ex: `--export=true` 96 | 97 | - ## Examples: 98 | - Downloading messages and media from a channel after Jan 1st 2018: 99 | - `discord-dl --channel="12371093817" --after="2018-01-01" --download-media=true --token="asdfasdfasdfasdf" --o="test.db" --media-location="~/pics"` 100 | ## Contributing 101 | Pull requests are welcome. Please open an issue first to discuss what you would like to change. 102 | 103 | ## License 104 | GNU AGPL v3 -------------------------------------------------------------------------------- /archiver/archiver.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "errors" 5 | "flag" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "strings" 10 | "sync" 11 | 12 | "github.com/BurntSushi/toml" 13 | "github.com/bwmarrin/discordgo" 14 | "github.com/sirupsen/logrus" 15 | "github.com/yakabuff/discord-dl/common" 16 | "github.com/yakabuff/discord-dl/db" 17 | "github.com/yakabuff/discord-dl/job" 18 | "github.com/yakabuff/discord-dl/models" 19 | "github.com/yakabuff/discord-dl/web" 20 | ) 21 | 22 | const VERSION = "3.0.0-alpha" 23 | 24 | type Archiver struct { 25 | Db db.Db 26 | Args models.ArchiverArgs 27 | Dg *discordgo.Session 28 | Web web.Web 29 | Queue job.JobQueue 30 | Wg sync.WaitGroup 31 | } 32 | 33 | var log *logrus.Logger 34 | 35 | func (a Archiver) InitLogger() { 36 | if a.Args.Logging { 37 | l, err := common.NewErrLogger() 38 | if err != nil { 39 | logrus.New().Fatal(err) 40 | } 41 | log = l 42 | log.SetReportCaller(true) 43 | } else { 44 | logrus.SetOutput(ioutil.Discard) 45 | } 46 | } 47 | 48 | func (a Archiver) InitListener() { 49 | if a.Args.Listen && strings.HasPrefix(a.Args.Token, "Bot") { 50 | log.Info("Listening for changes...") 51 | a.addHandlers() 52 | } 53 | } 54 | 55 | func (a Archiver) InitWeb() error { 56 | 57 | if a.Args.Deploy { 58 | if a.Db.DbConnection == nil { 59 | return errors.New("No db connection") 60 | } 61 | log.Info("Starting webview...") 62 | 63 | a.Web = web.NewWeb(a.Db, a.Args.DeployPort, a.Args.MediaLocation, &a.Queue, a.Args.Logging) 64 | a.Web.Deploy(a.Db) 65 | } 66 | 67 | return nil 68 | } 69 | 70 | func ParseConfigFile(fileName string, args *models.ArchiverArgs) error { 71 | 72 | _, err := toml.DecodeFile(fileName, &args) 73 | 74 | if err != nil { 75 | return err 76 | } 77 | return nil 78 | } 79 | 80 | func checkFlagMode(input string, guild string, channel string) models.Mode { 81 | var count int 82 | var mode models.Mode 83 | 84 | if guild != "" { 85 | count++ 86 | mode = models.GUILD 87 | } 88 | if channel != "" { 89 | count++ 90 | mode = models.CHANNEL 91 | } 92 | 93 | if count == 1 { 94 | return mode 95 | } else if count > 1 { 96 | return models.INVALID 97 | } else { 98 | return models.NONE 99 | } 100 | } 101 | 102 | //Returns true if valid 103 | func ValidFlags(job models.JobArgs, archiver models.ArchiverArgs) bool { 104 | if archiver.Export && archiver.Output != "" { 105 | fmt.Fprintln(os.Stderr, "Cannot use --export and --output together") 106 | return false 107 | } 108 | 109 | if job.Guild != "" && job.Channel != "" { 110 | fmt.Fprintln(os.Stderr, "Cannot use --guild and --channel together") 111 | return false 112 | } 113 | 114 | // If channel or guild in job args AND output DB empty / export false, exit 115 | if job.Guild != "" || job.Channel != "" { 116 | if archiver.Output == "" && archiver.Export == false && archiver.Input == "" { 117 | fmt.Fprintln(os.Stderr, "Must have an output") 118 | return false 119 | } 120 | if archiver.Output == "" && archiver.Export == false { 121 | fmt.Fprintln(os.Stderr, "Must have an output") 122 | return false 123 | } 124 | } 125 | 126 | if archiver.Deploy { 127 | if archiver.Output == "" { 128 | fmt.Fprintln(os.Stderr, "Cannot run webview without database connection") 129 | return false 130 | } 131 | } 132 | 133 | if (job.Before != "" || job.After != "") && job.FastUpdate != false { 134 | fmt.Fprintln(os.Stderr, "Cannot have before/after flags with fast-update") 135 | return false 136 | } 137 | 138 | if job.Before != "" && job.After != "" { 139 | if strings.Contains(job.Before, "-") && !strings.Contains(job.After, "-") || !strings.Contains(job.Before, "-") && strings.Contains(job.After, "-") { 140 | fmt.Fprintln(os.Stderr, "Before and after flags must be in the same format") 141 | return false 142 | } 143 | 144 | if !strings.Contains(job.Before, "-") && !strings.Contains(job.After, "-") { 145 | fmt.Fprintln(os.Stderr, "Invalid date format") 146 | return false 147 | } 148 | } 149 | return true 150 | } 151 | 152 | func InitCli() (models.JobArgs, models.ArchiverArgs) { 153 | 154 | // progress := flag.Bool("progress", false, "Displays progress of task. Enabling this will output verbose logging") 155 | before := flag.String("before", "", "Retrieves all messages before this date or message id") 156 | after := flag.String("after", "", "Retrieves all messages after this date or message id") 157 | fastUpdate := flag.Bool("fast-update", false, "Retrieves all message after the last downloaded message") 158 | downloadMedia := flag.Bool("download-media", false, "downloads embedded images and files from message") 159 | token := flag.String("t", "", "Sets user or bot token") 160 | output := flag.String("o", "", "Sets output db path") 161 | input := flag.String("i", "", "Input mode. Gets config from input file") 162 | guild := flag.String("guild", "", "Guild mode. Retrieves messages and channels from selected guild") 163 | channel := flag.String("channel", "", "Retrieves messages from selected channel") 164 | listen := flag.Bool("listen", false, "Listens for new messages/events and archives in real time. Can only be used with a bot account") 165 | listenChannels := flag.String("listen-channels", "", "Sets list of channels you wish to listen to") 166 | listenGuilds := flag.String("listen-guilds", "", "Sets list of guilds you wish to listen to") 167 | deploy := flag.Bool("deploy", false, "Deploys webapp") 168 | deployPort := flag.Int("deploy-port", 8080, "Set webview port") 169 | blacklistedChannels := flag.String("blacklisted-channels", "", "Sets list of blacklisted channel IDs as a string delimited by a comma. Can only be used with guild") 170 | mediaLocation := flag.String("media-location", "media", "Set location to store attachments and media") 171 | version := flag.Bool("version", false, "Checks version") 172 | logging := flag.Bool("log", true, "Verbose logging to file") 173 | progress := flag.Bool("progress", false, "Displays progress bar in terminal") 174 | export := flag.Bool("export", false, "Exports chat to file") 175 | flag.Parse() 176 | 177 | if *version { 178 | fmt.Println(VERSION) 179 | os.Exit(0) 180 | } 181 | 182 | mode := checkFlagMode(*input, *guild, *channel) 183 | 184 | if mode == models.INVALID { 185 | fmt.Fprintln(os.Stderr, "Invalid flags") 186 | os.Exit(1) 187 | } 188 | 189 | job := models.JobArgs{ 190 | Mode: mode, 191 | Before: *before, 192 | After: *after, 193 | FastUpdate: *fastUpdate, 194 | Guild: *guild, 195 | Channel: *channel, 196 | } 197 | 198 | args := models.ArchiverArgs{ 199 | DownloadMedia: *downloadMedia, 200 | MediaLocation: *mediaLocation, 201 | Token: *token, 202 | Output: *output, 203 | Input: *input, 204 | Listen: *listen, 205 | Deploy: *deploy, 206 | DeployPort: *deployPort, 207 | BlacklistedChannels: strings.Split(*blacklistedChannels, ","), 208 | ListenChannels: strings.Split(*listenChannels, ","), 209 | ListenGuilds: strings.Split(*listenGuilds, ","), 210 | Logging: *logging, 211 | Progress: *progress, 212 | Export: *export, 213 | } 214 | 215 | if !ValidFlags(job, args) { 216 | os.Exit(1) 217 | } 218 | return job, args 219 | } 220 | -------------------------------------------------------------------------------- /archiver/channel.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strconv" 7 | "strings" 8 | "time" 9 | 10 | "github.com/bwmarrin/discordgo" 11 | "github.com/vbauerster/mpb/v7" 12 | "github.com/yakabuff/discord-dl/common" 13 | "github.com/yakabuff/discord-dl/db" 14 | "github.com/yakabuff/discord-dl/job" 15 | "github.com/yakabuff/discord-dl/models" 16 | ) 17 | 18 | func (a Archiver) ChannelDownload(channel string, fastUpdate bool, after string, before string, state job.JobState) error { 19 | // case 1: only after flag. 20 | // case 2: only before flag 21 | // case 3: after AND before floag 22 | // case 4: --fast-update flag 23 | // case 5: contains no flag 24 | // log.Println("Downloading channel " + channel) 25 | 26 | c, err := a.Dg.Channel(channel) 27 | if err != nil { 28 | if err.(*discordgo.RESTError).Message.Code == 50001 { 29 | return nil 30 | } 31 | log.Println(err) 32 | 33 | return err 34 | } 35 | 36 | if c == nil { 37 | return nil 38 | } 39 | 40 | var guildID string 41 | if c.Type == discordgo.ChannelTypeGuildText || 42 | c.Type == discordgo.ChannelTypeDM || 43 | c.Type == discordgo.ChannelTypeGroupDM || 44 | c.Type == discordgo.ChannelTypeGuildPublicThread || 45 | c.Type == discordgo.ChannelTypeGuildPrivateThread { 46 | 47 | if c.Type == discordgo.ChannelTypeGuildText { 48 | guildID = c.GuildID 49 | } 50 | if fastUpdate { 51 | err = a.DownloadMessages(after, before, channel, guildID, true, state) 52 | } else { 53 | //Both before and after flags 54 | if before != "" && after != "" { 55 | err = a.DownloadMessages(after, before, channel, guildID, false, state) 56 | } else if before == "" && after == "" { 57 | //Both before and after empty 58 | err = a.DownloadMessages("", "", channel, guildID, false, state) 59 | } else { 60 | //Before empty OR after empty 61 | if strings.Contains(before, "-") && after == "" { 62 | err = a.DownloadRangeDate(after, before, channel, guildID, state) 63 | } else if strings.Contains(after, "-") && before == "" { 64 | err = a.DownloadRangeDate(after, before, channel, guildID, state) 65 | } else if !strings.Contains(after, "-") && before == "" { 66 | err = a.DownloadMessages(after, before, channel, guildID, false, state) 67 | } else { 68 | err = a.DownloadMessages(after, before, channel, guildID, false, state) 69 | } 70 | } 71 | } 72 | 73 | } else { 74 | return errors.New("Channel is not a text channel") 75 | } 76 | 77 | return err 78 | } 79 | 80 | //Convert after and before to Time if applicable 81 | //Convert Time for after and before to Discord Unix 82 | //Run DownloadMessage on before and after unix times 83 | func (a Archiver) DownloadRangeDate(after string, before string, channel_id string, guild_id string, state job.JobState) error { 84 | 85 | if before != "" { 86 | before_time, err := common.DateToTime(before) 87 | if err != nil { 88 | return err 89 | } 90 | //Generate initial snowflake message ID position 91 | bt := ((before_time.Unix()+1)*1000 - 1420070400000) << 22 92 | before_id := strconv.Itoa(int(bt)) 93 | 94 | if after != "" { 95 | after_time, _ := common.DateToTime(after) 96 | at := ((after_time.Unix()-1)*1000 - 1420070400000) << 22 97 | after_id := strconv.Itoa(int(at)) 98 | err := a.DownloadMessages(before_id, after_id, channel_id, guild_id, false, state) 99 | if err != nil { 100 | return err 101 | } 102 | } else { 103 | err := a.DownloadMessages(before_id, "", channel_id, guild_id, false, state) 104 | if err != nil { 105 | return err 106 | } 107 | } 108 | 109 | } else { 110 | if after != "" { 111 | after_time, _ := common.DateToTime(after) 112 | fmt.Println(after_time) 113 | at := ((after_time.Unix()-1)*1000 - 1420070400000) << 22 114 | after_id := strconv.Itoa(int(at)) 115 | a.DownloadMessages("", after_id, channel_id, guild_id, false, state) 116 | } else { 117 | a.DownloadMessages("", "", channel_id, guild_id, false, state) 118 | } 119 | } 120 | 121 | return nil 122 | } 123 | 124 | func (a Archiver) DownloadMessages(before_id string, after_id string, channel_id string, guild_id string, fast_update bool, state job.JobState) error { 125 | var _beforeid string = before_id 126 | var _afterid string = after_id 127 | 128 | messages, error := a.Dg.ChannelMessages(channel_id, 100, before_id, "", "") 129 | if error != nil { 130 | log.Error(error) 131 | 132 | return error 133 | } 134 | //Start archiving messages 135 | var in_range bool = true 136 | for len(messages) != 0 && in_range { 137 | for _, m := range messages { 138 | 139 | id := m.ID 140 | 141 | m.GuildID = guild_id 142 | if after_id != "" { 143 | if id > after_id { 144 | // log.Printf("Downloading message %s %s\n", m.Timestamp, m.ID) 145 | before_id = id 146 | //insert into db 147 | err := a.ProcessMessages(m, fast_update, a.Args.DownloadMedia, state.Id) 148 | if err != nil { 149 | if errors.Is(err, db.UniqueConstraintError) { 150 | return nil 151 | } 152 | log.Error(err) 153 | return err 154 | } 155 | 156 | CalculateChannelProgress(_afterid, _beforeid, m.ID, state.Progress, state.Bar) 157 | if *state.Status == job.CANCELLED { 158 | return nil 159 | } 160 | 161 | //Fetch threads if exist 162 | if m.Thread != nil { 163 | log.Println("Thread spotted. Queueing thread: " + m.Thread.ID) 164 | 165 | ja := models.JobArgs{Mode: models.CHANNEL, Before: "", After: "", FastUpdate: fast_update, Guild: "", Channel: m.Thread.ID} 166 | job := job.NewJob(ja) 167 | err := a.Queue.Enqueue(job) 168 | if err != nil { 169 | log.Error(err) 170 | } 171 | } 172 | 173 | } else { 174 | in_range = false 175 | break 176 | } 177 | } else { 178 | // log.Printf("Downloading message %s %s %s\n", m.Timestamp, m.ID, m.ChannelID) 179 | err := a.ProcessMessages(m, fast_update, a.Args.DownloadMedia, state.Id) 180 | before_id = id 181 | if err != nil { 182 | if errors.Is(err, db.UniqueConstraintError) { 183 | return nil 184 | } 185 | return err 186 | } 187 | 188 | CalculateChannelProgress(_afterid, _beforeid, m.ID, state.Progress, state.Bar) 189 | if *state.Status == job.CANCELLED { 190 | return nil 191 | } 192 | 193 | if m.Thread != nil { 194 | 195 | log.Info("Thread spotted. Traversing thread: " + m.Thread.ID) 196 | 197 | ja := models.JobArgs{Mode: models.CHANNEL, Before: "", After: "", FastUpdate: fast_update, Guild: "", Channel: m.Thread.ID} 198 | job := job.NewJob(ja) 199 | err := a.Queue.Enqueue(job) 200 | if err != nil { 201 | log.Error(err) 202 | } 203 | 204 | } 205 | } 206 | } 207 | if *state.Status == job.CANCELLED { 208 | return nil 209 | } 210 | messages, error = a.Dg.ChannelMessages(channel_id, 100, before_id, "", "") 211 | if error != nil { 212 | return error 213 | } 214 | } 215 | return nil 216 | } 217 | 218 | func CalculateChannelProgress(afterID string, beforeID string, currMessageID string, progress *int, bar *mpb.Bar) { 219 | //If only after empty: after == discordEpoch, before = before. after = after - after. before = before - after. curr = curr - after 220 | //If only before empty: after == after, before = curr unix time. after = after - after. before = before - after. curr = curr - after 221 | //If both empty.. 222 | //If neither empty: after = after, before = before. after = after - after. before = before - after. curr = curr - after 223 | var startTime int64 224 | var endTime int64 225 | // if after == 0, assume discord epoch 226 | if afterID == "" && beforeID != "" { 227 | endTime = common.DiscordEpoch 228 | startTime, _ = common.SnowflakeToUnixTime(beforeID) 229 | } else if afterID != "" && beforeID == "" { 230 | endTime, _ = common.SnowflakeToUnixTime(afterID) 231 | startTime = time.Now().Unix() 232 | } else if afterID == "" && beforeID == "" { 233 | endTime = common.DiscordEpoch / 1000 234 | startTime = time.Now().Unix() 235 | } else { 236 | endTime, _ = common.SnowflakeToUnixTime(afterID) 237 | startTime, _ = common.SnowflakeToUnixTime(beforeID) 238 | } 239 | 240 | currTime, _ := common.SnowflakeToUnixTime(currMessageID) 241 | //Normalize numbers to calculate percentage 242 | var quotient float64 = float64(((float64(startTime) - float64(endTime)) - (float64(currTime) - float64(endTime)))) / (float64(startTime) - float64(endTime)) 243 | pct := quotient * 100 244 | *progress = int(pct) 245 | bar.SetCurrent(int64(pct)) 246 | // log.Printf("Progress is %d, start time: %d, end time: %d, curr time: %d", *progress, startTime, endTime, currTime) 247 | } 248 | -------------------------------------------------------------------------------- /archiver/discord.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "strings" 5 | "time" 6 | 7 | "github.com/bwmarrin/discordgo" 8 | "github.com/yakabuff/discord-dl/common" 9 | "github.com/yakabuff/discord-dl/models" 10 | ) 11 | 12 | func (a Archiver) CreateConnection() (error, *discordgo.Session) { 13 | 14 | dg, err := discordgo.New(a.Args.Token) 15 | if err != nil { 16 | log.Error(err.Error()) 17 | return err, nil 18 | } 19 | err = dg.Open() 20 | 21 | if err != nil { 22 | log.Error(err.Error()) 23 | return err, nil 24 | } 25 | u, err := dg.User("@me") 26 | if err != nil { 27 | log.Error(err.Error()) 28 | return err, nil 29 | } 30 | log.Infof("discord-dl has succesfully logged into %s#%s %s\n", u.Username, u.Discriminator, u.ID) 31 | 32 | return nil, dg 33 | } 34 | 35 | func (a Archiver) addHandlers() { 36 | a.Dg.Identify.Intents = discordgo.IntentsGuildMessages 37 | // log.Println("Adding discord event handlers") 38 | a.Dg.AddHandler(a.messageListen) 39 | a.Dg.AddHandler(a.messageUpdateListen) 40 | } 41 | 42 | func (a Archiver) messageListen(dg *discordgo.Session, m *discordgo.MessageCreate) { 43 | 44 | user, _ := a.Dg.User("@me") 45 | // Ignore all messages created by the bot itself 46 | if m.Author.ID == user.ID { 47 | return 48 | } 49 | if !common.Contains(a.Args.ListenChannels, m.ChannelID) || !common.Contains(a.Args.ListenGuilds, m.GuildID) { 50 | return 51 | } 52 | // log.Println("[LISTEN] Detected new message. Fetching message " + m.ID + " from" + m.ChannelID) 53 | guildID := m.GuildID 54 | //If message contains something that resembles a URL, wait a few seconds for discord to get embed info 55 | //https://github.com/bwmarrin/discordgo/issues/1066 56 | if strings.Contains(m.Content, "https://") || strings.Contains(m.Content, "http://") { 57 | go func(ID string, ChannelID string) { 58 | time.Sleep(time.Second * 5) 59 | m, err := dg.ChannelMessage(ChannelID, ID) 60 | if err != nil { 61 | log.Error("Could not fetch " + m.ID + " from " + m.ChannelID) 62 | return 63 | } 64 | m.GuildID = guildID 65 | err = a.InsertMessage(m, false, a.Args.DownloadMedia) 66 | if err != nil { 67 | log.Error("Could not insert message " + m.ID + " from " + m.ChannelID) 68 | } 69 | }(m.ID, m.ChannelID) 70 | } else { 71 | m, err := dg.ChannelMessage(m.ChannelID, m.ID) 72 | if err != nil { 73 | log.Error("Could not fetch " + m.ID + " from " + m.ChannelID) 74 | return 75 | } 76 | m.GuildID = guildID 77 | err = a.InsertMessage(m, false, a.Args.DownloadMedia) 78 | if err != nil { 79 | log.Error("Could not insert message " + m.ID + " from " + m.ChannelID) 80 | } 81 | } 82 | } 83 | 84 | func (a Archiver) messageUpdateListen(dg *discordgo.Session, m *discordgo.MessageUpdate) { 85 | //Note: If message with link is sent, it does not return all fields.... Get message ID and channelID and retrieve message this way instead. 86 | 87 | message, err := dg.ChannelMessage(m.ChannelID, m.ID) 88 | if err != nil { 89 | log.Error("Failed to get edit: " + m.ID + " " + m.ChannelID) 90 | } 91 | if !common.Contains(a.Args.ListenChannels, message.ChannelID) || !common.Contains(a.Args.ListenGuilds, message.GuildID) { 92 | return 93 | } 94 | if message.Author.ID == dg.State.User.ID { 95 | return 96 | } 97 | // log.Println("[LISTEN] Detected new message edit. Fetching message " + m.ID + " from" + m.ChannelID) 98 | //filter out all messages that do not have an edit timestamp. Only listen for content edits 99 | 100 | if m.EditedTimestamp != nil { 101 | edited_timestamp := message.EditedTimestamp.Unix() 102 | edit := models.NewEdit(message.ID, edited_timestamp, message.Content) 103 | a.InsertEdit(edit) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /archiver/export.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "io/fs" 9 | "os" 10 | "strings" 11 | "time" 12 | 13 | "github.com/bwmarrin/discordgo" 14 | "github.com/yakabuff/discord-dl/common" 15 | "github.com/yakabuff/discord-dl/models" 16 | ) 17 | 18 | func (a Archiver) ExportMessage(m *discordgo.Message, downloadMedia bool, jobId string) error { 19 | timestamp, _ := discordgo.SnowflakeTimestamp(m.ID) 20 | timestamp_unix := timestamp.Unix() 21 | id := m.ID 22 | content := m.Content 23 | author_id := m.Author.ID 24 | author_username := m.Author.Username 25 | channel_id := m.ChannelID 26 | guild_id := m.GuildID 27 | var reply_to string 28 | var editedTimestamp int64 = -1 29 | var threadId string 30 | //Check if message is a reply 31 | if m.MessageReference != nil { 32 | reply_to = (*m).MessageReference.MessageID 33 | } 34 | if m.EditedTimestamp != nil { 35 | editedTimestamp = m.EditedTimestamp.Unix() 36 | } 37 | if m.Thread != nil { 38 | threadId = m.Thread.ID 39 | } 40 | 41 | var embeds []models.Embed 42 | var attachments []models.Attachment 43 | 44 | //TODO: If hash exists for embed, don't redownload. Sometimes, embed images change eg: github -> num stars goes up in image 45 | //If it has embed, download embed 46 | for _, i := range m.Embeds { 47 | //If image != null, download image, add URL to embed, download 48 | //If thumbnail != null downlaod thumbnail, add URL to embed, download 49 | //If video != null download video, add URL to embed, download 50 | //Iterate through fields for every embed. Combine fields, seperate with \n 51 | 52 | var fields string 53 | if i.Fields != nil { 54 | for _, j := range i.Fields { 55 | fields = fields + j.Name + "\n" + j.Value + "\n" 56 | } 57 | } 58 | var imageURL string 59 | if i.Image != nil { 60 | imageURL = i.Image.URL 61 | } 62 | var videoURL string 63 | if i.Video != nil { 64 | videoURL = i.Video.URL 65 | } 66 | var thumbnailURL string 67 | if i.Thumbnail != nil { 68 | thumbnailURL = i.Thumbnail.URL 69 | } 70 | var authorName string 71 | var authorURL string 72 | if i.Author != nil { 73 | authorName = i.Author.Name 74 | authorURL = i.Author.URL 75 | } 76 | 77 | var footerText string 78 | if i.Footer != nil { 79 | footerText = i.Footer.Text 80 | } 81 | var dateRetrieved string = fmt.Sprintf("%d", time.Now().Unix()) 82 | embed := models.NewEmbed(m.ID, 83 | dateRetrieved, 84 | i.URL, 85 | i.Title, 86 | i.Description, 87 | i.Timestamp, 88 | thumbnailURL, 89 | "", 90 | imageURL, 91 | "", 92 | videoURL, 93 | "", 94 | footerText, 95 | authorName, 96 | authorURL, 97 | fields, 98 | ) 99 | 100 | //Download embed media 101 | if i.Image != nil { 102 | sum, err := common.DownloadFile(i.Image.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 103 | if err != nil { 104 | var e *fs.PathError 105 | if errors.As(err, &e) { 106 | log.Fatal(err) 107 | } 108 | log.Error(err) 109 | } 110 | 111 | embed.EmbedImageHash = sum 112 | } 113 | 114 | if i.Thumbnail != nil { 115 | sum, err := common.DownloadFile(i.Thumbnail.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 116 | if err != nil { 117 | log.Error(err) 118 | } 119 | embed.EmbedThumbnailHash = sum 120 | } 121 | //Download videos in embeds from discord ONLY. 122 | if i.Video != nil && strings.HasPrefix(i.Video.URL, "https://cdn.discordapp.com") { 123 | sum, err := common.DownloadFile(i.Video.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 124 | if err != nil { 125 | log.Error(err) 126 | } 127 | 128 | embed.EmbedVideoHash = sum 129 | } 130 | 131 | embeds = append(embeds, embed) 132 | } 133 | 134 | for _, i := range m.Attachments { 135 | attachment := models.NewAttachment(i.ID, m.ID, i.Filename, i.URL, "") 136 | 137 | //Download embed media 138 | hash, err := common.DownloadFile(i.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 139 | if err != nil { 140 | log.Error(err) 141 | } 142 | 143 | attachment.AttachmentHash = hash 144 | 145 | attachments = append(attachments, attachment) 146 | } 147 | msg := models.NewMessageJson(id, channel_id, guild_id, timestamp_unix, content, author_id, author_username, reply_to, fmt.Sprintf("%d", editedTimestamp), threadId, embeds, attachments) 148 | 149 | err := WriteMessageJson(msg, jobId) 150 | return err 151 | } 152 | 153 | // We will need to incrementally append to the file. 154 | // It will be impossible to put 1million messages all in a struct 155 | // We will need to decompose the channel into messages and append them individually 156 | // 1) Files will be .json 157 | // 2) Open file. Check if it is empty. 158 | // 3) If not empty, check if there is content. Check json array ([] symbols) 159 | // 4) If empty, construct json document symbols 160 | // 5) If not empty, delete ] symbol. Add message struct. Delete , symbol. Re add ] symbol 161 | // file.Seek(0, 2) to go to end of file 162 | func WriteMessageJson(msg models.MessageJson, jobID string) error { 163 | name := msg.ChannelId + "_" + jobID + ".json" 164 | var file *os.File 165 | //If empty, create, else read last char of file. if ] character, assume it is json. delete char, append and re add ]. if ] not found, append [, append msg and append ] 166 | 167 | _, err := os.Stat(name) 168 | 169 | if errors.Is(err, os.ErrNotExist) { 170 | 171 | file, err = os.Create(name) 172 | if err != nil { 173 | return err 174 | } 175 | defer file.Close() 176 | //Write [ character 177 | file.WriteString("[\n") 178 | //Write message (no trailing comma) 179 | b, err := json.MarshalIndent(msg, "", "\t") 180 | if err != nil { 181 | return err 182 | } 183 | file.WriteString(string(b) + "\n") 184 | //Write ] character 185 | file.WriteString("]") 186 | 187 | } else { 188 | file, err = os.OpenFile(name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777) 189 | if err != nil { 190 | return err 191 | } 192 | defer file.Close() 193 | // If file already exists, we can assume that there are already messages in the file 194 | // Delete last ] character. If does not exist, return error 195 | 196 | err := deleteLastSquareBracket(file) 197 | if err != nil { 198 | log.Error(err) 199 | return err 200 | } 201 | // Write message (prefixed comma) 202 | b, err := json.MarshalIndent(msg, "", "\t") 203 | if err != nil { 204 | return err 205 | } 206 | file.WriteString("," + "\n" + string(b) + "\n") 207 | // Write ] character 208 | file.WriteString("]") 209 | } 210 | 211 | return nil 212 | } 213 | 214 | //Verify last line ']' and first line '[' 215 | //Second line = '{' and second last line = '}' 216 | func verifyExportStructure(f *os.File) bool { 217 | valid := false 218 | char := make([]byte, 1) 219 | f, _ = os.Open(f.Name()) 220 | f.Seek(-1, io.SeekEnd) 221 | f.Read(char) 222 | 223 | if char[0] == 93 { 224 | valid = true 225 | } else { 226 | valid = false 227 | } 228 | 229 | f.Seek(-2, io.SeekEnd) 230 | f.Read(char) 231 | 232 | if char[0] == 125 { 233 | valid = true 234 | } else { 235 | valid = false 236 | } 237 | 238 | f.Seek(1, io.SeekStart) 239 | f.Read(char) 240 | 241 | if char[0] == 91 { 242 | valid = true 243 | } else { 244 | valid = false 245 | } 246 | 247 | f.Seek(2, io.SeekStart) 248 | f.Read(char) 249 | 250 | if char[0] == 123 { 251 | valid = true 252 | } else { 253 | valid = false 254 | } 255 | 256 | return valid 257 | } 258 | 259 | //Truncate file by 2 bytes. (\n and ]) 260 | func deleteLastSquareBracket(file *os.File) error { 261 | if verifyExportStructure(file) == false { 262 | return errors.New("Invalid export structure") 263 | } 264 | 265 | stat, err := file.Stat() 266 | if err != nil { 267 | return err 268 | } 269 | filesize := stat.Size() 270 | 271 | return os.Truncate(file.Name(), filesize-2) 272 | } 273 | -------------------------------------------------------------------------------- /archiver/export_test.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/yakabuff/discord-dl/models" 8 | ) 9 | 10 | func TestExport(t *testing.T) { 11 | msg := models.MessageJson{MessageId: "messageid", ChannelId: "channelid"} 12 | msg2 := models.MessageJson{MessageId: "messageid2", ChannelId: "channelid"} 13 | err := WriteMessageJson(msg, "420420") 14 | if err != nil { 15 | t.Error(err) 16 | } 17 | err = WriteMessageJson(msg2, "420420") 18 | if err != nil { 19 | 20 | t.Error(err) 21 | } 22 | f, _ := os.Open("channelid_420420.json") 23 | stat, err := f.Stat() 24 | if err != nil { 25 | t.Error(err) 26 | } 27 | filesize := stat.Size() 28 | 29 | if filesize != 407 { 30 | t.Error(err) 31 | } 32 | 33 | e := os.Remove("channelid_420420.json") 34 | if e != nil { 35 | t.Error(err) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /archiver/guild.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "github.com/bwmarrin/discordgo" 5 | "github.com/yakabuff/discord-dl/common" 6 | ) 7 | 8 | func (a Archiver) GetChannelsGuild(guildID string) ([]string, error) { 9 | 10 | channels, err := a.Dg.GuildChannels(guildID) 11 | if err != nil { 12 | log.Error("Could not find guild") 13 | return nil, err 14 | } 15 | res := []string{} 16 | for i, val := range channels { 17 | _, err := a.Dg.Channel(val.ID) 18 | if err == nil { 19 | if val.Type == discordgo.ChannelTypeGuildText && !common.Contains(a.Args.BlacklistedChannels, val.ID) { 20 | res = append(res, channels[i].ID) 21 | } 22 | 23 | } 24 | 25 | } 26 | return res, nil 27 | } 28 | 29 | // func contains(channels []string, id string) bool { 30 | // for _, a := range channels { 31 | // if a == id { 32 | // return true 33 | // } 34 | // } 35 | // return false 36 | // } 37 | 38 | // c, err := a.Dg.Channel(channel) 39 | // if err != nil { 40 | // if err.(*discordgo.RESTError).Message.Code == 50001 { 41 | // log.Println("Do not have permission for channel") 42 | // return nil 43 | // } 44 | // log.Println(err) 45 | 46 | // return err 47 | // } 48 | -------------------------------------------------------------------------------- /archiver/message.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io/fs" 7 | "strings" 8 | "time" 9 | 10 | "github.com/bwmarrin/discordgo" 11 | "github.com/yakabuff/discord-dl/common" 12 | "github.com/yakabuff/discord-dl/db" 13 | "github.com/yakabuff/discord-dl/models" 14 | ) 15 | 16 | func (a Archiver) InsertMessage(m *discordgo.Message, fastUpdate bool, downloadMedia bool) error { 17 | //Try adding message to DB 18 | //fast update, unique constraint error -> log and skip message(return fast_update error) 19 | //fast update, non unique constraint error -> return error 20 | //non fast update, unique constriant error -> log, continue(do not return anything) and download edits, attachments, embeds 21 | //non fast update non unique constraint error -> return error 22 | 23 | //Add to edits table if does not exist 24 | //Add to attachments if not exist 25 | //Add to embed if not exist 26 | 27 | timestamp, _ := discordgo.SnowflakeTimestamp(m.ID) 28 | timestamp_unix := timestamp.Unix() 29 | id := m.ID 30 | content := m.Content 31 | author_id := m.Author.ID 32 | author_username := m.Author.Username 33 | channel_id := m.ChannelID 34 | guild_id := m.GuildID 35 | var reply_to string 36 | var editedTimestamp int64 = -1 37 | var threadId string 38 | //Check if message is a reply 39 | if m.MessageReference != nil { 40 | reply_to = (*m).MessageReference.MessageID 41 | } 42 | if m.EditedTimestamp != nil { 43 | editedTimestamp = m.EditedTimestamp.Unix() 44 | } 45 | if m.Thread != nil { 46 | threadId = m.Thread.ID 47 | } 48 | msg := models.NewMessage(id, channel_id, guild_id, timestamp_unix, content, author_id, author_username, reply_to, editedTimestamp, threadId) 49 | 50 | errMsg := a.Db.InsertMessage(msg) 51 | 52 | if fastUpdate == true && errMsg != nil { 53 | //check for unique constraint err. If found, exit program 54 | if !errors.Is(errMsg, db.UniqueConstraintError) { 55 | log.Error(errMsg) 56 | return errMsg 57 | } else { 58 | log.Info("Fast update triggered") 59 | //return fast update error 60 | return models.FastUpdateError 61 | } 62 | 63 | } else if fastUpdate == false && errMsg != nil { 64 | if !errors.Is(errMsg, db.UniqueConstraintError) { 65 | log.Println(errMsg) 66 | return errMsg 67 | } 68 | } 69 | 70 | //Check if it is edited message. 71 | //If message is edited, insert edit. Check if uniqueConstraintError 72 | if m.EditedTimestamp != nil { 73 | edit := models.NewEdit(id, editedTimestamp, content) 74 | errEdit := a.InsertEdit(edit) 75 | if errEdit != nil { 76 | log.Error(errEdit) 77 | return errEdit 78 | } 79 | } 80 | 81 | //TODO: If hash exists for embed, don't redownload. Sometimes, embed images change eg: github -> num stars goes up in image 82 | //If it has embed, download embed 83 | for _, i := range m.Embeds { 84 | //If image != null, download image, add URL to embed, download 85 | //If thumbnail != null downlaod thumbnail, add URL to embed, download 86 | //If video != null download video, add URL to embed, download 87 | //Iterate through fields for every embed. Combine fields, seperate with \n 88 | 89 | var fields string 90 | if i.Fields != nil { 91 | for _, j := range i.Fields { 92 | fields = fields + j.Name + "\n" + j.Value + "\n" 93 | } 94 | } 95 | var imageURL string 96 | if i.Image != nil { 97 | imageURL = i.Image.URL 98 | } 99 | var videoURL string 100 | if i.Video != nil { 101 | videoURL = i.Video.URL 102 | } 103 | var thumbnailURL string 104 | if i.Thumbnail != nil { 105 | thumbnailURL = i.Thumbnail.URL 106 | } 107 | var authorName string 108 | var authorURL string 109 | if i.Author != nil { 110 | authorName = i.Author.Name 111 | authorURL = i.Author.URL 112 | } 113 | 114 | var footerText string 115 | if i.Footer != nil { 116 | footerText = i.Footer.Text 117 | } 118 | var dateRetrieved string = fmt.Sprintf("%d", time.Now().Unix()) 119 | embed := models.NewEmbed(m.ID, 120 | dateRetrieved, 121 | i.URL, 122 | i.Title, 123 | i.Description, 124 | i.Timestamp, 125 | thumbnailURL, 126 | "", 127 | imageURL, 128 | "", 129 | videoURL, 130 | "", 131 | footerText, 132 | authorName, 133 | authorURL, 134 | fields, 135 | ) 136 | 137 | //Download embed media 138 | if i.Image != nil { 139 | sum, err := common.DownloadFile(i.Image.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 140 | if err != nil { 141 | var e *fs.PathError 142 | if errors.As(err, &e) { 143 | log.Fatal(err) 144 | } 145 | log.Error(err) 146 | } 147 | 148 | embed.EmbedImageHash = sum 149 | } 150 | 151 | if i.Thumbnail != nil { 152 | sum, err := common.DownloadFile(i.Thumbnail.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 153 | if err != nil { 154 | log.Error(err) 155 | } 156 | embed.EmbedThumbnailHash = sum 157 | } 158 | //Download videos in embeds from discord ONLY. 159 | if i.Video != nil && strings.HasPrefix(i.Video.URL, "https://cdn.discordapp.com") { 160 | sum, err := common.DownloadFile(i.Video.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 161 | if err != nil { 162 | log.Error(err) 163 | } 164 | 165 | embed.EmbedVideoHash = sum 166 | } 167 | 168 | errEmbed := a.InsertEmbed(embed) 169 | if errEmbed != nil { 170 | log.Error(errEmbed) 171 | return errEmbed 172 | } 173 | } 174 | 175 | for _, i := range m.Attachments { 176 | attachment := models.NewAttachment(i.ID, m.ID, i.Filename, i.URL, "") 177 | 178 | //Download embed media 179 | hash, err := common.DownloadFile(i.URL, m.ChannelID, a.Args.MediaLocation, downloadMedia) 180 | if err != nil { 181 | log.Error(err) 182 | } 183 | 184 | attachment.AttachmentHash = hash 185 | 186 | errAttachment := a.InsertAttachment(attachment) 187 | if errAttachment != nil { 188 | return errAttachment 189 | } 190 | } 191 | return nil 192 | } 193 | 194 | //Note on threads. 195 | //if MessageType=21, this signifies thread top message. this message has a threads field which is a channel ID 196 | //All messages in the thread has the channelID of that thread and not the channelID the thread is in. 197 | //Note on media 198 | // 199 | 200 | func (a Archiver) InsertEdit(edit models.Edit) error { 201 | errEdit := a.Db.InsertEdit(edit) 202 | if !errors.Is(errEdit, db.UniqueConstraintError) { 203 | return errEdit 204 | } 205 | return nil 206 | } 207 | 208 | func (a Archiver) InsertEmbed(embed models.Embed) error { 209 | errEmbed := a.Db.InsertEmbed(embed) 210 | if !errors.Is(errEmbed, db.UniqueConstraintError) { 211 | return errEmbed 212 | } 213 | return nil 214 | } 215 | 216 | func (a Archiver) InsertAttachment(attachment models.Attachment) error { 217 | errAttachment := a.Db.InsertAttachment(attachment) 218 | if !errors.Is(errAttachment, db.UniqueConstraintError) { 219 | return errAttachment 220 | } 221 | return nil 222 | } 223 | 224 | func (a Archiver) ProcessMessages(m *discordgo.Message, fastUpdate bool, downloadMedia bool, id string) error { 225 | 226 | if a.Args.Output != "" && a.Args.Export == false { 227 | //If database, insertMessage 228 | err := a.InsertMessage(m, fastUpdate, downloadMedia) 229 | return err 230 | } else { 231 | //If export, export to file 232 | err := a.ExportMessage(m, downloadMedia, id) 233 | return err 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /archiver/structure.go: -------------------------------------------------------------------------------- 1 | package archiver 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/mattn/go-sqlite3" 7 | "github.com/yakabuff/discord-dl/common" 8 | "github.com/yakabuff/discord-dl/db" 9 | ) 10 | 11 | //get channel metadata 12 | 13 | //get guild metadasta 14 | 15 | //could there be a situation where 2 jobs are fetching metadata at same time. both query channel names, see last name is different and date is different too 16 | //both try to insert same name with their current time (might be slightly different but still duplicates) 17 | //make get channel-metadata a job.. when you make a get_channel job, also make a get_channel_metadata job. don't combine them. 18 | //then limit the number of 19 | //idea: desconstruct jobs by type: guild/structure/channel but also guild id, channel id... guilds should be deconstructed into channels. the only guild specific thing guild meta data 20 | 21 | // queue: {[channel1, channel1], [channel2, channel2, channel2]}. then process first element of every array in queue concurrently? 22 | 23 | func (a Archiver) InsertChannelID(channel string) error { 24 | errChannel := a.Db.InsertChannelID(channel) 25 | 26 | if errChannel != nil { 27 | log.Error(errChannel.Error()) 28 | return errChannel 29 | } 30 | return nil 31 | } 32 | 33 | func (a Archiver) InsertGuildID(guild string) error { 34 | errGuild := a.Db.InsertGuildID(guild) 35 | 36 | if !errors.Is(errGuild, db.UniqueConstraintError) { 37 | return errGuild 38 | } 39 | return nil 40 | } 41 | 42 | //Index guild metadata: icon, name, banner 43 | func (a Archiver) IndexGuild(guild string) error { 44 | g, err := a.Dg.Guild(guild) 45 | if err != nil { 46 | return err 47 | } 48 | //Insert guild ID 49 | err = a.InsertGuildID(g.ID) 50 | if err != nil { 51 | return err 52 | } 53 | //Insert guild name if different 54 | //make sure latest guild name != g.Name 55 | 56 | err = a.Db.InsertGuildNames(g.ID, g.Name) 57 | if err != nil { 58 | var sqliteErr sqlite3.Error 59 | if errors.As(err, &sqliteErr) { 60 | if int(sqliteErr.Code) != 19 && int(sqliteErr.ExtendedCode) != 1811 { 61 | return err 62 | } 63 | } 64 | } 65 | 66 | if g.ID != "" { 67 | iconHash, err := common.DownloadFile(g.IconURL(), g.ID, a.Args.MediaLocation, true) 68 | if err != nil { 69 | log.Error(err) 70 | } 71 | 72 | //Insert and download guild icon if different. If g.Icon != select icon_hash from guild_icon ORDER BY date ASC LIMIT 1 73 | 74 | err = a.Db.InsertGuildIcons(g.ID, iconHash) 75 | if err != nil { 76 | var sqliteErr sqlite3.Error 77 | if errors.As(err, &sqliteErr) { 78 | if int(sqliteErr.Code) != 19 && int(sqliteErr.ExtendedCode) != 1811 { 79 | return err 80 | } 81 | } 82 | } 83 | } 84 | var bannerHash string 85 | if g.BannerURL() != "" { 86 | bannerHash, err = common.DownloadFile(g.BannerURL(), g.ID, a.Args.MediaLocation, true) 87 | if err != nil { 88 | log.Error(err) 89 | } 90 | //Insert and download guild banner if different 91 | } 92 | err = a.Db.InsertGuildBanner(g.ID, bannerHash) 93 | if err != nil { 94 | var sqliteErr sqlite3.Error 95 | if errors.As(err, &sqliteErr) { 96 | if int(sqliteErr.Code) != 19 && int(sqliteErr.ExtendedCode) != 1811 { 97 | return err 98 | } 99 | } 100 | } 101 | 102 | //Update guild with new metadata (if any) 103 | err = a.Db.UpdateGuildMetaTransaction(g.ID) 104 | return err 105 | } 106 | 107 | //Index channel metadata: topic, name, guild it belongs to, channel type 108 | func (a Archiver) IndexChannel(channel string) error { 109 | if a.Args.Output == "" { 110 | return nil 111 | } 112 | c, err := a.Dg.Channel(channel) 113 | if err != nil { 114 | log.Error(err) 115 | return err 116 | } 117 | 118 | //Insert channel ID 119 | err = a.InsertChannelID(c.ID) 120 | if err != nil { 121 | log.Error(err) 122 | return err 123 | } 124 | 125 | err = a.InsertGuildID(c.GuildID) 126 | if err != nil { 127 | log.Error(err) 128 | return err 129 | } 130 | 131 | err = a.IndexGuild(c.GuildID) 132 | if err != nil { 133 | log.Error(err) 134 | return err 135 | } 136 | 137 | err = a.Db.InsertChannelNames(c.ID, c.Name) 138 | if err != nil { 139 | var sqliteErr sqlite3.Error 140 | if errors.As(err, &sqliteErr) { 141 | if int(sqliteErr.Code) != 19 && int(sqliteErr.ExtendedCode) != 1811 { 142 | log.Error(err) 143 | return err 144 | } 145 | } 146 | } 147 | 148 | err = a.Db.InsertChannelTopic(c.ID, c.Topic) 149 | if err != nil { 150 | var sqliteErr sqlite3.Error 151 | if errors.As(err, &sqliteErr) { 152 | if int(sqliteErr.Code) != 19 && int(sqliteErr.ExtendedCode) != 1811 { 153 | log.Error(err) 154 | return err 155 | } 156 | } 157 | } 158 | err = a.Db.UpdateChannelMetaTransaction(c.ID, c.IsThread(), c.GuildID) 159 | if err != nil { 160 | log.Error(err) 161 | return err 162 | } 163 | 164 | return err 165 | } 166 | -------------------------------------------------------------------------------- /common/logger.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/sirupsen/logrus" 7 | log "github.com/sirupsen/logrus" 8 | ) 9 | 10 | func NewErrLogger() (*log.Logger, error) { 11 | file, err := os.OpenFile("errors.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) 12 | if err != nil { 13 | return nil, err 14 | } 15 | var log = logrus.New() 16 | log.Out = file 17 | return log, nil 18 | } 19 | 20 | func NewWebLogger() (*log.Logger, error) { 21 | file, err := os.OpenFile("web.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | var log = logrus.New() 27 | log.Out = file 28 | return log, nil 29 | } 30 | -------------------------------------------------------------------------------- /common/util.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "time" 7 | 8 | // "github.com/bwmarrin/discordgo" 9 | "crypto/sha256" 10 | "fmt" 11 | "io" 12 | "net/http" 13 | "os" 14 | "path/filepath" 15 | "strconv" 16 | "strings" 17 | 18 | "github.com/bwmarrin/discordgo" 19 | ) 20 | 21 | const DiscordEpoch = 1420070400000 22 | 23 | //160724514639 24 | 25 | //Turns a date in form yyyy-mm-dd into discord unix time (epoch at 2015-01-01) 26 | func DateToDiscordTime(date string) (int64, error) { 27 | split := strings.Split(date, "-") 28 | //["2021", "02", "23"] 29 | year, err := strconv.ParseInt(split[0], 10, 64) 30 | if err != nil { 31 | return 0, err 32 | } 33 | month, err := strconv.ParseInt(split[1], 10, 64) 34 | if err != nil { 35 | return 0, err 36 | } 37 | day, err := strconv.ParseInt(split[2], 10, 64) 38 | if err != nil { 39 | return 0, err 40 | } 41 | zone, _ := time.Now().Zone() 42 | loc, _ := time.LoadLocation(zone) 43 | //make unix time and convert to discord time 44 | t := time.Date(int(year), time.Month(month), int(day), 0, 0, 0, 0, loc) 45 | 46 | unix := t.Unix()*1000 - DiscordEpoch 47 | return unix, nil 48 | 49 | } 50 | 51 | //Turns a date in form yyyy-mm-dd HH:MM:SS TIMEZONE into time 52 | func DateToTime(date string) (time.Time, error) { 53 | //[yyyy-mm-dd, HH:MM:SS, TIMEZONE] 54 | split := strings.Split(date, " ") 55 | //["2021", "02", "23"] 56 | dates := strings.Split(split[0], "-") 57 | //["12", "11", "42"] 58 | times := strings.Split(split[1], ":") 59 | //EST 60 | timeZone := split[2] 61 | 62 | year, err := strconv.ParseInt(dates[0], 10, 64) 63 | if err != nil { 64 | return time.Time{}, err 65 | } 66 | month, err := strconv.ParseInt(dates[1], 10, 64) 67 | if err != nil { 68 | return time.Time{}, err 69 | } 70 | day, err := strconv.ParseInt(dates[2], 10, 64) 71 | if err != nil { 72 | return time.Time{}, err 73 | } 74 | 75 | hour, err := strconv.ParseInt(times[0], 10, 64) 76 | if err != nil { 77 | return time.Time{}, err 78 | } 79 | minute, err := strconv.ParseInt(times[1], 10, 64) 80 | if err != nil { 81 | return time.Time{}, err 82 | } 83 | second, err := strconv.ParseInt(times[2], 10, 64) 84 | if err != nil { 85 | return time.Time{}, err 86 | } 87 | 88 | loc, err2 := time.LoadLocation(timeZone) 89 | 90 | t := time.Date(int(year), time.Month(month), int(day), int(hour), int(minute), int(second), 0, loc) 91 | 92 | return t, err2 93 | } 94 | 95 | func SnowflakeToUnixTime(id string) (int64, error) { 96 | // i, err := strconv.ParseInt(id, 10, 64) 97 | // if err != nil { 98 | // return -1, err 99 | // } 100 | 101 | i, _ := discordgo.SnowflakeTimestamp(id) 102 | timestamp := i.Unix() 103 | return timestamp, nil 104 | } 105 | 106 | //if embed or attachment 107 | //GET file url's response.body. 108 | //get bytes of response via ReadAll() 109 | //get hash of file via bytes sha256.Sum256([]byte("hello world\n")) 110 | //write bytes into file with hash as name into specified path 111 | //return sha256 sum 112 | func DownloadFile(url string, channel_id string, path string, save bool) (string, error) { 113 | // Get the data 114 | resp, err := http.Get(url) 115 | if err != nil { 116 | return "", err 117 | } 118 | defer resp.Body.Close() 119 | 120 | newpath := filepath.Join(".", path, channel_id) 121 | err = os.MkdirAll(newpath, os.ModePerm) 122 | if err != nil { 123 | return "", err 124 | } 125 | //read response stream into byte array 126 | body, err := io.ReadAll(resp.Body) 127 | //Duplicate body stream as you cannot read it twice 128 | body2 := bytes.NewReader(body) 129 | if err != nil { 130 | return "", err 131 | } 132 | //hash byte array 133 | sum := fmt.Sprintf("%x", sha256.Sum256(body)) 134 | 135 | if !save { 136 | return sum, nil 137 | } 138 | 139 | //create file with hash as file name 140 | newpath = filepath.Join(".", newpath, sum) 141 | _, errExist := os.Stat(newpath) 142 | if errExist == nil { 143 | //If exist, return hash and do not download file 144 | return sum, nil 145 | } 146 | if errors.Is(errExist, os.ErrNotExist) { 147 | //If file does not exist, download file and return sum 148 | out, err := os.Create(newpath) 149 | if err != nil { 150 | return "", err 151 | } 152 | defer out.Close() 153 | // Write the body to file 154 | _, err = io.Copy(out, body2) 155 | if err != nil { 156 | return sum, err 157 | } 158 | return sum, nil 159 | } 160 | //If error is not errNotExist, return error and sum. Something is wrong 161 | return sum, errExist 162 | } 163 | 164 | func Contains(channels []string, id string) bool { 165 | for _, a := range channels { 166 | if a == id { 167 | return true 168 | } 169 | } 170 | return false 171 | } 172 | -------------------------------------------------------------------------------- /db/db.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "log" 6 | "os" 7 | 8 | _ "github.com/mattn/go-sqlite3" 9 | 10 | // "github.com/bwmarrin/discordgo" 11 | "errors" 12 | 13 | // "path/filepath" 14 | "strings" 15 | // "github.com/yakabuff/discord-dl/models" 16 | ) 17 | 18 | const POSTGRES = "mariadb" 19 | const SQLITE = "sqlite3" 20 | 21 | var UniqueConstraintError = errors.New("Unique constraint error") 22 | 23 | type Db struct { 24 | DbConnection *sql.DB 25 | } 26 | 27 | func Init_db(path string) (*Db, error) { 28 | var err error 29 | //Check if DB exists 30 | if path == "" { 31 | //If path empty, fallback and check default db location 32 | _, err = os.Stat("archive.db") 33 | } else { 34 | _, err = os.Stat(path) 35 | } 36 | 37 | driver := determineDbType(path) 38 | 39 | var dbConn *sql.DB 40 | var file *os.File 41 | if err == nil { 42 | //Exists 43 | if path == "" { 44 | dbConn, err = sql.Open(driver, "archive.db?_foreign_keys=on") 45 | } else { 46 | dbConn, err = sql.Open(driver, path+"?_foreign_keys=on") 47 | } 48 | if err != nil { 49 | return nil, err 50 | } 51 | } else if errors.Is(err, os.ErrNotExist) { 52 | if path == "" { 53 | path = "archive.db" 54 | file, err = os.Create(path) 55 | } else { 56 | file, err = os.Create(path) // Create SQLite file 57 | } 58 | if err != nil { 59 | log.Println("could not create db file") 60 | log.Fatal(err.Error()) 61 | } 62 | file.Close() 63 | dbConn, err = sql.Open("sqlite3", path+"?_foreign_keys=on") 64 | if err != nil { 65 | return nil, err 66 | } 67 | createTable(dbConn) 68 | //*message_id | channel_id | guild| | date | content | media | sender_id | reply_to // 69 | // 234234242 | 23489353 | 324242 | 1231 |asdfasdfs | | 234242 | 234756// 70 | } else { 71 | //Panic 72 | log.Fatal(err.Error()) 73 | } 74 | db := Db{DbConnection: dbConn} 75 | return &db, err 76 | } 77 | func determineDbType(path string) string { 78 | if strings.HasPrefix(path, "postgres://") { 79 | return POSTGRES 80 | } 81 | return SQLITE 82 | } 83 | -------------------------------------------------------------------------------- /db/queries.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "github.com/yakabuff/discord-dl/models" 5 | ) 6 | 7 | func (db Db) GetMessages(guild_id string, channel_id string, last_date int, after bool) (error, *models.Messages) { 8 | var messages models.Messages 9 | //use keyset pagination 10 | //first page: fetch first 100 messages. get date > curr time. keep track of the date of the last message returned 11 | //second page: fetch second batch of 100. get date > date of the last message returned in the previous batch 12 | //query messages -> query edits -> query embeds -> query attachments 13 | var stmt string 14 | if after == true { 15 | stmt = `SELECT * FROM messages where channel_id = $1 AND guild_id = $2 AND date > $3 ORDER BY date DESC LIMIT 10` 16 | } else { 17 | stmt = `SELECT * FROM messages where channel_id = $1 AND guild_id = $2 AND date < $3 ORDER BY date DESC LIMIT 10` 18 | } 19 | 20 | rows, err := db.DbConnection.Query(stmt, channel_id, guild_id, last_date) 21 | if err != nil { 22 | return err, nil 23 | } 24 | defer rows.Close() 25 | 26 | for rows.Next() { 27 | var message models.MessageOut 28 | err := rows.Scan( 29 | &message.MessageId, 30 | &message.ChannelId, 31 | &message.GuildId, 32 | &message.MessageTimestamp, 33 | &message.Content, 34 | &message.SenderId, 35 | &message.SenderName, 36 | &message.ReplyTo, 37 | &message.EditTime, 38 | &message.ThreadId) 39 | if err != nil { 40 | return err, nil 41 | } 42 | 43 | err, edits := db.GetEdits(message.MessageId) 44 | if err != nil { 45 | return err, nil 46 | } 47 | err, embeds := db.GetEmbeds(message.MessageId) 48 | if err != nil { 49 | return err, nil 50 | } 51 | err, attachments := db.GetAttachments(message.MessageId) 52 | if err != nil { 53 | return err, nil 54 | } 55 | 56 | // addEmbedResourceLink(embeds, message.ChannelId) 57 | // addAttachmentResourceLink(attachments, message.ChannelId) 58 | message.Edits = edits 59 | message.Embeds = embeds 60 | message.Attachments = attachments 61 | messages.Messages = append(messages.Messages, message) 62 | } 63 | return nil, &messages 64 | } 65 | 66 | func (db Db) GetEdits(message_id string) (error, []models.Edit) { 67 | var edits []models.Edit 68 | stmt := `SELECT * FROM edits where message_id = $1` 69 | rows, err := db.DbConnection.Query(stmt, message_id) 70 | if err != nil { 71 | return err, nil 72 | } 73 | defer rows.Close() 74 | for rows.Next() { 75 | var edit models.Edit 76 | err := rows.Scan(&edit.MessageId, 77 | &edit.EditTime, 78 | &edit.Content) 79 | 80 | if err != nil { 81 | return err, nil 82 | } 83 | edits = append(edits, edit) 84 | } 85 | return nil, edits 86 | } 87 | 88 | func (db Db) GetEmbeds(message_id string) (error, []models.EmbedOut) { 89 | var embeds []models.EmbedOut 90 | stmt := `SELECT * FROM embeds where message_id = $1 ORDER BY embed_date_retrieved DESC LIMIT 1` 91 | rows, err := db.DbConnection.Query(stmt, message_id) 92 | if err != nil { 93 | return err, nil 94 | } 95 | defer rows.Close() 96 | 97 | for rows.Next() { 98 | var embed models.EmbedOut 99 | err := rows.Scan( 100 | &embed.MessageId, 101 | &embed.EmbedDateRetrieved, 102 | &embed.EmbedUrl, 103 | &embed.EmbedTitle, 104 | &embed.EmbedDescription, 105 | &embed.EmbedTimestamp, 106 | &embed.EmbedThumbnailUrl, 107 | &embed.EmbedThumbnailHash, 108 | &embed.EmbedImageUrl, 109 | &embed.EmbedImageHash, 110 | &embed.EmbedVideoUrl, 111 | &embed.EmbedVideoHash, 112 | &embed.EmbedFooter, 113 | &embed.EmbedAuthorName, 114 | &embed.EmbedAuthorUrl, 115 | &embed.EmbedField) 116 | if err != nil { 117 | return err, nil 118 | } 119 | 120 | embeds = append(embeds, embed) 121 | } 122 | return nil, embeds 123 | } 124 | 125 | func (db Db) GetAttachments(message_id string) (error, []models.AttachmentOut) { 126 | var attachments []models.AttachmentOut 127 | stmt := `SELECT * FROM attachments where message_id = $1` 128 | rows, err := db.DbConnection.Query(stmt, message_id) 129 | if err != nil { 130 | return err, nil 131 | } 132 | defer rows.Close() 133 | 134 | for rows.Next() { 135 | var attachment models.AttachmentOut 136 | err := rows.Scan( 137 | &attachment.AttachmentId, 138 | &attachment.MessageId, 139 | &attachment.AttachmentFilename, 140 | &attachment.AttachmentUrl, 141 | &attachment.AttachmentHash) 142 | if err != nil { 143 | return err, nil 144 | } 145 | 146 | attachments = append(attachments, attachment) 147 | } 148 | return nil, attachments 149 | } 150 | 151 | func (db Db) GetChannelsFromGuild(guild_id string) ([]models.Channel, error) { 152 | var channels []models.Channel 153 | stmt := `SELECT channel_id, name, topic, guild_id FROM channels_meta where guild_id = $1 AND is_thread = 0` 154 | rows, err := db.DbConnection.Query(stmt, guild_id) 155 | if err != nil { 156 | return nil, err 157 | } 158 | defer rows.Close() 159 | for rows.Next() { 160 | var channel models.Channel 161 | err := rows.Scan( 162 | &channel.ChannelID, 163 | &channel.Name, 164 | &channel.Topic, 165 | &channel.GuildID) 166 | 167 | if err != nil { 168 | return nil, err 169 | } 170 | 171 | channels = append(channels, channel) 172 | } 173 | return channels, nil 174 | } 175 | 176 | func (db Db) GetAllGuilds() ([]models.GuildOut, error) { 177 | var guilds []models.GuildOut 178 | stmt := `SELECT * FROM guilds_meta` 179 | rows, err := db.DbConnection.Query(stmt) 180 | if err != nil { 181 | return nil, err 182 | } 183 | defer rows.Close() 184 | for rows.Next() { 185 | var guild models.GuildOut 186 | err := rows.Scan( 187 | &guild.GuildID, 188 | &guild.IconHash, 189 | &guild.BannerHash, 190 | &guild.Name) 191 | if err != nil { 192 | return nil, err 193 | } 194 | 195 | guilds = append(guilds, guild) 196 | } 197 | return guilds, nil 198 | } 199 | -------------------------------------------------------------------------------- /db/queries_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import "testing" 4 | 5 | func TestGetChannelsFromGuild(t *testing.T) { 6 | e := dbConn.InsertChannelID("123") 7 | if e != nil { 8 | t.Errorf("Failed to insert channel id") 9 | } 10 | e = dbConn.InsertGuildID("456") 11 | if e != nil { 12 | t.Errorf("Failed to insert channel id") 13 | } 14 | 15 | e = dbConn.InsertChannelTopic("123", "mytopic") 16 | if e != nil { 17 | t.Errorf("Failed to insert channel id") 18 | } 19 | 20 | e = dbConn.InsertChannelNames("123", "myname") 21 | if e != nil { 22 | t.Errorf("Failed to insert channel id") 23 | } 24 | e = dbConn.UpdateChannelMetaTransaction("123", false, "456") 25 | if e != nil { 26 | t.Errorf("Failed to insert channel id") 27 | } 28 | 29 | chans, e := dbConn.GetChannelsFromGuild("456") 30 | if e != nil { 31 | t.Errorf("Failed to insert channel id") 32 | } 33 | 34 | if len(chans) == 1 { 35 | if chans[0].ChannelID != "123" && chans[0].GuildID != "456" && chans[0].Name != "myname" && chans[0].Topic != "mytopic" { 36 | t.Error("Invalid values") 37 | } 38 | } else { 39 | t.Error("Invalid values") 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /db/schema.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | var schema string = ` 4 | PRAGMA user_version = 1; 5 | CREATE TABLE channels("channel_id" TEXT NOT NULL PRIMARY KEY); 6 | 7 | CREATE TABLE guilds( 8 | "guild_id" TEXT NOT NULL PRIMARY KEY 9 | ); 10 | 11 | CREATE TABLE channel_topics( 12 | "channel_id" TEXT NOT NULL, 13 | "date_renamed" INTEGER NOT NULL, 14 | "channel_topic" TEXT NOT NULL, 15 | FOREIGN KEY (channel_id) REFERENCES channels(channel_id), 16 | PRIMARY KEY(channel_id, date_renamed) 17 | ); 18 | 19 | CREATE TABLE guilds_meta( 20 | "guild_id" TEXT NOT NULL PRIMARY KEY, 21 | "icon" TEXT, 22 | "banner" TEXT, 23 | "name" TEXT NOT NULL 24 | ); 25 | 26 | CREATE TABLE guild_names( 27 | "guild_id" TEXT NOT NULL, 28 | "date_renamed" INTEGER NOT NULL, 29 | "guild_name" TEXT NOT NULL, 30 | FOREIGN KEY (guild_id) REFERENCES guilds(guild_id) 31 | PRIMARY KEY(guild_id, date_renamed) 32 | ); 33 | 34 | CREATE TABLE guild_icons( 35 | "guild_id" TEXT NOT NULL, 36 | "date_renamed" INTEGER NOT NULL, 37 | "guild_icon_hash" TEXT NOT NULL, 38 | FOREIGN KEY (guild_id) REFERENCES guilds(guild_id), 39 | PRIMARY KEY(guild_id, date_renamed) 40 | ); 41 | 42 | CREATE TABLE guild_banners( 43 | "guild_id" TEXT NOT NULL, 44 | "date_renamed" INTEGER NOT NULL, 45 | "guild_banner_hash" TEXT NOT NULL NOT NULL, 46 | FOREIGN KEY (guild_id) REFERENCES guilds(guild_id), 47 | PRIMARY KEY(guild_id, date_renamed) 48 | ); 49 | 50 | CREATE TABLE messages ( 51 | "message_id" TEXT NOT NULL PRIMARY KEY, 52 | "channel_id" TEXT NOT NULL, 53 | "guild_id" TEXT, 54 | "date" INTEGER NOT NULL, 55 | "content" TEXT NOT NULL, 56 | "sender_id" TEXT NOT NULL, 57 | "sender_name" TEXT NOT NULL, 58 | "reply_to" TEXT, 59 | "edited_timestamp" INTEGER, 60 | "thread_id" TEXT, 61 | FOREIGN KEY (channel_id) REFERENCES channels(channel_id) 62 | ); 63 | 64 | CREATE TABLE attachments ( 65 | "message_id" TEXT NOT NULL, 66 | "attachment_id" TEXT NOT NULL PRIMARY KEY, 67 | "attachment_filename" TEXT NOT NULL, 68 | "attachment_URL" TEXT NOT NULL, 69 | "attachment_hash" TEXT NOT NULL, 70 | FOREIGN KEY (message_id) REFERENCES messages(message_id) 71 | ); 72 | 73 | CREATE TABLE edits ( 74 | "message_id" TEXT, 75 | "edit_time" INTEGER, 76 | "content" TEXT, 77 | PRIMARY KEY(message_id, edit_time, content), 78 | FOREIGN KEY (message_id) REFERENCES messages(message_id) 79 | ); 80 | 81 | CREATE TABLE embeds ( 82 | "message_id" TEXT NOT NULL, 83 | "embed_date_retrieved" TEXT NOT NULL, 84 | "embed_url" TEXT, 85 | "embed_title" TEXT, 86 | "embed_description" TEXT, 87 | "embed_timestamp" TEXT, 88 | "embed_thumbnail_url" TEXT, 89 | "embed_thumbnail_hash" TEXT, 90 | "embed_image_url" TEXT, 91 | "embed_image_hash" TEXT, 92 | "embed_video_url" TEXT, 93 | "embed_video_hash" TEXT, 94 | "embed_footer" TEXT, 95 | "embed_author_name" TEXT, 96 | "embed_author_url" TEXT, 97 | "embed_field" TEXT, 98 | UNIQUE(message_id, 99 | embed_date_retrieved, 100 | embed_url, 101 | embed_title, 102 | embed_description, 103 | embed_timestamp, 104 | embed_thumbnail_url, 105 | embed_thumbnail_hash, 106 | embed_image_url, 107 | embed_image_hash, 108 | embed_video_url, 109 | embed_video_hash, 110 | embed_footer, 111 | embed_author_name, 112 | embed_author_url, 113 | embed_field 114 | ), 115 | FOREIGN KEY (message_id) REFERENCES messages(message_id) 116 | ); 117 | 118 | CREATE TABLE channels_meta( 119 | "channel_id" TEXT NOT NULL PRIMARY KEY, 120 | "name" TEXT NOT NULL, 121 | "topic" TEXT, 122 | "guild_id" TEXT NOT NULL, 123 | "is_thread" INTEGER NOT NULL CHECK(is_thread >= 0 and is_thread <= 1), 124 | FOREIGN KEY (guild_id) REFERENCES guilds(guild_id), 125 | FOREIGN KEY (channel_id) REFERENCES channels(channel_id) 126 | ); 127 | 128 | CREATE TABLE channel_names( 129 | "channel_id" TEXT NOT NULL, 130 | "date_renamed" INTEGER NOT NULL, 131 | "channel_name" TEXT NOT NULL, 132 | FOREIGN KEY (channel_id) REFERENCES channels(channel_id), 133 | PRIMARY KEY(channel_id, date_renamed) 134 | ); 135 | 136 | CREATE TRIGGER guildNameTrigger BEFORE INSERT ON guild_names 137 | BEGIN 138 | SELECT 139 | CASE 140 | WHEN EXISTS (SELECT * from (select * from guild_names where guild_id = NEW.guild_id order by date_renamed DESC LIMIT 1) t WHERE t.guild_name IS NEW.guild_name order by date_renamed DESC) 141 | THEN RAISE (ABORT, 'guildNameTrigger violated') 142 | END; 143 | END; 144 | 145 | CREATE TRIGGER guildIconTrigger BEFORE INSERT ON guild_icons 146 | BEGIN 147 | SELECT 148 | CASE 149 | WHEN EXISTS (SELECT * from (select * from guild_icons where guild_id = NEW.guild_id order by date_renamed DESC LIMIT 1) t WHERE t.guild_icon_hash IS NEW.guild_icon_hash order by date_renamed DESC) 150 | THEN RAISE (ABORT, 'guildIconTrigger violated') 151 | END; 152 | END; 153 | 154 | CREATE TRIGGER guildBannerTrigger BEFORE INSERT ON guild_banners 155 | BEGIN 156 | SELECT 157 | CASE 158 | WHEN EXISTS (SELECT * from (select * from guild_banners where guild_id = NEW.guild_id order by date_renamed DESC LIMIT 1) t WHERE t.guild_banner_hash IS NEW.guild_banner_hash order by date_renamed DESC) 159 | THEN RAISE (ABORT, 'guildBannerTrigger violated') 160 | END; 161 | END; 162 | 163 | CREATE TRIGGER channelTopicTrigger BEFORE INSERT ON channel_topics 164 | BEGIN 165 | SELECT 166 | CASE 167 | WHEN EXISTS (SELECT * from (select * from channel_topics where channel_id = NEW.channel_id order by date_renamed DESC LIMIT 1) t WHERE t.channel_topic IS NEW.channel_topic order by date_renamed DESC) 168 | THEN RAISE (ABORT, 'channelTopicTrigger violated') 169 | END; 170 | END; 171 | 172 | CREATE TRIGGER channelNameTrigger BEFORE INSERT ON channel_names 173 | BEGIN 174 | SELECT 175 | CASE 176 | WHEN EXISTS (SELECT * from (select * from channel_names where channel_id = NEW.channel_id order by date_renamed DESC LIMIT 1) t WHERE t.channel_name IS NEW.channel_name order by date_renamed DESC) 177 | THEN RAISE (ABORT, 'channelNameTrigger violated') 178 | END; 179 | END; 180 | 181 | ` 182 | -------------------------------------------------------------------------------- /db/statements.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "time" 6 | 7 | "github.com/mattn/go-sqlite3" 8 | "github.com/yakabuff/discord-dl/models" 9 | ) 10 | 11 | func (db Db) InsertMessage(m models.Message) error { 12 | stmt := ` 13 | INSERT INTO messages (message_id, channel_id, guild_id, date, content, sender_id, sender_name, reply_to, edited_timestamp, thread_id) 14 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) 15 | ` 16 | _, err := db.DbConnection.Exec(stmt, m.MessageId, m.ChannelId, m.GuildId, m.MessageTimestamp, m.Content, m.SenderId, m.SenderName, m.ReplyTo, m.EditTime, m.ThreadId) 17 | 18 | if sqliteErr, ok := err.(sqlite3.Error); ok { 19 | if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 1555 { 20 | return UniqueConstraintError 21 | } else { 22 | return err 23 | } 24 | } 25 | return err 26 | } 27 | 28 | func (db Db) InsertEdit(m models.Edit) error { 29 | stmt := ` 30 | INSERT INTO edits (message_id, edit_time, content) 31 | VALUES ($1, $2, $3) 32 | ` 33 | _, err := db.DbConnection.Exec(stmt, m.MessageId, m.EditTime, m.Content) 34 | 35 | if sqliteErr, ok := err.(sqlite3.Error); ok { 36 | if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 1555 { 37 | return UniqueConstraintError 38 | } else { 39 | return err 40 | } 41 | } 42 | return err 43 | } 44 | 45 | func (db Db) InsertEmbed(m models.Embed) error { 46 | stmt := ` 47 | INSERT INTO embeds (message_id, embed_date_retrieved, embed_url, embed_title, embed_description, embed_timestamp, embed_thumbnail_url, embed_thumbnail_hash, embed_image_url, embed_image_hash, embed_video_url, embed_video_hash, embed_footer, embed_author_name, embed_author_url, embed_field) 48 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) 49 | ` 50 | _, err := db.DbConnection.Exec(stmt, m.MessageId, m.EmbedDateRetrieved, m.EmbedUrl, m.EmbedTitle, m.EmbedDescription, m.EmbedTimestamp, m.EmbedThumbnailUrl, m.EmbedThumbnailHash, m.EmbedImageUrl, m.EmbedImageHash, m.EmbedVideoUrl, m.EmbedVideoHash, m.EmbedFooter, m.EmbedAuthorName, m.EmbedAuthorUrl, m.EmbedField) 51 | 52 | if sqliteErr, ok := err.(sqlite3.Error); ok { 53 | if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique { 54 | return UniqueConstraintError 55 | } else { 56 | return err 57 | } 58 | } 59 | return err 60 | } 61 | 62 | func (db Db) InsertChannelID(channel string) error { 63 | stmt := `INSERT INTO channels(channel_id) VALUES($1)` 64 | _, err := db.DbConnection.Exec(stmt, channel) 65 | if sqliteErr, ok := err.(sqlite3.Error); ok { 66 | if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 1555 { 67 | return nil 68 | } else { 69 | return err 70 | } 71 | } 72 | return err 73 | } 74 | 75 | //fix 76 | func (db Db) InsertChannelNames(channel string, name string) error { 77 | now := time.Now().UnixNano() 78 | stmt := `INSERT INTO channel_names(channel_id, date_renamed, channel_name) VALUES($1, $2, $3)` 79 | _, err := db.DbConnection.Exec(stmt, channel, now/1000000, name) 80 | 81 | // if sqliteErr, ok := err.(sqlite3.Error); ok { 82 | // if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 1555 { 83 | // return nil 84 | // } else { 85 | // return err 86 | // } 87 | // } 88 | return err 89 | } 90 | 91 | //fix 92 | func (db Db) InsertChannelTopic(channel string, topic string) error { 93 | now := time.Now().UnixNano() 94 | stmt := `INSERT INTO channel_topics(channel_id, date_renamed, channel_topic) VALUES($1, $2, $3)` 95 | _, err := db.DbConnection.Exec(stmt, channel, now/1000000, topic) 96 | return err 97 | } 98 | 99 | func (db Db) InsertGuildID(guild string) error { 100 | stmt := `INSERT INTO guilds(guild_id) VALUES($1)` 101 | _, err := db.DbConnection.Exec(stmt, guild) 102 | if sqliteErr, ok := err.(sqlite3.Error); ok { 103 | if sqliteErr.Code == 19 && sqliteErr.ExtendedCode == 1555 { 104 | return nil 105 | } else { 106 | return err 107 | } 108 | } 109 | return err 110 | } 111 | 112 | func (db Db) InsertAttachment(m models.Attachment) error { 113 | stmt := ` 114 | INSERT INTO attachments (message_id, attachment_id, attachment_filename, attachment_URL, attachment_hash) 115 | VALUES ($1, $2, $3, $4, $5) 116 | ` 117 | _, err := db.DbConnection.Exec(stmt, m.MessageId, m.AttachmentId, m.AttachmentFilename, m.AttachmentUrl, m.AttachmentHash) 118 | 119 | return err 120 | } 121 | 122 | func (db Db) InsertGuildNames(gid string, guild_name string) error { 123 | 124 | now := time.Now().UnixNano() 125 | stmt := `INSERT INTO guild_names VALUES($1, $2, $3);` 126 | _, err := db.DbConnection.Exec(stmt, gid, now/1000000, guild_name) 127 | 128 | return err 129 | } 130 | 131 | func (db Db) InsertGuildIcons(gid string, icon_hash string) error { 132 | 133 | now := time.Now().UnixNano() 134 | stmt := `INSERT INTO guild_icons VALUES($1, $2, $3);` 135 | _, err := db.DbConnection.Exec(stmt, gid, now/1000000, icon_hash) 136 | 137 | return err 138 | } 139 | 140 | func (db Db) InsertGuildBanner(gid string, banner_hash string) error { 141 | 142 | now := time.Now().UnixNano() 143 | stmt := `INSERT INTO guild_banners VALUES($1, $2, $3);` 144 | _, err := db.DbConnection.Exec(stmt, gid, now/1000000, banner_hash) 145 | 146 | return err 147 | } 148 | 149 | func (db Db) UpdateGuildMetaTransaction(gid string) error { 150 | 151 | insert := `INSERT INTO guilds_meta values($1, $2, $3, $4) ON CONFLICT(guild_id) DO UPDATE SET guild_id = $1, name = $4, icon = $2, banner = $3;` 152 | 153 | var name, icon, banner string 154 | var row *sql.Row 155 | 156 | tx, err := db.DbConnection.Begin() 157 | if err != nil { 158 | tx.Rollback() 159 | return err 160 | } 161 | row = tx.QueryRow("select guild_name from guild_names where guild_id=$1 order by date_renamed DESC LIMIT 1;", gid) 162 | err = row.Scan(&name) 163 | if err != nil { 164 | tx.Rollback() 165 | return err 166 | } 167 | row = tx.QueryRow("select guild_icon_hash from guild_icons where guild_id=$1 order by date_renamed DESC LIMIT 1;", gid) 168 | err = row.Scan(&icon) 169 | if err != nil { 170 | tx.Rollback() 171 | return err 172 | } 173 | row = tx.QueryRow("select guild_banner_hash from guild_banners where guild_id=$1 order by date_renamed DESC LIMIT 1;", gid) 174 | err = row.Scan(&banner) 175 | if err != nil { 176 | tx.Rollback() 177 | return err 178 | } 179 | _, err = tx.Exec(insert, gid, icon, banner, name) 180 | 181 | if err != nil { 182 | tx.Rollback() 183 | return err 184 | } 185 | err = tx.Commit() 186 | return err 187 | 188 | } 189 | 190 | func (db Db) UpdateChannelMetaTransaction(cid string, isThread bool, gid string) error { 191 | 192 | insert := `INSERT INTO channels_meta values($1, $2, $3, $4, $5) ON CONFLICT(channel_id) DO UPDATE SET channel_id = $1, name = $2, topic = $3;` 193 | 194 | var name, topic string 195 | var row *sql.Row 196 | 197 | tx, err := db.DbConnection.Begin() 198 | if err != nil { 199 | tx.Rollback() 200 | return err 201 | } 202 | row = tx.QueryRow("select channel_name from channel_names where channel_id=$1 order by date_renamed DESC LIMIT 1;", cid) 203 | err = row.Scan(&name) 204 | if err != nil { 205 | tx.Rollback() 206 | return err 207 | } 208 | row = tx.QueryRow("select channel_topic from channel_topics where channel_id=$1 order by date_renamed DESC LIMIT 1;", cid) 209 | err = row.Scan(&topic) 210 | if err != nil { 211 | tx.Rollback() 212 | return err 213 | } 214 | 215 | _, err = tx.Exec(insert, cid, name, topic, gid, isThread) 216 | 217 | if err != nil { 218 | tx.Rollback() 219 | return err 220 | } 221 | err = tx.Commit() 222 | return err 223 | 224 | } 225 | -------------------------------------------------------------------------------- /db/structure_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | var dbConn *Db 12 | 13 | func setup() { 14 | db, err := Init_db("test.db") 15 | dbConn = db 16 | if err != nil { 17 | fmt.Println(err) 18 | os.Exit(1) 19 | } 20 | } 21 | 22 | func cleanup() { 23 | dbConn.DbConnection.Close() 24 | os.Remove("test.db") 25 | } 26 | 27 | func teardown() { 28 | cleanup() 29 | setup() 30 | } 31 | 32 | func TestMain(m *testing.M) { 33 | setup() 34 | m.Run() 35 | // cleanup() 36 | } 37 | 38 | func TestInsertGuildID(t *testing.T) { 39 | e := dbConn.InsertGuildID("123") 40 | if e != nil { 41 | t.Errorf("Failed to insert guild id") 42 | } 43 | } 44 | 45 | func TestInsertChannelID(t *testing.T) { 46 | e := dbConn.InsertChannelID("123") 47 | if e != nil { 48 | t.Errorf("Failed to insert channel id") 49 | } 50 | } 51 | 52 | func TestInsertGuildName(t *testing.T) { 53 | 54 | e := dbConn.InsertGuildID("123123123") 55 | if e != nil { 56 | t.Errorf("Failed to insert guild id") 57 | t.Log(e.Error()) 58 | } 59 | 60 | e = dbConn.InsertGuildNames("123123123", "chan1") 61 | if e != nil { 62 | t.Errorf("Failed to upsert channel name chan1 1") 63 | t.Errorf(e.Error()) 64 | } 65 | 66 | e = dbConn.InsertGuildNames("123123123", "chan1") //Fail 67 | 68 | if assert.Error(t, e) { 69 | res := (e.Error() == "guildNameTrigger violated") 70 | 71 | assert.Equal(t, true, res) 72 | } 73 | e = dbConn.InsertGuildNames("123123123", "chan2") //pass 74 | if e != nil { 75 | t.Errorf("Failed to upsert channel name chan2") 76 | t.Errorf(e.Error()) 77 | } 78 | 79 | e = dbConn.InsertGuildNames("123123123", "chan1") //Pass 80 | if e != nil { 81 | t.Errorf("Failed to upsert channel name chan1 3") 82 | t.Errorf(e.Error()) 83 | } 84 | 85 | e = dbConn.InsertGuildNames("123123123", "chan1") //Fail 86 | 87 | if assert.Error(t, e) { 88 | res := (e.Error() == "guildNameTrigger violated") 89 | 90 | assert.Equal(t, true, res) 91 | } 92 | e = dbConn.InsertGuildNames("123123123", "chan1") // Fail 93 | 94 | if assert.Error(t, e) { 95 | res := (e.Error() == "guildNameTrigger violated") 96 | 97 | assert.Equal(t, true, res) 98 | } 99 | teardown() 100 | } 101 | 102 | func TestUpsertGuildMeta(t *testing.T) { 103 | e := dbConn.InsertGuildID("123123123") 104 | if e != nil { 105 | t.Errorf("Failed to insert guild id") 106 | t.Log(e.Error()) 107 | } 108 | 109 | e = dbConn.InsertGuildNames("123123123", "chan1") 110 | if e != nil { 111 | t.Errorf("Failed to upsert channel name chan1 1") 112 | t.Errorf(e.Error()) 113 | } 114 | e = dbConn.InsertGuildIcons("123123123", "iconhash1") 115 | if e != nil { 116 | t.Errorf("Failed to upsert icon") 117 | t.Errorf(e.Error()) 118 | } 119 | 120 | e = dbConn.InsertGuildBanner("123123123", "bannerhash1") 121 | if e != nil { 122 | t.Errorf("Failed to upsert banner") 123 | t.Errorf(e.Error()) 124 | } 125 | 126 | e = dbConn.UpdateGuildMetaTransaction("123123123") 127 | if e != nil { 128 | t.Errorf(e.Error()) 129 | } 130 | /////////////////////////////////////// 131 | e = dbConn.InsertGuildNames("123123123", "chan2") 132 | if e != nil { 133 | t.Errorf("Failed to upsert channel name chan2 1") 134 | t.Errorf(e.Error()) 135 | } 136 | e = dbConn.InsertGuildIcons("123123123", "iconhash2") 137 | if e != nil { 138 | t.Errorf("Failed to upsert icon") 139 | t.Errorf(e.Error()) 140 | } 141 | 142 | e = dbConn.InsertGuildBanner("123123123", "bannerhash2") 143 | if e != nil { 144 | t.Errorf("Failed to upsert banner") 145 | t.Errorf(e.Error()) 146 | } 147 | 148 | e = dbConn.UpdateGuildMetaTransaction("123123123") 149 | if e != nil { 150 | t.Errorf(e.Error()) 151 | } 152 | //////////////////////////////////////// 153 | e = dbConn.InsertGuildNames("123123123", "chan2") 154 | if assert.Error(t, e) { 155 | res := (e.Error() == "guildNameTrigger violated") 156 | 157 | assert.Equal(t, true, res) 158 | } 159 | e = dbConn.InsertGuildIcons("123123123", "iconhash2") 160 | if assert.Error(t, e) { 161 | res := (e.Error() == "guildIconTrigger violated") 162 | 163 | assert.Equal(t, true, res) 164 | } 165 | 166 | e = dbConn.InsertGuildBanner("123123123", "bannerhash2") 167 | if assert.Error(t, e) { 168 | res := (e.Error() == "guildBannerTrigger violated") 169 | 170 | assert.Equal(t, true, res) 171 | } 172 | 173 | e = dbConn.UpdateGuildMetaTransaction("123123123") 174 | if e != nil { 175 | t.Errorf(e.Error()) 176 | } 177 | teardown() 178 | } 179 | 180 | func TestInsertGuildIcon(t *testing.T) { 181 | 182 | } 183 | 184 | func TestInsertGuildBanner(t *testing.T) { 185 | 186 | } 187 | 188 | func TestUpsertChannelMeta(t *testing.T) { 189 | e := dbConn.InsertGuildID("234234234") 190 | if e != nil { 191 | t.Errorf("Failed to insert guild id") 192 | t.Log(e.Error()) 193 | } 194 | e = dbConn.InsertChannelID("123123123") 195 | if e != nil { 196 | t.Errorf("Failed to insert guild id") 197 | t.Log(e.Error()) 198 | } 199 | 200 | e = dbConn.InsertChannelNames("123123123", "chan1name") 201 | if e != nil { 202 | t.Errorf("Failed to upsert channel name chan1 1") 203 | t.Errorf(e.Error()) 204 | } 205 | e = dbConn.InsertChannelTopic("123123123", "chan1topic") 206 | if e != nil { 207 | t.Errorf("Failed to upsert icon") 208 | t.Errorf(e.Error()) 209 | } 210 | e = dbConn.UpdateChannelMetaTransaction("123123123", true, "234234234") 211 | if e != nil { 212 | t.Errorf(e.Error()) 213 | } 214 | // teardown() 215 | } 216 | -------------------------------------------------------------------------------- /db/tables.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "log" 6 | ) 7 | 8 | func createTable(db *sql.DB) { 9 | 10 | log.Println("Creating tables") 11 | _, errx := db.Exec(schema) 12 | if errx != nil { 13 | log.Fatal(errx.Error()) 14 | } 15 | log.Println("Tables initialized") 16 | 17 | } 18 | -------------------------------------------------------------------------------- /ddl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yakabuff/discord-dl/7ce8b4e34cbc0eee6131dd1e6b4e01dbe6081f96/ddl.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/yakabuff/discord-dl 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/BurntSushi/toml v1.1.0 7 | github.com/bwmarrin/discordgo v0.24.0 8 | github.com/go-chi/chi/v5 v5.0.7 9 | github.com/google/uuid v1.3.0 10 | github.com/mattn/go-sqlite3 v1.14.9 11 | github.com/schollz/progressbar/v3 v3.8.6 12 | github.com/sirupsen/logrus v1.8.1 // indirect 13 | github.com/stretchr/testify v1.3.0 // indirect 14 | github.com/vbauerster/mpb/v7 v7.4.1 15 | golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 // indirect 16 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect 17 | golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect 18 | ) 19 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= 2 | github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 3 | github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow= 4 | github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4= 5 | github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8= 6 | github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo= 7 | github.com/bwmarrin/discordgo v0.24.0 h1:Gw4MYxqHdvhO99A3nXnSLy97z5pmIKHZVJ1JY5ZDPqY= 8 | github.com/bwmarrin/discordgo v0.24.0/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY= 9 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 11 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8= 13 | github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= 14 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 15 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 16 | github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= 17 | github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 18 | github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw= 19 | github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= 20 | github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= 21 | github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 22 | github.com/mattn/go-sqlite3 v1.14.9 h1:10HX2Td0ocZpYEjhilsuo6WWtUqttj2Kb0KtD86/KYA= 23 | github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= 24 | github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ= 25 | github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= 26 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 27 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 28 | github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= 29 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 30 | github.com/schollz/progressbar/v3 v3.8.6 h1:QruMUdzZ1TbEP++S1m73OqRJk20ON11m6Wqv4EoGg8c= 31 | github.com/schollz/progressbar/v3 v3.8.6/go.mod h1:W5IEwbJecncFGBvuEh4A7HT1nZZ6WNIL2i3qbnI0WKY= 32 | github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= 33 | github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 34 | github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= 35 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 36 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 37 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 38 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 39 | github.com/vbauerster/mpb/v7 v7.4.1 h1:NhLMWQ3gNg2KJR8oeA9lO8Xvq+eNPmixDmB6JEQOUdA= 40 | github.com/vbauerster/mpb/v7 v7.4.1/go.mod h1:Ygg2mV9Vj9sQBWqsK2m2pidcf9H3s6bNKtqd3/M4gBo= 41 | golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= 42 | golang.org/x/crypto v0.0.0-20220131195533-30dcbda58838/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 43 | golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 h1:SLP7Q4Di66FONjDJbCYrCRrh97focO6sLogHO7/g8F0= 44 | golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 45 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 46 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 47 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 48 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 49 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 50 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 51 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 52 | golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 53 | golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 54 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= 55 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 56 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 57 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 58 | golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8= 59 | golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 60 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 61 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 62 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 63 | -------------------------------------------------------------------------------- /job/job.go: -------------------------------------------------------------------------------- 1 | package job 2 | 3 | import ( 4 | "errors" 5 | "io/ioutil" 6 | "sync" 7 | 8 | "github.com/google/uuid" 9 | "github.com/sirupsen/logrus" 10 | "github.com/vbauerster/mpb/v7" 11 | "github.com/vbauerster/mpb/v7/decor" 12 | "github.com/yakabuff/discord-dl/common" 13 | "github.com/yakabuff/discord-dl/models" 14 | ) 15 | 16 | type Archiver interface { 17 | ChannelDownload(channel string, fastUpdate bool, after string, before string, state JobState) error 18 | GetChannelsGuild(guildID string) ([]string, error) 19 | IndexGuild(guild string) error 20 | IndexChannel(channel string) error 21 | } 22 | type Jobs struct { 23 | Jobs []JobOut 24 | } 25 | 26 | var log *logrus.Logger 27 | 28 | type JobOut struct { 29 | Id string 30 | Snowflake string 31 | Progress int 32 | Status string 33 | Error string 34 | } 35 | 36 | type Job struct { 37 | Id string 38 | Snowflake string 39 | Progress int 40 | Args models.JobArgs 41 | Status Status 42 | Error error 43 | } 44 | type JobQueue struct { 45 | *sync.Mutex 46 | Queue map[string]*Worker 47 | MaxSize int 48 | Wg *sync.WaitGroup 49 | Archiver Archiver 50 | Jobs map[string]*Job 51 | Progress *mpb.Progress 52 | } 53 | 54 | type Worker struct { 55 | Channel *chan *Job 56 | Category string 57 | MaxSize int 58 | CurrJob *Job 59 | } 60 | 61 | type JobState struct { 62 | Progress *int 63 | Error *error 64 | Status *Status 65 | Bar *mpb.Bar 66 | Id string 67 | } 68 | 69 | type Status int 70 | 71 | const ( 72 | PENDING Status = iota 73 | RUNNING 74 | CANCELLED 75 | ERROR 76 | FINISHED 77 | ) 78 | 79 | func NewJob(args models.JobArgs) Job { 80 | id := uuid.New().String() 81 | var snowflake string 82 | switch args.Mode { 83 | case models.CHANNEL: 84 | snowflake = args.Channel 85 | case models.GUILD: 86 | snowflake = args.Guild 87 | } 88 | job := Job{Id: id, Args: args, Snowflake: snowflake, Status: PENDING} 89 | return job 90 | } 91 | 92 | func NewJobQueue(a Archiver, logger bool) JobQueue { 93 | initLogger(logger) 94 | m := sync.Mutex{} 95 | q := make(map[string]*Worker) 96 | jr := make(map[string]*Job) 97 | w := &sync.WaitGroup{} 98 | pg := mpb.New(mpb.WithWaitGroup(w)) 99 | return JobQueue{ 100 | &m, 101 | q, 102 | 60, 103 | &sync.WaitGroup{}, 104 | a, 105 | jr, 106 | pg, 107 | } 108 | } 109 | 110 | func initLogger(logger bool) { 111 | if logger { 112 | l, err := common.NewErrLogger() 113 | if err != nil { 114 | logrus.New().Fatal(err) 115 | } 116 | log = l 117 | log.SetReportCaller(true) 118 | } else { 119 | logrus.SetOutput(ioutil.Discard) 120 | } 121 | } 122 | 123 | func (a *JobQueue) AddJobRecord(job *Job) { 124 | 125 | a.Jobs[job.Id] = job 126 | 127 | } 128 | 129 | func (a *JobQueue) Enqueue(job Job) error { 130 | 131 | a.Lock() 132 | defer a.Unlock() 133 | 134 | if _, ok := a.Queue[job.Snowflake]; ok { 135 | //If group exists, add job to preexisting worker 136 | var w *chan *Job = a.Queue[job.Snowflake].Channel 137 | select { 138 | case *w <- &job: 139 | log.Infof("Job ID %s added for %s. Task commencing", job.Id, job.Snowflake) 140 | a.AddJobRecord(&job) 141 | default: 142 | log.Warning("Channel is full. Job was not added") 143 | return errors.New("channel is full. Job was not added") 144 | } 145 | 146 | } else { 147 | c := make(chan *Job, 100) 148 | a.Queue[job.Snowflake] = &Worker{Channel: &c, Category: job.Snowflake} 149 | 150 | var w *chan *Job = a.Queue[job.Snowflake].Channel 151 | select { 152 | case *w <- &job: 153 | //Startup a worker and start processing jobs 154 | a.Wg.Add(1) 155 | log.Infof("Job ID %s added for %s. Task commencing", job.Id, job.Snowflake) 156 | a.AddJobRecord(&job) 157 | go a.StartWorker(a.Queue[job.Snowflake]) 158 | 159 | default: 160 | log.Infof("Worker %s is full. Job was not added", a.Queue[job.Snowflake].Category) 161 | return errors.New("channel is full. Job was not added") 162 | } 163 | 164 | } 165 | return nil 166 | } 167 | 168 | func (a *JobQueue) StartWorker(w *Worker) { 169 | for { 170 | select { 171 | case task := <-*w.Channel: 172 | w.CurrJob = task 173 | task.Status = RUNNING 174 | w.Category = task.Snowflake 175 | log.Infof("Executing job %s %s", w.Category, task.Id) 176 | a.ExecJobArgs(task.Args, task) 177 | log.Infof("Finished executing job %s %s", w.Category, task.Id) 178 | default: 179 | log.Info("Last job processed in " + w.Category) 180 | delete(a.Queue, w.Category) 181 | a.Wg.Done() 182 | return 183 | } 184 | } 185 | } 186 | 187 | func (a *JobQueue) ExecJobArgs(j models.JobArgs, job *Job) { 188 | 189 | if j.Mode != models.NONE { 190 | switch j.Mode { 191 | case models.GUILD: 192 | // call function in archiver that returns list of channels in guild 193 | // index guild metadata 194 | // queue channels from list 195 | job.Status = RUNNING 196 | 197 | guilds, err := a.Archiver.GetChannelsGuild(j.Guild) 198 | if err != nil { 199 | job.Error = err 200 | job.Status = ERROR 201 | log.Error(err) 202 | a.Wg.Done() 203 | return 204 | } 205 | 206 | for _, val := range guilds { 207 | ja := models.JobArgs{Mode: models.CHANNEL, Before: job.Args.Before, After: job.Args.After, FastUpdate: job.Args.FastUpdate, Guild: "", Channel: val} 208 | jobtmp := NewJob(ja) 209 | err = a.Enqueue(jobtmp) 210 | //If queue full, exit with error 211 | if err != nil { 212 | break 213 | } 214 | } 215 | if err != nil { 216 | job.Status = ERROR 217 | job.Error = err 218 | log.Error(err) 219 | } else { 220 | job.Status = FINISHED 221 | } 222 | a.Wg.Done() 223 | 224 | case models.CHANNEL: 225 | //When processing a channel, first index channel, then download its messages 226 | job.Status = RUNNING 227 | bar := newBar(a.Progress, job.Snowflake, job.Id) 228 | a.Wg.Add(1) 229 | var state JobState = JobState{Progress: &job.Progress, Error: &job.Error, Status: &job.Status, Bar: bar, Id: job.Id} 230 | err := a.Archiver.IndexChannel(j.Channel) 231 | if err != nil { 232 | log.Error(err) 233 | job.Error = err 234 | job.Status = ERROR 235 | 236 | bar.Abort(false) 237 | a.Wg.Done() 238 | return 239 | } 240 | 241 | err = a.Archiver.ChannelDownload(j.Channel, j.FastUpdate, j.After, j.Before, state) 242 | 243 | job.Progress = 100 244 | bar.SetCurrent(100) 245 | 246 | if err != nil { 247 | job.Error = err 248 | job.Status = ERROR 249 | if errors.Is(err, models.FastUpdateError) { 250 | job.Status = FINISHED 251 | } else { 252 | bar.Abort(false) 253 | a.Wg.Done() 254 | return 255 | } 256 | } else { 257 | job.Status = FINISHED 258 | } 259 | 260 | bar.Completed() 261 | state.Bar.Completed() 262 | a.Wg.Done() 263 | } 264 | } 265 | } 266 | 267 | func newBar(group *mpb.Progress, snowflake string, id string) *mpb.Bar { 268 | bar2 := group.AddBar(int64(100), 269 | mpb.PrependDecorators( 270 | // simple name decorator 271 | decor.Name("Job ID: "+id+" | "+" Snowflake: "+snowflake), 272 | // decor.DSyncWidth bit enables column width synchronization 273 | decor.Percentage(decor.WCSyncSpace), 274 | ), 275 | ) 276 | 277 | return bar2 278 | } 279 | 280 | func (a *JobQueue) CancelJob(id string) error { 281 | a.Lock() 282 | defer a.Unlock() 283 | if _, ok := a.Jobs[id]; ok { 284 | a.Jobs[id].Status = CANCELLED 285 | } else { 286 | return errors.New("Invalid ID") 287 | } 288 | return nil 289 | } 290 | 291 | func (a *JobQueue) GetAllJobs() Jobs { 292 | var res Jobs 293 | for key := range a.Jobs { 294 | var s string 295 | var err string 296 | switch a.Jobs[key].Status { 297 | case PENDING: 298 | s = "PENDING" 299 | case CANCELLED: 300 | s = "CANCELLED" 301 | case FINISHED: 302 | s = "FINISHED" 303 | case RUNNING: 304 | s = "RUNNING" 305 | case ERROR: 306 | s = "ERROR" 307 | } 308 | if a.Jobs[key].Error != nil { 309 | err = a.Jobs[key].Error.Error() 310 | } 311 | j := JobOut{Id: a.Jobs[key].Id, Snowflake: a.Jobs[key].Snowflake, Progress: a.Jobs[key].Progress, Status: s, Error: err} 312 | res.Jobs = append(res.Jobs, j) 313 | } 314 | return res 315 | } 316 | 317 | //note on jobs: 318 | //archiver has a set of jobs in a datastructure or a channel. 319 | //archiver will assign a worker to each job.(non blocking). Max of 10 jobs? 320 | //Each worker will be running on a new goroutine 321 | //each job will get same DB and DG but different set of args 322 | 323 | //each worker can be cancelled. can get progress of each job 324 | 325 | //job queue: I'm thinking instead of a queue of channels that fire concurrently.. it should be like this: 326 | 327 | //queue channel1 -> in progress, queue channel1 -> in queue, channel 1 is in process of archiving, queue channel2 -> in progress , queue channel 3 -> in progress 328 | //queue channel 2 -> in queue, channel 2(1) completed, channel 2(2) -> in progress 329 | //{[channel1, channel1], [channel2, channel2], [guild1, guild1]} 330 | 331 | //{channel1: [channel1job, channel1job], channel2:[channel2job, channel2job]} 332 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "os/signal" 8 | "syscall" 9 | 10 | "github.com/yakabuff/discord-dl/archiver" 11 | "github.com/yakabuff/discord-dl/db" 12 | "github.com/yakabuff/discord-dl/job" 13 | "github.com/yakabuff/discord-dl/models" 14 | ) 15 | 16 | func main() { 17 | 18 | jobArgs, args := archiver.InitCli() 19 | 20 | //Parse config file if specified 21 | if args.Input != "" { 22 | err := archiver.ParseConfigFile(args.Input, &args) 23 | if err != nil { 24 | fmt.Fprintln(os.Stderr, err.Error()) 25 | os.Exit(1) 26 | } 27 | } 28 | 29 | if !archiver.ValidFlags(jobArgs, args) { 30 | fmt.Fprintln(os.Stderr, "Invalid flags") 31 | os.Exit(1) 32 | } 33 | 34 | var theArchiver = archiver.Archiver{Args: args} 35 | 36 | theArchiver.InitLogger() 37 | if args.Output != "" { 38 | db, err := db.Init_db(theArchiver.Args.Output) 39 | if err != nil { 40 | fmt.Fprintln(os.Stderr, err.Error()) 41 | os.Exit(1) 42 | } 43 | theArchiver.Db = *db 44 | } 45 | 46 | if args.Token != "" { 47 | errDg, dg := theArchiver.CreateConnection() 48 | if errDg != nil { 49 | // log.Println(theArchiver.Args.Token) 50 | fmt.Fprintln(os.Stderr, errDg.Error()) 51 | os.Exit(1) 52 | } 53 | 54 | theArchiver.Dg = dg 55 | 56 | theArchiver.InitListener() 57 | } 58 | 59 | err := theArchiver.InitWeb() 60 | if err != nil { 61 | fmt.Fprintln(os.Stderr, err.Error()) 62 | os.Exit(1) 63 | } 64 | theArchiver.Queue = job.NewJobQueue(&theArchiver, theArchiver.Args.Logging) 65 | 66 | if jobArgs.Mode != models.NONE { 67 | //Wait until job is complete and then exit 68 | theArchiver.Queue.Enqueue(job.NewJob(jobArgs)) 69 | theArchiver.Queue.Wg.Wait() 70 | theArchiver.Queue.Progress.Wait() 71 | log.Println("Job has finished") 72 | 73 | } else { 74 | //If no job, run forever and wait for jobs 75 | fmt.Println("discord-dl is now running. Press CTRL-C to exit.") 76 | sc := make(chan os.Signal, 1) 77 | signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill) 78 | <-sc 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /models/args.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | //Job args 4 | type JobArgs struct { 5 | Mode Mode 6 | Before string 7 | After string 8 | FastUpdate bool 9 | Guild string 10 | Channel string 11 | } 12 | 13 | //Archiver system args 14 | type ArchiverArgs struct { 15 | DownloadMedia bool 16 | Token string 17 | Output string 18 | MediaLocation string 19 | DeployPort int 20 | Listen bool 21 | Deploy bool 22 | Input string 23 | BlacklistedChannels []string 24 | ListenChannels []string 25 | ListenGuilds []string 26 | Logging bool 27 | Progress bool 28 | Export bool 29 | } 30 | 31 | type Mode int 32 | 33 | const ( 34 | NONE Mode = iota 35 | INPUT 36 | GUILD 37 | CHANNEL 38 | INVALID 39 | EXPORT 40 | ) 41 | -------------------------------------------------------------------------------- /models/attachment.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type AttachmentOut struct { 4 | AttachmentId string 5 | MessageId string 6 | AttachmentFilename string 7 | AttachmentUrl string 8 | AttachmentHash string 9 | ResourcePath string 10 | ResourceType string 11 | } 12 | 13 | type Attachment struct { 14 | AttachmentId string 15 | MessageId string 16 | AttachmentFilename string 17 | AttachmentUrl string 18 | AttachmentHash string 19 | } 20 | 21 | func NewAttachment(AttachmentId string, 22 | MessageId string, 23 | AttachmentFilename string, 24 | AttachmentUrl string, 25 | AttachmentHash string, 26 | ) Attachment { 27 | 28 | a := Attachment{AttachmentId: AttachmentId, MessageId: MessageId, AttachmentFilename: AttachmentFilename, AttachmentUrl: AttachmentUrl, AttachmentHash: AttachmentHash} 29 | return a 30 | } 31 | -------------------------------------------------------------------------------- /models/channel.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type Channel struct { 4 | ChannelID string 5 | Name string 6 | Topic string 7 | GuildID string 8 | } 9 | 10 | type Channels struct { 11 | Channels []Channel 12 | } 13 | -------------------------------------------------------------------------------- /models/edit.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type Edit struct { 4 | MessageId string 5 | EditTime int64 6 | Content string 7 | } 8 | 9 | func NewEdit(MessageId string, EditTime int64, Content string) Edit { 10 | edit := Edit{MessageId: MessageId, EditTime: EditTime, Content: Content} 11 | return edit 12 | } 13 | -------------------------------------------------------------------------------- /models/embed.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type EmbedOut struct { 4 | MessageId string 5 | EmbedDateRetrieved string 6 | EmbedUrl string 7 | EmbedTitle string 8 | EmbedDescription string 9 | EmbedTimestamp string 10 | EmbedThumbnailUrl string 11 | EmbedThumbnailHash string 12 | EmbedImageUrl string 13 | EmbedImageHash string 14 | EmbedVideoUrl string 15 | EmbedVideoHash string 16 | EmbedFooter string 17 | EmbedAuthorName string 18 | EmbedAuthorUrl string 19 | EmbedField string 20 | ResourcePathThumbnail string 21 | ResourcePathImage string 22 | ResourcePathVideo string 23 | } 24 | 25 | type Embed struct { 26 | MessageId string 27 | EmbedDateRetrieved string 28 | EmbedUrl string 29 | EmbedTitle string 30 | EmbedDescription string 31 | EmbedTimestamp string 32 | EmbedThumbnailUrl string 33 | EmbedThumbnailHash string 34 | EmbedImageUrl string 35 | EmbedImageHash string 36 | EmbedVideoUrl string 37 | EmbedVideoHash string 38 | EmbedFooter string 39 | EmbedAuthorName string 40 | EmbedAuthorUrl string 41 | EmbedField string 42 | } 43 | 44 | func NewEmbed(MessageId string, 45 | EmbedDateRetrieved string, 46 | EmbedUrl string, 47 | EmbedTitle string, 48 | EmbedDescription string, 49 | EmbedTimestamp string, 50 | EmbedThumbnailUrl string, 51 | EmbedThumbnailHash string, 52 | EmbedImageUrl string, 53 | EmbedImageHash string, 54 | EmbedVideoUrl string, 55 | EmbedVideoHash string, 56 | EmbedFooter string, 57 | EmbedAuthorName string, 58 | EmbedAuthorUrl string, 59 | EmbedField string) Embed { 60 | 61 | e := Embed{MessageId: MessageId, 62 | EmbedDateRetrieved: EmbedDateRetrieved, 63 | EmbedUrl: EmbedUrl, 64 | EmbedTitle: EmbedTitle, 65 | EmbedDescription: EmbedDescription, 66 | EmbedTimestamp: EmbedTimestamp, 67 | EmbedThumbnailUrl: EmbedThumbnailUrl, 68 | EmbedThumbnailHash: EmbedThumbnailHash, 69 | EmbedImageUrl: EmbedImageUrl, 70 | EmbedImageHash: EmbedImageHash, 71 | EmbedVideoUrl: EmbedVideoUrl, 72 | EmbedVideoHash: EmbedVideoHash, 73 | EmbedFooter: EmbedFooter, 74 | EmbedAuthorName: EmbedAuthorName, 75 | EmbedAuthorUrl: EmbedAuthorUrl, 76 | EmbedField: EmbedField} 77 | return e 78 | } 79 | -------------------------------------------------------------------------------- /models/guild.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type Guild struct { 4 | GuildID string 5 | Name string 6 | BannerHash string 7 | IconHash string 8 | } 9 | 10 | type GuildOut struct { 11 | GuildID string 12 | Name string 13 | BannerHash string 14 | IconHash string 15 | GuildBannerResourcePath string 16 | GuildIconResourcePath string 17 | } 18 | 19 | type Guilds struct { 20 | Guilds []GuildOut 21 | } 22 | -------------------------------------------------------------------------------- /models/message.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | type MessageOut struct { 8 | MessageId string 9 | ChannelId string 10 | GuildId string 11 | MessageTimestamp int64 12 | Content string 13 | SenderId string 14 | SenderName string 15 | ReplyTo string 16 | EditTime string 17 | ThreadId string 18 | ThreadPath string 19 | Edits []Edit 20 | Embeds []EmbedOut 21 | Attachments []AttachmentOut 22 | } 23 | 24 | type Message struct { 25 | MessageId string 26 | ChannelId string 27 | GuildId string 28 | MessageTimestamp int64 29 | Content string 30 | SenderId string 31 | SenderName string 32 | ReplyTo string 33 | EditTime int64 34 | ThreadId string 35 | } 36 | 37 | func NewMessage(MessageId string, ChannelId string, GuildId string, MessageTimestamp int64, Content string, SenderId string, SenderName string, ReplyTo string, EditTime int64, ThreadId string) Message { 38 | msg := Message{ 39 | MessageId: MessageId, 40 | ChannelId: ChannelId, 41 | GuildId: GuildId, 42 | MessageTimestamp: MessageTimestamp, 43 | Content: Content, 44 | SenderId: SenderId, 45 | SenderName: SenderName, 46 | ReplyTo: ReplyTo, 47 | EditTime: EditTime, 48 | ThreadId: ThreadId} 49 | return msg 50 | } 51 | 52 | var FastUpdateError = errors.New("Reached downloaded message") 53 | 54 | type MessageJson struct { 55 | MessageId string 56 | ChannelId string 57 | GuildId string 58 | MessageTimestamp int64 59 | Content string 60 | SenderId string 61 | SenderName string 62 | ReplyTo string 63 | EditTime string 64 | ThreadId string 65 | Embeds []Embed 66 | Attachments []Attachment 67 | } 68 | 69 | func NewMessageJson(MessageId string, 70 | ChannelId string, 71 | GuildId string, 72 | MessageTimestamp int64, 73 | Content string, 74 | SenderId string, 75 | SenderName string, 76 | ReplyTo string, 77 | EditTime string, 78 | ThreadId string, 79 | Embeds []Embed, 80 | Attachments []Attachment) MessageJson { 81 | 82 | return MessageJson{ 83 | MessageId, 84 | ChannelId, 85 | GuildId, 86 | MessageTimestamp, 87 | Content, 88 | SenderId, 89 | SenderName, 90 | ReplyTo, 91 | EditTime, 92 | ThreadId, 93 | Embeds, 94 | Attachments, 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /models/messages.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type Messages struct { 4 | Messages []MessageOut 5 | } 6 | -------------------------------------------------------------------------------- /sample_config.toml: -------------------------------------------------------------------------------- 1 | # DISCORD-DL CONFIG 2 | 3 | # Toggle downloading media 4 | DownloadMedia = false 5 | 6 | # Enter discord token 7 | Token = "Bot asdfasdf" 8 | 9 | # Database location 10 | Output = "~/database/my.db" 11 | 12 | # Downloaded media location 13 | MediaLocation = "~/images/" 14 | 15 | # Webapp port 16 | DeployPort = 8080 17 | 18 | # Listen for new messages (works only with bot accounts) 19 | Listen = false 20 | 21 | # Deploy webapp 22 | Deploy = true 23 | 24 | # Channel IDs of channels you wish to ignore 25 | BlacklistedChannels = ["channelid1", "channelid2"] 26 | 27 | #Channel IDs you wish to listen to if listen is enabled 28 | ListenChannels = ["channelid1", "channelid2"] 29 | 30 | #Guild IDs you wish to listen to if listen is enabled 31 | ListenGuilds = ["guildid1", "guildid2"] 32 | 33 | #Enable error logging to file 34 | Logging = true -------------------------------------------------------------------------------- /web/deploy.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "embed" 5 | "html/template" 6 | "io/ioutil" 7 | "net/http" 8 | "path/filepath" 9 | "strconv" 10 | "strings" 11 | "time" 12 | 13 | "github.com/go-chi/chi/v5" 14 | "github.com/sirupsen/logrus" 15 | "github.com/yakabuff/discord-dl/common" 16 | "github.com/yakabuff/discord-dl/db" 17 | "github.com/yakabuff/discord-dl/job" 18 | "github.com/yakabuff/discord-dl/models" 19 | ) 20 | 21 | //go:embed static/channel.html 22 | //go:embed static/channels.html 23 | //go:embed static/index.html 24 | //go:embed static/job.html 25 | var templates embed.FS 26 | 27 | type Web struct { 28 | db db.Db 29 | port int 30 | mediaLocation string 31 | JobQueue *job.JobQueue 32 | } 33 | 34 | var log *logrus.Logger 35 | 36 | func initLogger(logger bool) { 37 | if logger { 38 | l, err := common.NewWebLogger() 39 | if err != nil { 40 | logrus.New().Fatal(err) 41 | } 42 | log = l 43 | log.SetReportCaller(true) 44 | } else { 45 | logrus.SetOutput(ioutil.Discard) 46 | } 47 | } 48 | 49 | func NewWeb(db db.Db, port int, mediaLocation string, jobQueue *job.JobQueue, logger bool) Web { 50 | initLogger(logger) 51 | web := Web{} 52 | web.db = db 53 | web.port = port 54 | web.mediaLocation = mediaLocation 55 | web.JobQueue = jobQueue 56 | return web 57 | } 58 | 59 | func (web Web) Deploy(Db db.Db) { 60 | go func(Db db.Db) { 61 | log.Println("starting web app on port: " + strconv.Itoa(web.port)) 62 | r := chi.NewRouter() 63 | r.Route("/index", func(r chi.Router) { 64 | r.Get("/", web.guildHandler) 65 | r.Get("/{guild}", web.channelHandler) 66 | }) 67 | 68 | r.Route("/{guild}/{channel}", func(r chi.Router) { 69 | //First 100 messages 70 | r.Get("/", web.messageHandler) 71 | //100 messages after specified date 72 | r.Get("/{date}", web.messageHandlerDate) 73 | //fetch next 100 messages ( date + 1) or fetch previous 100 messages ( date -1) 74 | r.Get("/{date}/{nav}", web.messageHandlerNav) 75 | }) 76 | 77 | r.Route("/job", func(r chi.Router) { 78 | r.Get("/", web.ShowJobPanel) 79 | r.Get("/all", web.GetAllJobs) 80 | r.Get("/{jobID}", web.GetJobByID) 81 | // r.Get("/{snowflake}", web.GetJobsBySnowflake) 82 | r.Post("/submit", web.SubmitJob) 83 | r.Get("/progress/{jobID}", web.GetJobProgress) 84 | r.Post("/cancel/{jobID}", web.CancelJob) 85 | }) 86 | 87 | r.Get("/media/{channel}/{hash}", web.mediaHandler) 88 | http.ListenAndServe(":"+strconv.Itoa(web.port), r) 89 | }(Db) 90 | } 91 | 92 | func (web Web) mediaHandler(w http.ResponseWriter, r *http.Request) { 93 | channelParam := strings.TrimSpace(chi.URLParam(r, "channel")) 94 | hashParam := strings.TrimSpace(chi.URLParam(r, "hash")) 95 | path := filepath.FromSlash(web.mediaLocation + "/" + channelParam + "/" + hashParam) 96 | http.ServeFile(w, r, path) 97 | } 98 | 99 | func (web Web) guildHandler(w http.ResponseWriter, r *http.Request) { 100 | 101 | guilds, err := web.db.GetAllGuilds() 102 | 103 | if err != nil { 104 | log.Println(err) 105 | } 106 | web.addGuildMetadataResourceLink(guilds) 107 | 108 | g := models.Guilds{Guilds: guilds} 109 | tmpl, err := template.ParseFS(templates, "static/index.html") 110 | if err != nil { 111 | log.Println(err) 112 | } 113 | tmpl.Execute(w, g) 114 | } 115 | 116 | func (web Web) channelHandler(w http.ResponseWriter, r *http.Request) { 117 | guildParam := strings.TrimSpace(chi.URLParam(r, "guild")) 118 | log.Info(guildParam) 119 | 120 | log.Info(web.db) 121 | channels, err := web.db.GetChannelsFromGuild(guildParam) 122 | 123 | if err != nil { 124 | log.Println(err) 125 | } 126 | c := models.Channels{Channels: channels} 127 | tmpl, err := template.ParseFS(templates, "static/channels.html") 128 | if err != nil { 129 | log.Println(err) 130 | } 131 | tmpl.Execute(w, c) 132 | } 133 | 134 | func (web Web) messageHandler(w http.ResponseWriter, r *http.Request) { 135 | log.Println(r.Method + " " + r.URL.Path) 136 | guildParam := strings.TrimSpace(chi.URLParam(r, "guild")) 137 | channelParam := strings.TrimSpace(chi.URLParam(r, "channel")) 138 | 139 | date_unix := int(time.Now().Unix()) 140 | 141 | tmpl, err := template.ParseFS(templates, "static/channel.html") 142 | if err != nil { 143 | log.Println(err) 144 | } 145 | 146 | err, msgs := web.db.GetMessages(guildParam, channelParam, date_unix, false) 147 | if err != nil { 148 | log.Println(err) 149 | } 150 | for j, i := range msgs.Messages { 151 | web.addEmbedResourceLink(i.Embeds, channelParam) 152 | web.addAttachmentResourceLink(i.Attachments, channelParam) 153 | if msgs.Messages[j].ThreadId != "" { 154 | msgs.Messages[j].ThreadPath = filepath.FromSlash("/" + i.GuildId + "/" + i.ThreadId + "/") 155 | } 156 | } 157 | 158 | tmpl.Execute(w, *msgs) 159 | 160 | } 161 | 162 | func (web Web) messageHandlerDate(w http.ResponseWriter, r *http.Request) { 163 | log.Println(r.Method + " " + r.URL.Path) 164 | guildParam := strings.TrimSpace(chi.URLParam(r, "guild")) 165 | channelParam := strings.TrimSpace(chi.URLParam(r, "channel")) 166 | dateParam := strings.TrimSpace(chi.URLParam(r, "*")) 167 | 168 | date_unix, err := strconv.Atoi(dateParam) 169 | if err != nil { 170 | date_unix = int(time.Now().Unix()) 171 | } 172 | tmpl, err := template.ParseFS(templates, "static/channel.html") 173 | if err != nil { 174 | log.Println(err) 175 | } 176 | 177 | err, msgs := web.db.GetMessages(guildParam, channelParam, date_unix, false) 178 | if err != nil { 179 | log.Println(err) 180 | } 181 | for j, i := range msgs.Messages { 182 | web.addEmbedResourceLink(i.Embeds, channelParam) 183 | web.addAttachmentResourceLink(i.Attachments, channelParam) 184 | if msgs.Messages[j].ThreadId != "" { 185 | msgs.Messages[j].ThreadPath = filepath.FromSlash("/" + i.GuildId + "/" + i.ThreadId + "/") 186 | } 187 | } 188 | tmpl.Execute(w, *msgs) 189 | } 190 | 191 | func (web Web) messageHandlerNav(w http.ResponseWriter, r *http.Request) { 192 | log.Println(r.Method + " " + r.URL.Path) 193 | guildParam := strings.TrimSpace(chi.URLParam(r, "guild")) 194 | channelParam := strings.TrimSpace(chi.URLParam(r, "channel")) 195 | dateParam := strings.TrimSpace(chi.URLParam(r, "date")) 196 | afterParam := strings.TrimSpace(chi.URLParam(r, "nav")) 197 | 198 | date_unix, err := strconv.Atoi(dateParam) 199 | if err != nil { 200 | date_unix = int(time.Now().Unix()) 201 | } 202 | tmpl, err := template.ParseFS(templates, "static/channel.html") 203 | if err != nil { 204 | log.Println(err) 205 | } 206 | 207 | var msgs *models.Messages 208 | if afterParam == "next" { 209 | err, msgs = web.db.GetMessages(guildParam, channelParam, date_unix, true) 210 | if err != nil { 211 | log.Println(err) 212 | } 213 | } else if afterParam == "prev" { 214 | err, msgs = web.db.GetMessages(guildParam, channelParam, date_unix, false) 215 | if err != nil { 216 | log.Println(err) 217 | } 218 | } 219 | if len(msgs.Messages) != 0 { 220 | for j, i := range msgs.Messages { 221 | web.addEmbedResourceLink(i.Embeds, channelParam) 222 | web.addAttachmentResourceLink(i.Attachments, channelParam) 223 | if msgs.Messages[j].ThreadId != "" { 224 | msgs.Messages[j].ThreadPath = filepath.FromSlash("/" + i.GuildId + "/" + i.ThreadId + "/") 225 | } 226 | } 227 | } 228 | 229 | tmpl.ExecuteTemplate(w, "msgs", *msgs) 230 | } 231 | 232 | func (web Web) addEmbedResourceLink(embeds []models.EmbedOut, channel_id string) { 233 | for i, _ := range embeds { 234 | if embeds[i].EmbedImageHash != "" { 235 | embeds[i].ResourcePathImage = filepath.FromSlash("/" + web.mediaLocation + "/" + channel_id + "/" + embeds[i].EmbedImageHash) 236 | } 237 | if embeds[i].EmbedThumbnailHash != "" { 238 | embeds[i].ResourcePathThumbnail = filepath.FromSlash("/" + web.mediaLocation + "/" + channel_id + "/" + embeds[i].EmbedThumbnailHash) 239 | } 240 | if embeds[i].EmbedVideoHash != "" { 241 | embeds[i].ResourcePathVideo = filepath.FromSlash("/" + web.mediaLocation + "/" + channel_id + "/" + embeds[i].EmbedVideoHash) 242 | } 243 | } 244 | } 245 | 246 | func (web Web) addGuildMetadataResourceLink(guilds []models.GuildOut) { 247 | for i := range guilds { 248 | guilds[i].GuildBannerResourcePath = filepath.FromSlash("/" + web.mediaLocation + "/" + guilds[i].GuildID + "/" + guilds[i].BannerHash) 249 | guilds[i].GuildIconResourcePath = filepath.FromSlash("/" + web.mediaLocation + "/" + guilds[i].GuildID + "/" + guilds[i].IconHash) 250 | } 251 | 252 | } 253 | 254 | func (web Web) addAttachmentResourceLink(attachments []models.AttachmentOut, channel_id string) { 255 | for i, _ := range attachments { 256 | attachments[i].ResourcePath = filepath.FromSlash("/" + web.mediaLocation + "/" + channel_id + "/" + attachments[i].AttachmentHash) 257 | s := strings.ToLower(strings.Split(attachments[i].AttachmentFilename, ".")[1]) 258 | if s == "png" || s == "jpg" || s == "jpeg" || s == "gif" { 259 | attachments[i].ResourceType = "IMAGE" 260 | } else if s == "mp4" || s == "mov" || s == "wmv" || s == "avi" || s == "flv" || s == "swf" || s == "mkv" || s == "webm" { 261 | attachments[i].ResourceType = "VIDEO" 262 | } else { 263 | attachments[i].ResourceType = "FILE" 264 | } 265 | } 266 | } 267 | 268 | //need to somehow use ajax when going to next or prev page 269 | //when click next page, get date of last message, send via POST, server returns new URL and navigate to that URL. Update prev page button with old URL 270 | //at beginning: next has date of last message. prev has no date 271 | //next x1: next has date of last message. prev has no date 272 | //next x2: next has date of last message. prev has next x1's next 273 | //next x3: next has date of last message. prev has next x2's next 274 | //when click prev page, navigate to prev page using updated URL 275 | 276 | //click next/prev, 277 | -------------------------------------------------------------------------------- /web/job.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "html/template" 7 | "net/http" 8 | "strconv" 9 | "strings" 10 | 11 | "github.com/go-chi/chi/v5" 12 | "github.com/yakabuff/discord-dl/job" 13 | "github.com/yakabuff/discord-dl/models" 14 | ) 15 | 16 | func (web Web) GetAllJobs(w http.ResponseWriter, r *http.Request) { 17 | respondwithJSON(w, http.StatusCreated, web.JobQueue.Jobs) 18 | } 19 | 20 | func (web Web) GetJobByID(w http.ResponseWriter, r *http.Request) { 21 | id := strings.TrimSpace(chi.URLParam(r, "jobID")) 22 | j := web.JobQueue.Jobs[id] 23 | respondwithJSON(w, http.StatusCreated, j) 24 | } 25 | 26 | // func (web Web) GetJobBySnowflake(w http.ResponseWriter, r *http.Request) { 27 | 28 | // } 29 | 30 | func (web Web) SubmitJob(w http.ResponseWriter, r *http.Request) { 31 | var err error 32 | var j models.JobArgs 33 | 34 | err = r.ParseForm() 35 | if err != nil { 36 | respondWithError(w, http.StatusInternalServerError, "Job could not be submitted. Could not parse field") 37 | return 38 | } 39 | 40 | j.After = r.FormValue("After") 41 | j.Before = r.FormValue("Before") 42 | fu, err := strconv.ParseBool(r.FormValue("FastUpdate")) 43 | if err != nil { 44 | respondWithError(w, http.StatusInternalServerError, "Job could not be submitted. Invalid fast update field") 45 | return 46 | } 47 | j.FastUpdate = fu 48 | m := r.FormValue("Mode") 49 | switch m { 50 | case fmt.Sprintf("%d", models.GUILD): 51 | j.Guild = r.FormValue("Snowflake") 52 | j.Mode = models.GUILD 53 | case fmt.Sprintf("%d", models.CHANNEL): 54 | j.Channel = r.FormValue("Snowflake") 55 | j.Mode = models.CHANNEL 56 | } 57 | 58 | if j.Mode != models.CHANNEL && j.Mode != models.GUILD { 59 | respondWithError(w, http.StatusInternalServerError, "Invalid mode") 60 | return 61 | } 62 | 63 | job := job.NewJob(j) 64 | err = web.JobQueue.Enqueue(job) 65 | 66 | if err != nil { 67 | respondWithError(w, http.StatusInternalServerError, "Job could not be submitted. Queue is full") 68 | return 69 | } 70 | respondwithJSON(w, http.StatusCreated, map[string]string{"message": "Job successfully created"}) 71 | 72 | } 73 | 74 | // respondwithError return error message 75 | func respondWithError(w http.ResponseWriter, code int, msg string) { 76 | respondwithJSON(w, code, map[string]string{"message": msg}) 77 | } 78 | 79 | // respondwithJSON write json response format 80 | func respondwithJSON(w http.ResponseWriter, code int, payload interface{}) { 81 | response, _ := json.Marshal(payload) 82 | w.Header().Set("Content-Type", "application/json") 83 | w.WriteHeader(code) 84 | w.Write(response) 85 | } 86 | 87 | func (web Web) CancelJob(w http.ResponseWriter, r *http.Request) { 88 | id := strings.TrimSpace(chi.URLParam(r, "jobID")) 89 | j := web.JobQueue 90 | err := j.CancelJob(id) 91 | if err != nil { 92 | respondwithJSON(w, http.StatusCreated, map[string]string{"message": "Succesfully deleted job"}) 93 | } else { 94 | respondWithError(w, http.StatusInternalServerError, "Failed to cancel job. Invalid job ID") 95 | } 96 | } 97 | 98 | func (web Web) GetJobProgress(w http.ResponseWriter, r *http.Request) { 99 | id := strings.TrimSpace(chi.URLParam(r, "jobID")) 100 | j := web.JobQueue.Jobs[id] 101 | if j != nil { 102 | respondwithJSON(w, http.StatusCreated, map[string]string{"progress": fmt.Sprintf("%d", j.Progress)}) 103 | } else { 104 | respondWithError(w, http.StatusInternalServerError, "Invalid job. Could not fetch progress") 105 | } 106 | } 107 | 108 | func (web Web) ShowJobPanel(w http.ResponseWriter, r *http.Request) { 109 | jobs := web.JobQueue.GetAllJobs() 110 | 111 | tmpl, err := template.ParseFS(templates, "static/job.html") 112 | if err != nil { 113 | log.Println(err) 114 | } 115 | tmpl.Execute(w, jobs) 116 | } 117 | -------------------------------------------------------------------------------- /web/static/channel.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 |

discord-dl

13 | 14 |

15 |

16 | 17 | 18 | {{block "msgs" .}} 19 |
20 | {{range .Messages}} 21 | {{$channel := .ChannelId}} 22 | {{$guild := .GuildId}} 23 |
24 |
    25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | {{if .ReplyTo}} 51 | 52 | 53 | 54 | 55 | {{end}} 56 | {{if .Content}} 57 | 58 | 59 | 60 | 61 | {{end}} 62 | {{if ne .EditTime "-1"}} 63 | 64 | 65 | 66 | 67 | {{end}} 68 | {{if .ThreadId}} 69 | 70 | 71 | 72 | 73 | {{end}} 74 | {{if .ThreadPath}} 75 | 76 | 77 | 78 | 79 | {{end}} 80 |
    Message ID:{{.MessageId}}
    Channel ID: {{.ChannelId}}
    Guild ID: {{.GuildId}}
    Message Timestamp: {{.MessageTimestamp}}
    Sender ID: {{.SenderId }}
    Sender Name:{{.SenderName}}
    Reply To:{{.ReplyTo}}
    Content:{{.Content}}
    Last Edit Time: {{.EditTime}}
    ThreadID: {{.ThreadId}}
    Link to thread:Click here
    81 | 82 | {{if .Edits}} 83 |
    84 | Edits 85 | {{range .Edits}} 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
    Edit Time:{{.EditTime}}
    Edit Content:{{.Content}}
    96 | {{ end }} 97 |
    98 | {{end}} 99 | 100 | {{if .Embeds}} 101 |
    102 | Embeds 103 | {{range .Embeds}} 104 |
    105 | 106 | {{if .EmbedUrl}} 107 | 108 | 109 | 110 | 111 | {{end}} 112 | {{if .EmbedTimestamp}} 113 | 114 | 115 | 116 | 117 | {{end}} 118 | {{if .EmbedTitle}} 119 | 120 | 121 | 122 | 123 | {{end}} 124 | {{if .EmbedAuthorName}} 125 | 126 | 127 | 128 | 129 | {{end}} 130 | {{if .EmbedAuthorUrl}} 131 | 132 | 133 | 134 | 135 | {{end}} 136 | {{if .EmbedDescription}} 137 | 138 | 139 | 140 | 141 | {{end}} 142 | {{if .EmbedField}} 143 | 144 | 145 | 146 | 147 | {{end}} 148 | {{if .EmbedFooter}} 149 | 150 | 151 | 152 | 153 | {{end}} 154 | {{if .EmbedThumbnailUrl}} 155 | 156 | 157 | 158 | 159 | {{end}} 160 | {{if .EmbedThumbnailHash}} 161 | 162 | 163 | 164 | 165 | {{end}} 166 | {{if .EmbedImageUrl}} 167 | 168 | 169 | 170 | 171 | {{end}} 172 | {{ if .EmbedImageHash }} 173 | 174 | 175 | 176 | 177 | {{end}} 178 | {{ if .EmbedVideoUrl }} 179 | 180 | 181 | 182 | 183 | {{end}} 184 | {{ if .EmbedVideoHash }} 185 | 186 | 187 | 188 | 189 | {{end}} 190 | 191 | {{ if .ResourcePathThumbnail }} 192 | 193 | 194 | 195 | {{end}} 196 | {{ if .ResourcePathImage }} 197 | 198 | 199 | 200 | {{end}} 201 | {{ if .ResourcePathVideo}} 202 | 203 | 204 | 205 | {{end}} 206 |
    Embed URL:{{.EmbedUrl}}
    Embed timestamp:{{.EmbedTimestamp}}
    Embed title:{{.EmbedTitle}}
    Embed author name:{{.EmbedAuthorName}}
    Embed author URL:{{.EmbedAuthorUrl}}
    Embed description:{{.EmbedDescription}}
    Embed field:{{.EmbedField}}
    Embed footer:{{.EmbedFooter}}
    Embed thumbnail URL:{{.EmbedThumbnailUrl}}
    Embed thumbnail hash: {{.EmbedThumbnailHash}}
    Embed image URL:{{.EmbedImageUrl}}
    Embed image hash: {{.EmbedImageHash}}
    Embed video URL:{{.EmbedVideoUrl}}
    Embed video hash: {{.EmbedVideoHash}}
    207 |
    208 | {{ end }} 209 |
    210 | {{end}} 211 | 212 | {{if .Attachments}} 213 |
    214 | Attachments: 215 | {{range .Attachments}} 216 |
    217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | {{ if eq .ResourceType "IMAGE"}} 236 | 237 | {{ end }} 238 | 239 | 240 | {{ if eq .ResourceType "VIDEO" }} 241 | 244 | {{ end }} 245 | 246 | 247 | 248 | 249 | 250 |
    Attachment ID:{{.AttachmentId}}
    Attachment Hash:{{.AttachmentHash}}
    Attachment filename:{{.AttachmentFilename}}
    Attachment URL {{.AttachmentUrl}}
    Link to fileClick here
    251 |
    252 | {{ end }} 253 |
    254 | {{end}} 255 | 256 |
257 |
258 | {{ end }} 259 |
260 | {{ end }} 261 | 262 | 263 | 264 | 352 | -------------------------------------------------------------------------------- /web/static/channels.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 |

Channels

11 | 12 |
13 | 14 | {{range .Channels}} 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | {{ if .Topic}} 25 | 26 | {{end}} 27 | 28 |
Channel IDChannel NameChannel topic
{{ .ChannelID }}{{ .Name }}{{ .Topic }}
29 | {{ end }} 30 | 31 |
32 | 33 | -------------------------------------------------------------------------------- /web/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 |

Guilds

11 | 12 |
13 | 14 | {{range .Guilds}} 15 | 16 | 17 | {{ if .IconHash}} 18 | 19 | {{end}} 20 | 21 | 22 | {{ if .BannerHash }} 23 | 24 | {{end}} 25 | 26 |
{{ .GuildID }}{{ .Name }}{{ .GuildBannerResourcePath }}
27 | {{ end }} 28 | 29 |
30 | 31 | -------------------------------------------------------------------------------- /web/static/job.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 |

Submit Jobs

21 | 22 |
23 | 24 | 25 | 26 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 45 | 46 | 47 | 48 |
49 |

Job Queue

50 | {{block "jobs" .}} 51 |
52 |
53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | {{range .Jobs}} 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | {{end}} 71 |
CancelIDSnowflakeProgressStatusError
{{.Id}}{{.Snowflake}}{{.Progress}}%{{.Status}}{{.Error}}
72 |
73 | {{end}} 74 | 75 | 76 | 91 | 92 | --------------------------------------------------------------------------------