├── .gitignore ├── LICENSE-AGPLv3.txt ├── README.md ├── auth └── auth.go ├── cmd ├── drivesync │ └── uploader.go └── drivesyncd │ ├── daemon.go │ ├── signals.go │ └── worker.go ├── config ├── category_guessing.go ├── config.go └── utils.go ├── drivesync.go ├── errors └── errors.go ├── remote ├── sync.go └── utils.go └── utils └── utils.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | cmd/drivesyncd/*.pid 4 | cmd/drivesyncd/*.log 5 | cmd/playground/* 6 | *.pid 7 | *.log 8 | -------------------------------------------------------------------------------- /LICENSE-AGPLv3.txt: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DriveSync 2 | 3 | DriveSync is a tool for uploading local contents to your Google Drive. Written in Golang with support for `gccgo-6`, 4 | DriveSync aims to support for a wide range of Unix-like distributions. Tested platforms include: 5 | 6 | - macOS High Sierra with go 1.9 7 | - Gentoo Linux on SPARC with gccgo-6 and gccgo-7 8 | 9 | Further tests on other platforms are welcomed. 10 | 11 | DriveSync was created to solve the nuisance of uploading BitTorrent downloads to Google Drive automatically. 12 | More using scenarios await your discovery! 13 | 14 | ## Install 15 | 16 | Export `GOPATH` and run the following (same for updating): 17 | 18 | ```bash 19 | go get -u -v github.com/KireinaHoro/DriveSync/... 20 | ``` 21 | 22 | Don't forget the three dots (`...`) at the end of the above command. It's recommended to add `$GOPATH/bin` to your `$PATH` so 23 | that you can access the executables easily. 24 | 25 | ## Directory structure that DriveSync maintains 26 | 27 | ```plain 28 | [Google Drive Root] 29 | ├── archive-root/ 30 | | ├── Music/ 31 | | | ├── My Great Record/ 32 | | | | ├── track01.flac 33 | | | | ├── track02.flac 34 | | | | └── ... 35 | | | ├── My Great Single.flac 36 | | | └── ... 37 | | ├── Software 38 | | | ├── Install panicOS Low Sierra.app.tar.gz 39 | | | ├── My Awesome Tools 40 | | | | ├── busybox.tar.gz 41 | | | | ├── bash.tar.gz 42 | | | | └── ... 43 | | | └── ... 44 | | └── ... 45 | ├── Your Other Awesome Folders 46 | | └── ... 47 | └── ... 48 | ``` 49 | 50 | ## How it works 51 | 52 | DriveSync has two commandline tools available: 53 | 54 | - `drivesync` works in an one-shot manner, while 55 | - `drivesyncd` forks into the background, scaning a target directory at given frequency 56 | 57 | They sync files on your local system to your Google Drive, under `/${ARCHIVE_ROOT}/${DEFAULT_CATEGORY}`. Both commands have 58 | commandline options available. Invoke with `-h` to find out how to use them. 59 | 60 | Though DriveSync requires that you provide it with a category (either fixed-default or provided every time on commandline) for now, 61 | support for guessing the most appropriate category according to the object basename is planned. You can learn more about this 62 | [here](https://github.com/KireinaHoro/DriveSync/blob/master/config/category_guessing.go). Pull requests are welcomed. 63 | 64 | ## Usage & configuration 65 | 66 | First of all, obtain your own client secret for DriveSync to run. You can obtain your own `client_secret.json` 67 | [here](https://developers.google.com/drive/v3/web/quickstart/go#step_1_turn_on_the_api_name). 68 | 69 | After you've obtained your client secret, launch `drivesync` with `-interactive` to set up the configuration files and credentials. 70 | Note: you need to do this for every user you intend to use the tool with. Edit the configuration file according to your needs. 71 | 72 | ## Configuration file 73 | 74 | Both of the commands read configurations from a JSON file present at: 75 | 76 | - `${XDG_CONFIG_HOME:-"$HOME/.config"}/drivesync/config.json` 77 | - `/etc/drivesync/config.json` 78 | 79 | If the command fails to locate a valid configuration, it will create a sample one with the default values filled in. 80 | The configuration items are explained below. 81 | 82 | ```go 83 | var DefaultConfig = map[string]interface{}{ 84 | "archive-root": "archive", // the name of the archive root 85 | "client-secret-path": "${CONFIG_ROOT}/client_secret.json", // path of client_secret.json 86 | "create-missing": false, // whether to create missing archive roots or categories 87 | "default-category": "Uncategorized", // the default category to store content in 88 | "force-recheck": true, // whether to check if MD5 of local and remote versions of file matches 89 | "log-file": "${LOG_ROOT}/drivesyncd.log", // location of log file 90 | "pid-file": "${RUN_ROOT}/drivesyncd.pid", // location of pid file 91 | "proxy-url": "", // http proxy url 92 | "retry-ratio": 2, // ratio of expotential backoff each time a retry is triggered 93 | "retry-starting-rate": 1, // starting rate to wait for when retry occurs 94 | "scan-interval": "100ms", // interval to wait for when scanning for target change 95 | "target": "", // path of target directory to be scanned for new objects 96 | "use-proxy": false, // whether to use proxy for connection 97 | "verbose": true, // whether to write logs and outputs verbosely 98 | } 99 | ``` 100 | 101 | In the above default config, 102 | 103 | - `CONFIG_ROOT` will be expanded with `/etc/drivesync` if the user invoking the command to create the config file is root, 104 | or `${XDG_CONFIG_HOME:-"$HOME/.config"}/drivesync` otherwise; 105 | - `LOG_ROOT` will be `/var/log` and `RUN_ROOT` will be `/var/run` if invoked as root, or both will be `${HOME}/drivesync` 106 | otherwise. 107 | 108 | __NOTE:__ for ease of use, DriveSync will fall back to the permissive path listed above if the one configured in `config.json` 109 | is not available for writing for the caller. This behavior is for scenarios of users trying to launch `drivesync` or their own 110 | instance of `drivesyncd` without a user-specific `config.json`, which, if without this behavior, would fail due to missing permissions 111 | to write to system paths. 112 | 113 | You can reload the configuration file for a running `drivesyncd` with: 114 | 115 | ```bash 116 | drivesyncd -s reload 117 | ``` 118 | 119 | ...or send SIGHUP to it. SIGTERM and SIGQUIT can also be sent via the `-s` switch. Use `drivesyncd -h` to find out more. 120 | 121 | **NOTE:** due to limitations of the watcher API, `target` and `scan-interval` options won't get reloaded with a configuration 122 | file reload. You'll need to restart the daemon to reload these options. 123 | 124 | ## License 125 | 126 | DriveSync is licensed under AGPLv3. The full license text is available in the repository root, named LICENSE-AGPLv3.txt . 127 | 128 | ## Donations 129 | 130 | If you find this work helpful, consider buying me a glass of beer :) Accepted payment methods listed below: 131 | 132 | - PayPal: xubin990510@gmail.com 133 | - BTC: 13jTGFvjh7DAwiHZzxpaiqfehVnX2CWncC 134 | -------------------------------------------------------------------------------- /auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "net/http" 9 | "net/url" 10 | "os" 11 | "os/user" 12 | "path/filepath" 13 | 14 | "golang.org/x/net/context" 15 | "golang.org/x/oauth2" 16 | "golang.org/x/oauth2/google" 17 | "google.golang.org/api/drive/v3" 18 | 19 | C "github.com/KireinaHoro/DriveSync/config" 20 | ) 21 | 22 | // getClient uses a Context and Config to retrieve a Token 23 | // then generate a Client. It returns the generated Client. 24 | func getClient(ctx context.Context, config *oauth2.Config) *http.Client { 25 | cacheFile, err := tokenCacheFile() 26 | if err != nil { 27 | log.Fatalf("Unable to get path to cached credential file: %v", err) 28 | } 29 | tok, err := tokenFromFile(cacheFile) 30 | if err != nil { 31 | if C.Interactive { 32 | tok = getTokenFromWeb(config) 33 | saveToken(cacheFile, tok) 34 | } else { 35 | // we shouldn't try to prompt the user to login if not in interactive mode 36 | log.Fatal("Failed to get token while not in interactive mode; use interactive mode" + 37 | " to get token from remote") 38 | } 39 | } 40 | return config.Client(ctx, tok) 41 | } 42 | 43 | // getTokenFromWeb uses Config to request a Token. 44 | // It returns the retrieved Token. 45 | func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { 46 | authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) 47 | fmt.Printf("Go to the following link in your browser then type the "+ 48 | "authorization code: \n%v\n", authURL) 49 | 50 | var code string 51 | if _, err := fmt.Scan(&code); err != nil { 52 | log.Fatalf("Unable to read authorization code: %v", err) 53 | } 54 | 55 | tok, err := config.Exchange(context.Background(), code) 56 | if err != nil { 57 | log.Fatalf("Unable to retrieve token from web: %v", err) 58 | } 59 | return tok 60 | } 61 | 62 | // tokenCacheFile generates credential file path/filename. 63 | // It returns the generated credential path/filename. 64 | func tokenCacheFile() (string, error) { 65 | usr, err := user.Current() 66 | if err != nil { 67 | return "", err 68 | } 69 | tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials") 70 | os.MkdirAll(tokenCacheDir, 0700) 71 | return filepath.Join(tokenCacheDir, 72 | url.QueryEscape("drivesync-secrets.json")), err 73 | } 74 | 75 | // tokenFromFile retrieves a Token from a given file path. 76 | // It returns the retrieved Token and any read error encountered. 77 | func tokenFromFile(file string) (*oauth2.Token, error) { 78 | f, err := os.Open(file) 79 | if err != nil { 80 | return nil, err 81 | } 82 | defer f.Close() 83 | t := &oauth2.Token{} 84 | err = json.NewDecoder(f).Decode(t) 85 | return t, err 86 | } 87 | 88 | // saveToken uses a file path to create a file and store the 89 | // token in it. 90 | func saveToken(file string, token *oauth2.Token) { 91 | fmt.Printf("Saving credential file to: %s\n", file) 92 | f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) 93 | if err != nil { 94 | log.Fatalf("Unable to cache oauth token: %v", err) 95 | } 96 | defer f.Close() 97 | json.NewEncoder(f).Encode(token) 98 | } 99 | 100 | // Authenticate authenticates the application with Google Drive 101 | // server and returns a *drive.Service for further operation. 102 | // 103 | // Note: Authenticate expects a populated C.Config. Remember to 104 | // call C.ReadConfig before calling this function. 105 | func Authenticate() *drive.Service { 106 | conf := C.Config.Get() 107 | ctx := context.Background() 108 | 109 | b, err := ioutil.ReadFile(conf.ClientSecretPath) 110 | if err != nil { 111 | log.Fatalf("Unable to read client secret file: %v", err) 112 | } 113 | 114 | config, err := google.ConfigFromJSON(b, drive.DriveScope) 115 | if err != nil { 116 | log.Fatalf("Unable to parse client secret file to config: %v", err) 117 | } 118 | client := getClient(ctx, config) 119 | 120 | srv, err := drive.New(client) 121 | if err != nil { 122 | log.Fatalf("Unable to retrieve drive Client: %v", err) 123 | } 124 | return srv 125 | } 126 | -------------------------------------------------------------------------------- /cmd/drivesync/uploader.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "os" 9 | "path/filepath" 10 | "runtime" 11 | "strings" 12 | 13 | A "github.com/KireinaHoro/DriveSync/auth" 14 | C "github.com/KireinaHoro/DriveSync/config" 15 | E "github.com/KireinaHoro/DriveSync/errors" 16 | R "github.com/KireinaHoro/DriveSync/remote" 17 | ) 18 | 19 | // initFlags initializes the command-line arguments. 20 | func initFlags() { 21 | flag.Usage = func() { 22 | fmt.Fprintf(os.Stderr, "\nUsage: %s [options] ( || -interactive )\n\n", 23 | filepath.Base(os.Args[0])) 24 | flag.PrintDefaults() 25 | } 26 | 27 | conf := C.Config.Get() 28 | 29 | flag.StringVar(&conf.ArchiveRootName, "root", conf.ArchiveRootName, "name of the archive root") 30 | flag.StringVar(&conf.DefaultCategory, "category", conf.DefaultCategory, "destination category") 31 | flag.BoolVar(&conf.ForceRecheck, "recheck", conf.ForceRecheck, "force file checksum recheck") 32 | flag.BoolVar(&C.Interactive, "interactive", false, "work interactively") 33 | flag.BoolVar(&conf.Verbose, "verbose", conf.Verbose, "verbose output") 34 | flag.BoolVar(&conf.CreateMissing, "create-missing", conf.CreateMissing, "create category if not exist") 35 | 36 | flag.Parse() 37 | 38 | C.Target = flag.Arg(0) 39 | C.Config.Set(conf) 40 | } 41 | 42 | func main() { 43 | // process default configurations 44 | err := C.ReadConfig(false) 45 | if err != nil { 46 | log.Fatalf("Failed to read config: %v", err) 47 | } 48 | 49 | // process commandline flags 50 | initFlags() 51 | 52 | // config used should be get after commandline arguments parse 53 | conf := C.Config.Get() 54 | 55 | reader := bufio.NewReader(os.Stdin) 56 | 57 | // we need to do this manually for old runtime 58 | if conf.Verbose { 59 | fmt.Println("Procs usable:", runtime.NumCPU()) 60 | } 61 | runtime.GOMAXPROCS(runtime.NumCPU()) 62 | 63 | // authenticate to Google Drive server to get *drive.Service 64 | srv := A.Authenticate() 65 | 66 | var info os.FileInfo 67 | 68 | if C.Interactive { 69 | fmt.Print("Enter target to sync, in absolute path: ") 70 | C.Target, err = reader.ReadString('\n') 71 | C.Target = strings.TrimRight(C.Target, "\n") 72 | if err != nil { 73 | log.Fatalf("Failed to scan: %v", err) 74 | } 75 | info, err = os.Stat(C.Target) 76 | if err != nil { 77 | log.Fatalf("Failed to stat target '%s': %v", C.Target, err) 78 | } 79 | fmt.Print("Enter desired category: ") 80 | conf.DefaultCategory, err = reader.ReadString('\n') 81 | conf.DefaultCategory = strings.TrimRight(conf.DefaultCategory, "\n") 82 | if err != nil { 83 | log.Fatalf("Failed to scan: %v", err) 84 | } 85 | } else { 86 | if C.Target == "" { 87 | fmt.Fprintln(os.Stderr, "Please specify target properly.") 88 | flag.Usage() 89 | os.Exit(1) 90 | } 91 | if C.Target[0] != '/' { 92 | pwd, err := os.Getwd() 93 | if err != nil { 94 | log.Fatalf("Failed to get current working directory: %v", err) 95 | } 96 | C.Target = filepath.Clean(pwd + "/" + C.Target) 97 | } 98 | info, err = os.Stat(C.Target) 99 | if err != nil { 100 | log.Fatalf("Failed to stat target '%s': %v", C.Target, err) 101 | } 102 | } 103 | if info.IsDir() { 104 | fmt.Printf("Syncing directory '%s'...\n", C.Target) 105 | err = R.SyncDirectory(reader, srv, C.Target, conf.DefaultCategory) 106 | } else { 107 | fmt.Printf("Syncing file '%s'...\n", C.Target) 108 | err = R.SyncFile(reader, srv, C.Target, conf.DefaultCategory) 109 | } 110 | if err != nil { 111 | if _, ok := err.(E.ErrorSetMarkFailed); ok { 112 | log.Printf("Sync succeeded, yet failed to set sync mark: %v", err) 113 | } else { 114 | log.Fatalf("Failed to sync '%s': %v", C.Target, err) 115 | } 116 | } 117 | fmt.Println("Sync succeeded.") 118 | } 119 | -------------------------------------------------------------------------------- /cmd/drivesyncd/daemon.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "runtime" 7 | 8 | "github.com/radovskyb/watcher" 9 | "github.com/sevlyar/go-daemon" 10 | "google.golang.org/api/drive/v3" 11 | 12 | A "github.com/KireinaHoro/DriveSync/auth" 13 | C "github.com/KireinaHoro/DriveSync/config" 14 | ) 15 | 16 | var ( 17 | w *watcher.Watcher 18 | lock *daemon.LockFile 19 | srv *drive.Service 20 | done chan struct{} 21 | ) 22 | 23 | func main() { 24 | // parse flag 25 | parseFlags() 26 | // read config 27 | err := C.ReadConfig(true) 28 | if err != nil { 29 | log.Fatalf("E: Failed to read config: %v", err) 30 | } 31 | 32 | conf := C.Config.Get() 33 | 34 | srv = A.Authenticate() 35 | 36 | registerSignals() 37 | 38 | // initialize context for forking into background 39 | ctx := &daemon.Context{ 40 | PidFileName: conf.PidFile, 41 | PidFilePerm: 0644, 42 | LogFileName: conf.LogFile, 43 | LogFilePerm: 0640, 44 | WorkDir: "./", 45 | Umask: 027, 46 | Args: os.Args, 47 | } 48 | 49 | processCommand(ctx) 50 | 51 | // we're launched as a daemon 52 | lock, err = daemon.OpenLockFile(conf.Target+"/.drivesync-lock", 0644) 53 | defer lock.Remove() 54 | if err != nil { 55 | log.Fatalf("E: Failed to open lock file: %v", err) 56 | } else if err = lock.Lock(); err != nil { 57 | log.Fatalf("E: Failed to lock (maybe another daemon is running?): %v", err) 58 | } 59 | 60 | d, err := ctx.Reborn() 61 | if err != nil { 62 | log.Fatalf("E: Unable to fork: %v", err) 63 | } 64 | if d != nil { 65 | return 66 | } 67 | defer ctx.Release() 68 | 69 | log.Println("----------------------------") 70 | // we need to do this manually for old runtime 71 | if conf.Verbose { 72 | log.Println("I: Procs usable:", runtime.NumCPU()) 73 | } 74 | runtime.GOMAXPROCS(runtime.NumCPU()) 75 | 76 | // run indefinitely before receiving signal to quit 77 | done = make(chan struct{}) 78 | go worker() 79 | 80 | err = daemon.ServeSignals() 81 | if err != nil { 82 | log.Printf("E: %v", err) 83 | } 84 | log.Println("I: Daemon terminated.") 85 | } 86 | -------------------------------------------------------------------------------- /cmd/drivesyncd/signals.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "os" 9 | "syscall" 10 | 11 | "github.com/sevlyar/go-daemon" 12 | 13 | C "github.com/KireinaHoro/DriveSync/config" 14 | ) 15 | 16 | type signalInfo struct { 17 | description string 18 | signal os.Signal 19 | handler func(signal os.Signal) error 20 | } 21 | 22 | var ( 23 | // the accepted signal option from commandline 24 | signal *string 25 | // the list of available signals 26 | signals = map[string]signalInfo{ 27 | "quit": { 28 | "graceful shutdown", 29 | syscall.SIGQUIT, 30 | termHandler, 31 | }, 32 | "stop": { 33 | "immediate shutdown", 34 | syscall.SIGTERM, 35 | termHandler, 36 | }, 37 | "reload": { 38 | "reload configuration file", 39 | syscall.SIGHUP, 40 | reloadHandler, 41 | }, 42 | } 43 | ) 44 | 45 | // parseDescriptions initializes the flag descriptions. 46 | func parseFlags() { 47 | usage := "send signal to the daemon running" 48 | for k, v := range signals { 49 | usage += "\n\t\t" + k + "\t- " + v.description 50 | } 51 | signal = flag.String("s", "", usage) 52 | flag.Parse() 53 | } 54 | 55 | // registerSignals registers handlers for signals. 56 | func registerSignals() { 57 | for k, v := range signals { 58 | daemon.AddCommand(daemon.StringFlag(signal, k), v.signal, v.handler) 59 | } 60 | } 61 | 62 | // processCommand looks up if the signal given on commandline matches a known one. 63 | // If commandline arguments provided, the daemon will be started; 64 | // otherwise the commandline option will be processed. 65 | func processCommand(ctx *daemon.Context) { 66 | if len(daemon.ActiveFlags()) > 0 { 67 | d, err := ctx.Search() 68 | if err != nil { 69 | log.Fatalf("E: Unable find the daemon: %v", err) 70 | } 71 | err = daemon.SendCommands(d) 72 | if err != nil { 73 | log.Fatalf("E: Unable to send signal to the daemon: %v", err) 74 | } 75 | os.Exit(0) 76 | } else if *signal != "" { 77 | // an unknown signal 78 | log.Fatalf("E: Unknown signal: %s", *signal) 79 | } 80 | 81 | } 82 | 83 | // termHandler handles termination situations, shuts down the program immediately 84 | // or waits for clean-ups based on the signal received. 85 | func termHandler(sig os.Signal) error { 86 | logMessage := fmt.Sprintf("I: Received signal: %v.", sig.String()) 87 | if sig == syscall.SIGQUIT { 88 | logMessage += " Closing handles..." 89 | } else { 90 | logMessage += " Exiting now..." 91 | } 92 | log.Print(logMessage) 93 | err := lock.Remove() 94 | if err != nil { 95 | return errors.New(fmt.Sprintf("failed to remove lock file: %v", err)) 96 | } 97 | w.Close() 98 | // wait for things to be completed 99 | if sig == syscall.SIGQUIT { 100 | <-done 101 | } 102 | return daemon.ErrStop 103 | } 104 | 105 | // reloadHandler handles configuration file reload event. 106 | func reloadHandler(_ os.Signal) error { 107 | err := C.ReloadConfig() 108 | if err != nil { 109 | log.Printf("W: Failed to reload configuration: %v; check your configuration file.", err) 110 | } 111 | // C.Config.Get().Target won't get changed; restart is required if change for this is needed. 112 | return nil 113 | } 114 | -------------------------------------------------------------------------------- /cmd/drivesyncd/worker.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "time" 8 | 9 | "github.com/radovskyb/watcher" 10 | 11 | C "github.com/KireinaHoro/DriveSync/config" 12 | E "github.com/KireinaHoro/DriveSync/errors" 13 | R "github.com/KireinaHoro/DriveSync/remote" 14 | ) 15 | 16 | func worker() { 17 | conf := C.Config.Get() 18 | // initialize watcher 19 | w = watcher.New() 20 | w.IgnoreHiddenFiles(true) 21 | 22 | go func() { 23 | defer close(done) 24 | 25 | for { 26 | select { 27 | case event := <-w.Event: 28 | go func() { 29 | err := R.SyncWithGuess(nil, srv, event.Path, C.NoGuessing) 30 | if err != nil { 31 | if _, ok := err.(E.ErrorAlreadySynced); ok { 32 | log.Printf("I: Already synced: %q", event.Path) 33 | } else { 34 | log.Printf("W: Failed to sync %q: %v", event.Path, err) 35 | } 36 | } 37 | }() 38 | case err := <-w.Error: 39 | if err == watcher.ErrWatchedFileDeleted { 40 | fmt.Println(err) 41 | continue 42 | } 43 | log.Fatalf("E: Error occurred while watching: %v", err) 44 | case <-w.Closed: 45 | return 46 | } 47 | } 48 | }() 49 | 50 | w.Add(conf.Target) 51 | // we only care about new file events 52 | w.FilterOps(watcher.Create) 53 | 54 | log.Print("I: Daemon started.") 55 | 56 | f, err := os.Open(conf.Target) 57 | if err != nil { 58 | log.Fatalf("E: Failed to open target: %v", err) 59 | } 60 | if fi, err := f.Stat(); err != nil { 61 | log.Fatalf("E: Failed to stat target: %v", err) 62 | } else if !fi.IsDir() { 63 | log.Fatalf("E: Target %q is not a directory", fi.Name()) 64 | } 65 | 66 | // sync the target first 67 | log.Println("I: Syncing files/folders...") 68 | children, err := f.Readdirnames(-1) 69 | for _, v := range children { 70 | itemPath := conf.Target + "/" + v 71 | go func() { 72 | log.Printf("I: Syncing %q...", itemPath) 73 | err := R.SyncWithGuess(nil, srv, itemPath, C.NoGuessing) 74 | if err != nil { 75 | if _, ok := err.(E.ErrorAlreadySynced); ok { 76 | log.Printf("I: Already synced: %q", itemPath) 77 | } else { 78 | log.Printf("W: Failed to sync %q: %v", itemPath, err) 79 | } 80 | } 81 | }() 82 | } 83 | log.Println("I: Initial scan completed.") 84 | 85 | // start watching 86 | log.Printf("I: Starting watch of target %q...", conf.Target) 87 | 88 | interval, _ := time.ParseDuration(conf.ScanInterval) 89 | if err := w.Start(interval); err != nil { 90 | log.Fatalf("E: Failed to start watcher: %s", err) 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /config/category_guessing.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | // A Guesser accepts a basename and gives the most possibly suitable category name. 4 | type Guesser interface { 5 | Guess(string) string 6 | } 7 | 8 | // NoGuessing does not perform any form of guessing, simply returning the default 9 | type noGuessing struct{} 10 | 11 | func (r noGuessing) Guess(_ string) string { 12 | conf := Config.Get() 13 | return conf.DefaultCategory 14 | } 15 | 16 | var NoGuessing noGuessing 17 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "sync" 5 | 6 | U "github.com/KireinaHoro/DriveSync/utils" 7 | ) 8 | 9 | // runtime config 10 | var ( 11 | IgnoreList = map[string]struct{}{ 12 | ".DS_Store": {}, 13 | ".localized": {}, 14 | ".idea": {}, 15 | ".git": {}, 16 | ".drivesync-lock": {}, 17 | ".ehviewer": {}, 18 | } 19 | ArchiveRootID string 20 | CategoryIDs = U.NewSafeMap() 21 | ) 22 | 23 | // Constants that denote the default values for config values. 24 | const ( 25 | DriveFolderType = "application/vnd.google-apps.folder" 26 | RetryRatio = 2 27 | RetryStartingRate = 1 28 | ArchiveRootName = "archive" 29 | Category = "Uncategorized" 30 | ForceRecheck = true 31 | Verbose = true 32 | CreateMissing = false 33 | UseProxy = false 34 | ScanInterval = "100ms" 35 | ) 36 | 37 | // Variables that only get used by `drivesync` 38 | var ( 39 | // Interactive only affects `drivesync`; `drivesyncd` is always non-interactive 40 | Interactive = false 41 | // Target here denotes the object to be synced when calling `drivesync`; 42 | // not Config.Target 43 | Target = "" 44 | ) 45 | 46 | // configPath stores the location of the configuration file. 47 | // It's populated by the getConfigPath method. 48 | var configPath string 49 | 50 | // Config is the global variable that holds the configuration for the running daemon. 51 | var Config = NewSafeConfig() 52 | 53 | // type safeConfig is the goroutine-safe config. 54 | type safeConfig struct { 55 | v config 56 | m sync.RWMutex 57 | } 58 | 59 | func (r *safeConfig) Get() config { 60 | r.m.RLock() 61 | defer r.m.RUnlock() 62 | return r.v 63 | } 64 | 65 | func (r *safeConfig) Set(v config) { 66 | r.m.Lock() 67 | defer r.m.Unlock() 68 | r.v = v 69 | } 70 | 71 | func NewSafeConfig() *safeConfig { 72 | return &safeConfig{} 73 | } 74 | 75 | func NewConfig() config { 76 | return config{} 77 | } 78 | 79 | // type config denotes the configuration read by the daemon. 80 | type config struct { 81 | ArchiveRootName string `json:"archive-root"` 82 | ClientSecretPath string `json:"client-secret-path"` 83 | CreateMissing bool `json:"create-missing"` 84 | DefaultCategory string `json:"default-category"` 85 | ForceRecheck bool `json:"force-recheck"` 86 | LogFile string `json:"log-file"` 87 | PidFile string `json:"pid-file"` 88 | ProxyURL string `json:"proxy-url"` 89 | RetryRatio int `json:"retry-ratio"` 90 | RetryStartingRate int `json:"retry-starting-rate"` 91 | ScanInterval string `json:"scan-interval"` 92 | // Config.Target denotes the directory to be watched when calling `drivesyncd` 93 | Target string `json:"target"` 94 | UseProxy bool `json:"use-proxy"` 95 | Verbose bool `json:"verbose"` 96 | } 97 | -------------------------------------------------------------------------------- /config/utils.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "net/url" 9 | "os" 10 | "os/user" 11 | "path/filepath" 12 | "time" 13 | 14 | "github.com/pkg/errors" 15 | ) 16 | 17 | // getConfigPath populates the configPath global variable, returning errors in the process, 18 | // and, if any, leaves configPath unchanged. 19 | func getConfigPath() error { 20 | configPathSuffix := "/drivesync/config.json" 21 | usr, err := user.Current() 22 | if err != nil { 23 | return err 24 | } 25 | configRoots := []string{ 26 | "", 27 | "/etc", 28 | } 29 | if v := os.Getenv("XDG_CONFIG_HOME"); v != "" { 30 | configRoots[0] = v 31 | } else { 32 | configRoots[0] = usr.HomeDir + "/.config" 33 | } 34 | var found bool 35 | for _, v := range configRoots { 36 | path := filepath.Clean(v) + configPathSuffix 37 | fi, err := os.Stat(path) 38 | if err == nil && !fi.IsDir() { 39 | configPath = path 40 | found = true 41 | break 42 | } 43 | } 44 | if !found { 45 | // we'll need to create the config file 46 | if usr.Uid == "0" { 47 | configPath = configRoots[1] + configPathSuffix 48 | } else { 49 | configPath = configRoots[0] + configPathSuffix 50 | } 51 | } 52 | return nil 53 | } 54 | 55 | // ReadConfig finds, processes and loads the configuration file, and sets the global Config item 56 | // to the struct produced. It returns any errors that happen in the process. 57 | func ReadConfig(isDaemon bool) error { 58 | err := getConfigPath() 59 | if err != nil { 60 | return errors.New(fmt.Sprintf("failed to get config path: %v", err)) 61 | } 62 | usr, err := user.Current() 63 | if err != nil { 64 | return err 65 | } 66 | pathUser := usr.HomeDir + "/drivesyncd" 67 | if _, err := os.Stat(configPath); err != nil { 68 | log.Print("W: Config file doesn't exist. Creating a default one...") 69 | parentPath, _ := filepath.Split(configPath) 70 | err := os.MkdirAll(parentPath, 0755) 71 | if err != nil { 72 | return errors.New(fmt.Sprintf("failed to get parent of config path %q: %v", configPath, err)) 73 | } 74 | f, err := os.Create(configPath) 75 | if err != nil { 76 | return errors.New(fmt.Sprintf("failed to open config file: %v", err)) 77 | } 78 | defer f.Close() 79 | var logPath, pidPath string 80 | if usr.Uid == "0" { 81 | logPath = "/var/log" 82 | pidPath = "/var/run" 83 | } else { 84 | logPath = pathUser 85 | pidPath = pathUser 86 | } 87 | newConfig := config{ 88 | ArchiveRootName: ArchiveRootName, 89 | ClientSecretPath: parentPath + "client_secret.json", 90 | CreateMissing: CreateMissing, 91 | DefaultCategory: Category, 92 | ForceRecheck: ForceRecheck, 93 | LogFile: logPath + "/drivesyncd.log", 94 | PidFile: pidPath + "/drivesyncd.pid", 95 | RetryRatio: RetryRatio, 96 | RetryStartingRate: RetryStartingRate, 97 | ScanInterval: ScanInterval, 98 | Verbose: Verbose, 99 | UseProxy: UseProxy, 100 | } 101 | Config.Set(newConfig) 102 | b, err := json.MarshalIndent(newConfig, "", "\t") 103 | if err != nil { 104 | return errors.New(fmt.Sprintf("failed to marshal config: %v", err)) 105 | } 106 | _, err = f.Write(b) 107 | if err != nil { 108 | return errors.New(fmt.Sprintf("failed to write the default config file: %v", err)) 109 | } 110 | log.Printf("I: Default config file created at %q.", configPath) 111 | if isDaemon { 112 | return errors.New(`please set field "target" in the configuration file`) 113 | } else { 114 | return nil 115 | } 116 | } 117 | f, err := os.Open(configPath) 118 | if err != nil { 119 | return errors.New(fmt.Sprintf("failed to read config file: %v", err)) 120 | } 121 | dec := json.NewDecoder(f) 122 | var newConfig config 123 | if err := dec.Decode(&newConfig); err != nil { 124 | return errors.New(fmt.Sprintf("failed to decode config file: %v", err)) 125 | } 126 | if newConfig.Target != "" { 127 | newConfig.Target = filepath.Clean(newConfig.Target) 128 | } else if isDaemon { 129 | return errors.New(`please set field "target" in the configuration file`) 130 | } 131 | if _, err := time.ParseDuration(newConfig.ScanInterval); err != nil { 132 | return errors.New(fmt.Sprintf("failed to parse scan-interval: %v", err)) 133 | } 134 | if usr.Uid != "0" { 135 | f, err := os.Create(filepath.Dir(newConfig.LogFile) + "/.test-drivesyncd") 136 | if err != nil { 137 | log.Printf("W: Failed to open log file for writing: %v", err) 138 | log.Print("W: Falling back to storing things under user home...") 139 | err = os.MkdirAll(pathUser, os.ModePerm) 140 | if err != nil { 141 | log.Fatalf("E: %v", err) 142 | } 143 | newConfig.LogFile = pathUser + "/drivesyncd.log" 144 | newConfig.PidFile = pathUser + "/drivesyncd.pid" 145 | } else { 146 | f.Close() 147 | os.Remove(f.Name()) 148 | } 149 | } 150 | // check the proxy settings 151 | var proxyUrl *url.URL 152 | if newConfig.UseProxy { 153 | if newConfig.ProxyURL != "" { 154 | proxyUrl, err = url.Parse(newConfig.ProxyURL) 155 | if err != nil { 156 | return err 157 | } 158 | } else { 159 | return errors.New(`set up to use proxy yet "proxy-url" not set in configuration`) 160 | } 161 | } 162 | // checks finished, apply the new configuration 163 | Config.Set(newConfig) 164 | if newConfig.UseProxy { 165 | http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)} 166 | } 167 | return nil 168 | } 169 | 170 | func ReloadConfig() error { 171 | log.Print("I: Reloading configuration file...") 172 | err := ReadConfig(true) 173 | if err != nil { 174 | return err 175 | } 176 | return nil 177 | } 178 | -------------------------------------------------------------------------------- /drivesync.go: -------------------------------------------------------------------------------- 1 | package DriveSync 2 | 3 | // for godoc generation 4 | import ( 5 | _ "github.com/KireinaHoro/DriveSync/auth" 6 | _ "github.com/KireinaHoro/DriveSync/remote" 7 | ) 8 | -------------------------------------------------------------------------------- /errors/errors.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | import "strings" 4 | 5 | type ErrorNotFound string 6 | 7 | func (r ErrorNotFound) Error() string { 8 | return string(r) 9 | } 10 | 11 | type ErrorAlreadySynced string 12 | 13 | func (r ErrorAlreadySynced) Error() string { 14 | return string(r) 15 | } 16 | 17 | type ErrorChecksumMismatch string 18 | 19 | func (r ErrorChecksumMismatch) Error() string { 20 | return string(r) 21 | } 22 | 23 | type ErrorSetMarkFailed string 24 | 25 | func (r ErrorSetMarkFailed) Error() string { 26 | return string(r) 27 | } 28 | 29 | type ErrorMultipleResults []string 30 | 31 | func (r ErrorMultipleResults) Error() string { 32 | return "multiple results: " + strings.Join(r, " ") 33 | } 34 | -------------------------------------------------------------------------------- /remote/sync.go: -------------------------------------------------------------------------------- 1 | package remote 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "log" 8 | "math/rand" 9 | "os" 10 | "path/filepath" 11 | "strings" 12 | "sync" 13 | 14 | "golang.org/x/net/context" 15 | "google.golang.org/api/drive/v3" 16 | 17 | C "github.com/KireinaHoro/DriveSync/config" 18 | E "github.com/KireinaHoro/DriveSync/errors" 19 | U "github.com/KireinaHoro/DriveSync/utils" 20 | ) 21 | 22 | // SyncDirectory accepts a path to recursively upload to Google Drive to the specified category, 23 | // returning any error that happens in the process. 24 | // 25 | // It creates a ".sync_finished" mark file in the directory upon finishing, and will return 26 | // an ErrorAlreadySynced directly if that mark is present. 27 | func SyncDirectory(reader *bufio.Reader, srv *drive.Service, path, category string) error { 28 | conf := C.Config.Get() 29 | // trim the trailing slash 30 | path = filepath.Clean(path) 31 | markFilePath := path + "/.sync_finished" 32 | // check if we have the mark file 33 | if _, err := os.Stat(markFilePath); err == nil { 34 | return E.ErrorAlreadySynced("folder already synced") 35 | } else if !os.IsNotExist(err) { 36 | return errors.New(fmt.Sprintf("failed to check sync mark: %v", err)) 37 | } 38 | // parentIDs: key: path; value: parent ID 39 | parentIDs := make(map[string]string) 40 | var uploadWg sync.WaitGroup 41 | err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { 42 | if err != nil { 43 | log.Printf("Error occured while visiting path %s: %v", path, err) 44 | return err 45 | } 46 | if _, ok := C.IgnoreList[info.Name()]; ok { 47 | return nil 48 | } else if strings.HasPrefix(info.Name(), ".sync_finished") { 49 | return nil 50 | } 51 | parentPath, _ := filepath.Split(path) 52 | // trim the trailing slash 53 | parentPath = filepath.Clean(parentPath) 54 | parentID, ok := parentIDs[parentPath] 55 | if !ok { 56 | //log.Println("cache miss: ", parentPath) 57 | // parent path not present; this is the root of folder to upload 58 | parentID, err = getUploadLocation(reader, srv, category) 59 | if err != nil { 60 | return err 61 | } 62 | } 63 | // prepare for worker goroutine 64 | ctx := context.Background() 65 | // routineID for logging 66 | routineID := fmt.Sprintf("%05x", rand.Uint32()%0xfffff) 67 | if info.IsDir() { 68 | // createDirectoryWithCheck will check if file with the same name exists 69 | id := new(string) 70 | err := withRetry(U.CtxWithLoggerID(ctx, routineID), func() error { 71 | var err error 72 | *id, err = createDirectoryWithCheck(srv, info.Name(), parentID) 73 | return err 74 | }, retryIfNeeded) 75 | if err != nil { 76 | return err 77 | } else { 78 | // record parent entry 79 | parentIDs[path] = *id 80 | //log.Println("added parent map entry: ", path, id) 81 | if conf.Verbose { 82 | log.Printf("Created directory '%s' (from %s) with ID %s", info.Name(), path, *id) 83 | } 84 | } 85 | } else { 86 | uploadWg.Add(1) 87 | go func() { 88 | defer uploadWg.Done() 89 | // createFileWithCheck will check if file with the same name exists 90 | id := new(string) 91 | err := withRetry(U.CtxWithLoggerID(ctx, routineID), func() error { 92 | var err error 93 | *id, err = createFileWithCheck(srv, path, parentID) 94 | return err 95 | }, retryIfNeeded) 96 | if err != nil { 97 | log.Fatalf("Unexpected error while uploading file '%s' (from %s): %v", info.Name(), path, err) 98 | } 99 | if conf.Verbose { 100 | log.Printf("Uploaded file '%s' (from %s) with ID %s", info.Name(), path, *id) 101 | } 102 | }() 103 | } 104 | return nil 105 | }) 106 | // wait for all goroutines to finish working 107 | uploadWg.Wait() 108 | if err != nil { 109 | return errors.New(fmt.Sprintf("failed to sync directory: %v", err)) 110 | } 111 | // mark the folder as already synced 112 | _, err = os.Create(markFilePath) 113 | if err != nil { 114 | return E.ErrorSetMarkFailed(err.Error()) 115 | } 116 | if conf.Verbose { 117 | log.Printf("Sync completed for directory '%s' into category %s.", path, category) 118 | } 119 | return nil 120 | } 121 | 122 | // SyncFile accepts a path to upload to Google Drive to the specified category, 123 | // returning any error that happens in the process. 124 | // 125 | // It creates a (".sync_finished-"+filepath.Base(path)) mark file in the directory containing 126 | // the file, and will return an ErrorAlreadySynced directly if that mark is present. 127 | func SyncFile(reader *bufio.Reader, srv *drive.Service, path, category string) error { 128 | conf := C.Config.Get() 129 | // clean the path to avoid surprises 130 | path = filepath.Clean(path) 131 | parentPath, basename := filepath.Split(path) 132 | if _, ok := C.IgnoreList[basename]; ok || strings.HasPrefix(basename, ".sync_finished") { 133 | // file to be ignored 134 | log.Printf(`I: Useless file %q ignored for syncing.`, path) 135 | return nil 136 | } 137 | markFilePath := parentPath + ".sync_finished-" + basename 138 | // check if we have the mark file 139 | if _, err := os.Stat(markFilePath); err == nil { 140 | return E.ErrorAlreadySynced("file already synced") 141 | } else if !os.IsNotExist(err) { 142 | return errors.New(fmt.Sprintf("failed to check sync mark: %v", err)) 143 | } 144 | parentID, err := getUploadLocation(reader, srv, category) 145 | if err != nil { 146 | return err 147 | } 148 | ctx := context.Background() 149 | routineID := fmt.Sprintf("%05x", rand.Uint32()%0xfffff) 150 | id := new(string) 151 | err = withRetry(U.CtxWithLoggerID(ctx, routineID), func() error { 152 | var err error 153 | *id, err = createFileWithCheck(srv, path, parentID) 154 | return err 155 | }, retryIfNeeded) 156 | if err != nil { 157 | log.Fatalf("Unexpected error while uploading file '%s' (from %s): %v", basename, path, err) 158 | } 159 | if conf.Verbose { 160 | log.Printf("Uploaded file '%s' (from %s) with ID %s", basename, path, *id) 161 | } 162 | _, err = os.Create(markFilePath) 163 | if err != nil { 164 | return E.ErrorSetMarkFailed(err.Error()) 165 | } 166 | log.Printf("Sync completed for file '%s' into category %s.", path, category) 167 | return nil 168 | } 169 | 170 | // Sync accepts a path to an object, either a directory or a file, and uploads it to Google 171 | // Drive to the specified category, returning any error that happens in the process. 172 | // 173 | // It calls the corresponding function (either `SyncDirectory` or `SyncFile`) for processing. 174 | func Sync(reader *bufio.Reader, srv *drive.Service, path, category string) error { 175 | f, err := os.Open(path) 176 | if err != nil { 177 | return errors.New(fmt.Sprintf("failed to open path: %v", err)) 178 | } 179 | if fi, err := f.Stat(); err != nil { 180 | return errors.New(fmt.Sprintf("failed to stat path: %v", err)) 181 | } else { 182 | if fi.IsDir() { 183 | return SyncDirectory(reader, srv, path, category) 184 | } else { 185 | return SyncFile(reader, srv, path, category) 186 | } 187 | } 188 | } 189 | 190 | // SyncWithGuess accepts a C.Guesser and relevant arguments to call Sync, guessing the appropriate 191 | // category automatically. 192 | func SyncWithGuess(reader *bufio.Reader, srv *drive.Service, path string, guesser C.Guesser) error { 193 | return Sync(reader, srv, path, guesser.Guess(filepath.Base(path))) 194 | } 195 | -------------------------------------------------------------------------------- /remote/utils.go: -------------------------------------------------------------------------------- 1 | package remote 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "log" 8 | "mime" 9 | "net" 10 | "os" 11 | "path/filepath" 12 | "strings" 13 | "time" 14 | 15 | "golang.org/x/net/context" 16 | "google.golang.org/api/drive/v3" 17 | "google.golang.org/api/googleapi" 18 | 19 | C "github.com/KireinaHoro/DriveSync/config" 20 | E "github.com/KireinaHoro/DriveSync/errors" 21 | U "github.com/KireinaHoro/DriveSync/utils" 22 | ) 23 | 24 | // yesNoResponse prompts the user to make a choice, returning a boolean. 25 | func yesNoResponse(reader *bufio.Reader, prompt string) bool { 26 | if !C.Interactive { 27 | return false 28 | } 29 | fmt.Print(prompt + " [Y/n]: ") 30 | for { 31 | response, scanErr := reader.ReadString('\n') 32 | if scanErr != nil { 33 | log.Fatalf("failed to scan response: %v", scanErr) 34 | } 35 | switch strings.ToUpper(strings.TrimRight(response, "\n")) { 36 | case "": 37 | fallthrough 38 | case "Y": 39 | return true 40 | case "N": 41 | return false 42 | default: 43 | fmt.Printf("Sorry, response '%v' not understood. ", response) 44 | } 45 | } 46 | } 47 | 48 | // getLeafFromParent resolves the ID of the requested leaf in given folder ID. 49 | func getLeafFromParent(srv *drive.Service, leafName, parentID string, wantFolder bool) (string, error) { 50 | var q []string 51 | q = append(q, fmt.Sprintf("('%s' in parents)", parentID)) 52 | q = append(q, fmt.Sprintf("name='%s'", leafName)) 53 | if wantFolder { 54 | q = append(q, fmt.Sprintf("mimeType='%s'", C.DriveFolderType)) 55 | } else { 56 | q = append(q, fmt.Sprintf("mimeType!='%s'", C.DriveFolderType)) 57 | } 58 | q = append(q, "trashed=false") 59 | ansList, err := srv.Files.List().Q(strings.Join(q, "and")).Fields("files(id)").Do() 60 | if err != nil { 61 | return "", errors.New(fmt.Sprintf("failed to fetch ID of '%s': %v", leafName, err)) 62 | } else if len(ansList.Files) == 0 { 63 | return "", E.ErrorNotFound(fmt.Sprintf("error: no '%s' in '%s'", leafName, parentID)) 64 | } else if len(ansList.Files) > 1 { 65 | // return an E.ErrorMultipleResults 66 | var ret []string 67 | for _, f := range ansList.Files { 68 | ret = append(ret, f.Id) 69 | } 70 | return "", E.ErrorMultipleResults(ret) 71 | } 72 | return ansList.Files[0].Id, nil 73 | } 74 | 75 | // getUploadLocation resolves the folder ID of the given category. 76 | func getUploadLocation(reader *bufio.Reader, srv *drive.Service, category string) (string, error) { 77 | conf := C.Config.Get() 78 | var err error 79 | // get the archive root 80 | if C.ArchiveRootID == "" { 81 | C.ArchiveRootID, err = getLeafFromParent(srv, conf.ArchiveRootName, "root", true) 82 | if err != nil { 83 | if _, ok := err.(E.ErrorNotFound); conf.CreateMissing || (ok && 84 | yesNoResponse(reader, "Archive root not found; create it now?")) { 85 | C.ArchiveRootID, err = createDirectory(srv, conf.ArchiveRootName, "root") 86 | if err != nil { 87 | return "", errors.New(fmt.Sprintf("failed to create archive root '%s': %v", 88 | conf.ArchiveRootName, err)) 89 | } 90 | if conf.Verbose { 91 | log.Printf("Created %q.", conf.ArchiveRootName) 92 | } 93 | } else { 94 | return "", errors.New(fmt.Sprintf("failed to retrieve archive root '%s': %v", 95 | conf.ArchiveRootName, err)) 96 | } 97 | } 98 | } 99 | // get the desired category 100 | categoryID, ok := C.CategoryIDs.Get(category) 101 | if !ok { 102 | categoryID, err = getLeafFromParent(srv, category, C.ArchiveRootID, true) 103 | if err != nil { 104 | if _, ok := err.(E.ErrorNotFound); conf.CreateMissing || (ok && 105 | yesNoResponse(reader, fmt.Sprintf("Category '%s' not found; create it now?", category))) { 106 | categoryID, err = createDirectory(srv, category, C.ArchiveRootID) 107 | if err != nil { 108 | return "", errors.New(fmt.Sprintf("failed to create category '%s': %v", 109 | category, err)) 110 | } 111 | if conf.Verbose { 112 | log.Printf("Created %q.", category) 113 | } 114 | } else { 115 | return "", errors.New(fmt.Sprintf("failed to retrieve category '%s': %v", 116 | category, err)) 117 | } 118 | } 119 | C.CategoryIDs.Set(category, categoryID) 120 | } 121 | //fmt.Printf("Category folder ID: %s\n", categoryID) 122 | return categoryID, nil 123 | } 124 | 125 | // createDirectory creates the directory with name leafName inside directory 126 | // with ID of parentID, returning the ID of the created folder. 127 | // 128 | // Note: the caller shall check if the directory with leafName exists. 129 | // Failing to do so will result in duplicate directories. 130 | func createDirectory(srv *drive.Service, leafName, parentID string) (string, error) { 131 | createInfo := &drive.File{ 132 | Name: leafName, 133 | Description: leafName, 134 | MimeType: C.DriveFolderType, 135 | Parents: []string{parentID}, 136 | } 137 | info, err := srv.Files.Create(createInfo).Fields("id").Do() 138 | if err != nil { 139 | //return "", errors.New(fmt.Sprintf("failed to create on Drive server: %v", err)) 140 | return "", err 141 | } else { 142 | return info.Id, nil 143 | } 144 | } 145 | 146 | // createDirectoryWithCheck checks if the directory with given name exists in given parentID. 147 | // If such folder exists, it will return the ID of the existing folder; otherwise a new one 148 | // will be created. 149 | // 150 | // This function is to eliminate the problem of duplicate files on remote. 151 | func createDirectoryWithCheck(srv *drive.Service, leafName, parentID string) (string, error) { 152 | fileID, err := getLeafFromParent(srv, leafName, parentID, true) 153 | if err != nil { 154 | if _, ok := err.(E.ErrorNotFound); ok { 155 | return createDirectory(srv, leafName, parentID) 156 | } else { 157 | return "", err 158 | } 159 | } 160 | return fileID, nil 161 | } 162 | 163 | // createFile creates the file with path leafPath inside directory 164 | // with ID of parentID, uploads the contents of the file, and 165 | // returns the ID of the created file. If C.Config.ForceRecheck is true, it checks if the MD5 166 | // sums of remote and local matches. 167 | // 168 | // Note: the caller shall check if the file with leafName exists. 169 | // Failing to do so will result in duplicate files. 170 | func createFile(srv *drive.Service, leafPath, parentID string) (string, error) { 171 | conf := C.Config.Get() 172 | leafName := filepath.Base(leafPath) 173 | uploadFile, err := os.Open(leafPath) 174 | if err != nil { 175 | return "", errors.New(fmt.Sprintf("failed to open file '%s': %v", leafPath, err)) 176 | } 177 | createInfo := &drive.File{ 178 | Name: leafName, 179 | Description: leafName, 180 | MimeType: mime.TypeByExtension(filepath.Ext(leafName)), 181 | Parents: []string{parentID}, 182 | } 183 | //info, err := srv.Files.Create(createInfo).Media(uploadFile).Fields("id, md5Checksum").Do() 184 | // we don't need the md5Checksum field if C.Config.ForceRecheck != true 185 | intermediateCall := srv.Files.Create(createInfo).Media(uploadFile) 186 | if conf.ForceRecheck { 187 | intermediateCall = intermediateCall.Fields("id, md5Checksum") 188 | } else { 189 | intermediateCall = intermediateCall.Fields("id") 190 | } 191 | retVal, retErr := make(chan *drive.File), make(chan error) 192 | go func() { 193 | info, err := intermediateCall.Do() 194 | retErr <- err 195 | retVal <- info 196 | }() 197 | var info *drive.File 198 | if conf.ForceRecheck { 199 | f, err := os.Open(leafPath) 200 | if err != nil { 201 | return "", errors.New(fmt.Sprintf("failed to open file for checksum: %v", err)) 202 | } 203 | defer f.Close() 204 | 205 | // calculate the MD5 hash of the file 206 | realSum, err := U.CalculateSum(f) 207 | if err != nil { 208 | return "", errors.New(fmt.Sprintf("failed to calculate md5Checksum: %v", err)) 209 | } 210 | 211 | err = <-retErr 212 | if err != nil { 213 | return "", err 214 | } 215 | info = <-retVal 216 | if sum := info.Md5Checksum; sum != realSum { 217 | return "", E.ErrorChecksumMismatch(fmt.Sprintf( 218 | "md5Checksum mismatch: remote %s, local %s", sum, realSum)) 219 | } 220 | //log.Printf("file '%s' has identical remote/local md5Checksum", leafPath) 221 | } else { 222 | err := <-retErr 223 | if err != nil { 224 | return "", err 225 | } 226 | info = <-retVal 227 | } 228 | return info.Id, nil 229 | } 230 | 231 | // createFileWithCheck checks if the file with given name exists in given parentID. 232 | // If such file exists, it will delete the existing file so that situation of duplicate files 233 | // won't occur. 234 | // 235 | // This function is to eliminate the problem of duplicate files on remote. 236 | func createFileWithCheck(srv *drive.Service, leafPath, parentID string) (string, error) { 237 | leafName := filepath.Base(leafPath) 238 | fileID, err := getLeafFromParent(srv, leafName, parentID, false) 239 | if err == nil { 240 | // check file's checksum 241 | f, err := os.Open(leafPath) 242 | if err != nil { 243 | // non-critical; log the failure and continue 244 | if C.Verbose { 245 | log.Printf("Failed to open file for checksum calculation: %v", err) 246 | } 247 | goto AfterCheck 248 | } else { 249 | realSum, err := U.CalculateSum(f) 250 | if err != nil { 251 | // non-critical; log the failure and continue 252 | if C.Verbose { 253 | log.Printf("Failed to calculate checksum: %v", err) 254 | } 255 | goto AfterCheck 256 | } else { 257 | file, err := srv.Files.Get(fileID).Fields("md5Checksum").Do() 258 | if err != nil { 259 | // non-critical; log the failure and continue 260 | if C.Verbose { 261 | log.Printf("Failed to get remote file checksum: %v", err) 262 | } 263 | goto AfterCheck 264 | } 265 | if realSum == file.Md5Checksum { 266 | // we have identical copies of files 267 | if C.Verbose { 268 | log.Printf("File %q (%s) has identical remote and local versions, skipping re-upload.", 269 | leafName, fileID) 270 | } 271 | return fileID, nil 272 | } 273 | } 274 | } 275 | 276 | AfterCheck: 277 | err = srv.Files.Delete(fileID).Do() 278 | if err != nil { 279 | if C.Verbose { 280 | // non-critical; log the failure and continue 281 | log.Printf("Failed to remove existing file %q with ID %q: %v", leafName, fileID, err) 282 | } 283 | } else { 284 | if C.Verbose { 285 | log.Printf("Removed existing file %q with ID %q.", leafName, fileID) 286 | } 287 | } 288 | } else if err, ok := err.(E.ErrorMultipleResults); ok { 289 | // multiple results; we should delete all of them 290 | for _, f := range err { 291 | e := srv.Files.Delete(f).Do() 292 | if e != nil { 293 | if C.Verbose { 294 | // non-critical; log the failure and continue 295 | log.Printf("Failed to remove existing file %q with ID %q: %v", leafName, f, err) 296 | } 297 | } else { 298 | if C.Verbose { 299 | log.Printf("Removed existing file %q with ID %q.", leafName, f) 300 | } 301 | } 302 | } 303 | } 304 | return createFile(srv, leafPath, parentID) 305 | } 306 | 307 | // withRetry executes fn with retry upon failure in an exponential-backoff manner, 308 | // if the error returned by fn satisfies shouldRetry. 309 | func withRetry(ctx context.Context, fn func() error, shouldRetry func(error) bool) error { 310 | conf := C.Config.Get() 311 | l := U.GetLogger(ctx) 312 | err := fn() 313 | if shouldRetry(err) { 314 | if conf.Verbose { 315 | l.Printf("Need to retry due to: %v", err) 316 | } 317 | err = retry(ctx, fn, shouldRetry, C.RetryStartingRate, C.RetryRatio) 318 | } 319 | if err != nil { 320 | err = errors.New(fmt.Sprintf("[Job #%s] retry failed: %v", l, err)) 321 | } 322 | return err 323 | } 324 | 325 | // retry increases retry timeout by factor ratio every time until success, or if an error not 326 | // worth trying occurs. 327 | func retry(ctx context.Context, fn func() error, shouldRetry func(error) bool, currentRate, ratio int) error { 328 | conf := C.Config.Get() 329 | l := U.GetLogger(ctx) 330 | if conf.Verbose { 331 | l.Printf("Waiting %d second(s) before retrying...", currentRate) 332 | } 333 | time.Sleep(time.Duration(currentRate) * time.Second) 334 | err := fn() 335 | if shouldRetry(err) { 336 | err = retry(ctx, fn, shouldRetry, currentRate*ratio, ratio) 337 | } 338 | return err 339 | } 340 | 341 | // retryIfNeeded takes an error, returning true if it's worth retrying. 342 | func retryIfNeeded(err error) bool { 343 | if err != nil { 344 | if realErr, ok := err.(*googleapi.Error); ok { 345 | // retry on rate limit and all server-side errors 346 | if realErr.Code == 403 && strings.Contains( 347 | strings.ToLower(realErr.Message), "rate limit") { 348 | return true 349 | } else if 499 < realErr.Code && realErr.Code < 600 { 350 | return true 351 | } 352 | } else if _, ok := err.(E.ErrorChecksumMismatch); ok { 353 | // retry on checksum mismatch 354 | return true 355 | } else if _, ok := err.(net.Error); ok { 356 | // retry on network problem 357 | return true 358 | } 359 | } 360 | return false 361 | } 362 | -------------------------------------------------------------------------------- /utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "sync" 7 | 8 | "golang.org/x/net/context" 9 | "io" 10 | "crypto/md5" 11 | "encoding/hex" 12 | ) 13 | 14 | // SafeMap is a concurrent-safe map[string]string 15 | type safeMap struct { 16 | v map[string]string 17 | m sync.Mutex 18 | } 19 | 20 | func NewSafeMap() *safeMap { 21 | return &safeMap{v: make(map[string]string)} 22 | } 23 | 24 | func (r *safeMap) Get(key string) (value string, ok bool) { 25 | r.m.Lock() 26 | defer r.m.Unlock() 27 | value, ok = r.v[key] 28 | return 29 | } 30 | 31 | func (r *safeMap) Set(key, value string) { 32 | r.m.Lock() 33 | defer r.m.Unlock() 34 | r.v[key] = value 35 | } 36 | 37 | // logger provides pretty logging when used with goroutines, with pseudo-routine-id 38 | // for logs with better readability. 39 | type logger string 40 | 41 | const loggerID = "logger_id" 42 | 43 | func (l logger) Printf(format string, v ...interface{}) { 44 | log.Printf("[Job #%s] %s", l, fmt.Sprintf(format, v...)) 45 | } 46 | 47 | func (l logger) Println(v ...interface{}) { 48 | log.Printf("[Job #%s] %s", l, fmt.Sprintln(v...)) 49 | } 50 | 51 | // CtxWithLoggerID generates a new context with loggerID for logging. 52 | func CtxWithLoggerID(ctx context.Context, id string) context.Context { 53 | return context.WithValue(ctx, loggerID, id) 54 | } 55 | 56 | // GetLogger extracts logger from context. 57 | func GetLogger(ctx context.Context) logger { 58 | return logger(ctx.Value(loggerID).(string)) 59 | } 60 | 61 | // CalculateSum takes an io.Reader and calculates its md5Checksum. 62 | func CalculateSum(f io.Reader) (string, error) { 63 | h := md5.New() 64 | if _, err := io.Copy(h, f); err != nil { 65 | return "", err 66 | } 67 | return hex.EncodeToString(h.Sum(nil)), nil 68 | } 69 | --------------------------------------------------------------------------------