From 0ca48fecfd09b6dd1ab6a69ab0fb6f6084e4f97d Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Sat, 19 Jan 2019 20:28:53 -0700 Subject: [PATCH] Initial commit --- .gitignore | 5 + .sqliterc | 1 + LICENSE.txt | 661 ++++++++++++++++++ README.md | 123 ++++ account.go | 153 ++++ cmd/timeliner/main.go | 260 +++++++ datasource.go | 196 ++++++ datasources/facebook/facebook.go | 480 +++++++++++++ datasources/facebook/media.go | 184 +++++ datasources/facebook/post.go | 127 ++++ datasources/googlelocation/googlelocation.go | 338 +++++++++ datasources/googlephotos/googlephotos.go | 396 +++++++++++ datasources/googlephotos/media.go | 234 +++++++ datasources/twitter/models.go | 428 ++++++++++++ datasources/twitter/twitter.go | 317 +++++++++ db.go | 144 ++++ itemfiles.go | 283 ++++++++ itemgraph.go | 407 +++++++++++ mapmutex.go | 39 ++ oauth2.go | 100 +++ oauth2client/browser.go | 137 ++++ oauth2client/localapp.go | 57 ++ oauth2client/oauth2.go | 62 ++ .../oauth2proxy/cmd/oauth2proxy/main.go | 75 ++ oauth2client/oauth2proxy/proxy.go | 191 +++++ oauth2client/remoteapp.go | 192 +++++ persons.go | 75 ++ processing.go | 544 ++++++++++++++ ratelimit.go | 59 ++ timeliner.go | 133 ++++ wrappedclient.go | 276 ++++++++ 31 files changed, 6677 insertions(+) create mode 100644 .gitignore create mode 100644 .sqliterc create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 account.go create mode 100644 cmd/timeliner/main.go create mode 100644 datasource.go create mode 100644 datasources/facebook/facebook.go create mode 100644 datasources/facebook/media.go create mode 100644 datasources/facebook/post.go create mode 100644 datasources/googlelocation/googlelocation.go create mode 100644 datasources/googlephotos/googlephotos.go create mode 100644 datasources/googlephotos/media.go create mode 100644 datasources/twitter/models.go create mode 100644 datasources/twitter/twitter.go create mode 100644 db.go create mode 100644 itemfiles.go create mode 100644 itemgraph.go create mode 100644 mapmutex.go create mode 100644 oauth2.go create mode 100644 oauth2client/browser.go create mode 100644 oauth2client/localapp.go create mode 100644 oauth2client/oauth2.go create mode 100644 oauth2client/oauth2proxy/cmd/oauth2proxy/main.go create mode 100644 oauth2client/oauth2proxy/proxy.go create mode 100644 oauth2client/remoteapp.go create mode 100644 persons.go create mode 100644 processing.go create mode 100644 ratelimit.go create mode 100644 timeliner.go create mode 100644 wrappedclient.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3456dbd --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +_gitignore/ +_storage/ +oauth2client/oauth2proxy/cmd/oauth2proxy/credentials.toml +cmd/timeliner/config.toml +cmc/timeliner/timeliner \ No newline at end of file diff --git a/.sqliterc b/.sqliterc new file mode 100644 index 0000000..c8ccb13 --- /dev/null +++ b/.sqliterc @@ -0,0 +1 @@ +PRAGMA foreign_keys = ON; diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2451b55 --- /dev/null +++ b/README.md @@ -0,0 +1,123 @@ +Timeliner [![timeliner GoDoc](https://img.shields.io/badge/reference-godoc-blue.svg?style=flat-square)](https://godoc.org/github.com/mholt/timeliner) +========= + +Timeliner is a personal data aggregation utility. It collects all your digital things from pretty much anywhere and stores them on your own computer, indexes them, and projects them onto a single, unified timeline. + +The intended purpose of this tool is to help preserve personal and family history. + +Things that are stored by Timeliner are easily accessible in a SQLite database or, for media items like photos and videos, are simply plopped onto your disk as regular files, organized in folders by date and data source. + +**WORK IN PROGRESS NOTICE:** This project works as documented for the most part, but is still very young. Please contribute bug fixes, and note the TODOs in the code! + + +## About + +In general, Timeliner obtains _items_ from _data sources_ and stores them in a _timeline_. + +- **Items** are anything that has content: text, image, video, etc. For example: photos, tweets, social media posts, even locations. +- **Data sources** are anything that can provide a list of items. For example: social media sites, online services, archive files, etc. +- **Timelines** are repositories that store the data. Typically, you will have one timeline that is your own, but timelines can support multiple people and multiple accounts per person if you desire to share it. + +Technically speaking: + +- An **Item** implements this interface (TODO: godoc link) and provides access to its content and metadata. +- A **DataSource** is defined by this struct (TODO: godoc link) and configures a Client to access it. Clients are the types that actually do the listing of items. +- A **Timeline** is opened when being used. It consists of an underlying SQLite database and an adjacent data folder where larger/media items are stored as files. Timelines are essentially the folder that contains them. They are portable, so you can move them around and won't break things. However, don't change the contents of the folder directly! Don't add, remove, or modify items in the folder; you will break something. This does not mean timelines are read-only: they just have to be modified through the program in order to stay consistent. + + +## Supported Data Sources + +Data sources along with their unique ID: + +- Facebook (`facebook`) +- Google Location History (`google_location`) +- Google Photos (`google_photos`) +- Twitter (`twitter`) + +With the possibility to add many more. Please contribute! + + +## Install + +``` +$ go get -u github.com/mholt/timeliner/cmd/timeliner +``` + +## Tutorial + +All items are associated with an account from whence they come. Even if a data source doesn't have "accounts" strictly speaking, we still need to pretend they exist to keep things uniform. + +Accounts are designated in the form `/`. The user ID does not necessarily matter; just choose one that you will recognize, such that the data source ID + user ID are unique. Typically it is your login username or email address. + +If we want to use accounts that require OAuth2, we need to configure Timeliner with OAuth2 app credentials. By default, Timeliner will try to load `config.toml` in the current directory, but you can use the `-config` flag to change that. Here's a sample `config.toml` file for authenticating with Google: + +``` +[oauth2.providers.google] +client_id = "YOUR_APP_ID" +client_secret = "YOUR_APP_SECRET" +auth_url = "https://accounts.google.com/o/oauth2/auth" +token_url = "https://accounts.google.com/o/oauth2/token" +``` + +With that, let's create an account to store our Google Photos: + +``` +$ timeliner add-account google_photos/you@gmail.com +``` + +This will open your browser window to authenticate with OAuth2. + +You will notice that a folder called `timeliner_repo` was created in the current directory. This is your timeline. You can move it around if you want, and then use the `-repo` flag to work with that timeline. + +Now let's get all our stuff from Google Photos. And I mean, _all_ of it. It's ours, after all, not Google's: + +``` +$ timeliner get-all google_photos/you@gmail.com +``` + +This process can take weeks if you have a large librarry. Even if you have a fast Internet connection, the client is carefully rate-limited to be a good API citizen, so the process will be slow. + +If you open your timeline folder in a file browser, you will see it start to fill up with your photos from Google Photos. + +Data sources may create checkpoints as they go, so if a listing is resumable, `get-all` will automatically resume the last download if it did not complete. In the case of Google Photos, each page of API results is checkpointed. Checkpoints are not intended for long-term pauses. In other words, a resume should happen fairly shortly after being interrupted. + +Item processing is idempotent, so as long as items have faithfully-unique IDs across each account, items that already exist in the timeline will be skipped and/or processed much faster. + + +### Pulling the latest + +Once your initial download completes, you can run Timeliner so that only the latest items are retrieved: + +``` +$ timeliner get-latest google_photos/you@gmail.com +``` + +This will get only the items timestamped newer than the newest item in your timeline. + + +### Pruning your timeline + +Suppose you downloaded a bunch of photos with Timeliner that you later deleted from Google Photos. Timeliner can remove those items from your own timeline, too, to save disk space and keep things clean. + +However, this involves doing a complete listing of all the items. Pruning happens at the end. Any items not seen in the listing will be deleted. This also means that a full, uninterrupted listing is required, since resuming from a checkpoint yields an incomplete file listing. Pruning after a resumed listing will result in an error. (There's a TODO to improve this situation -- feel free to contribute! We just need to preserve the item listing along with the checkpoint.) + + +## Viewing your Timeline + +There is not currently a nice, all-in-one viewer for the timeline. I've just been using [Table Plus](https://tableplus.io) to browse the SQLite database, and my file browser to look at the files that are dumped. The important thing is that you have them. + +However, a viewer would be really cool. Contributions are welcomed along these lines, but this feature _must_ be thoroughly discussed before any pull requests will be accepted to implement a timeline viewer. Thanks! + + + +## License + +This project is licensed with AGPL. I chose this license because although I do want this software to be used very liberally, I do not want others to make proprietary software using this package. + +The point of this project is liberation of and control over one's own, personal data, and I want to ensure that this project won't be used in anything to perpetuate the walled garden situation we already face today. + + +## Notes + +Yes, I know this is very similar to what [Perkeep](https://perkeep.org/) does. Perkeep is a way cooler project in my opinion. However, Perkeep is more about storage and sync, whereas Timeliner is more focused on constructing relationships between items and projecting your digital life onto a single timeline. If Perkeep is my unified personal data storage, then Timeliner is my automatic journal. (But yes, I did have a slight headache after I realized that I was almost rewriting parts of Perkeep, until I decided that the two are different enough to warrant a separate project.) + diff --git a/account.go b/account.go new file mode 100644 index 0000000..e1b3405 --- /dev/null +++ b/account.go @@ -0,0 +1,153 @@ +package timeliner + +import ( + "bytes" + "encoding/gob" + "fmt" + "net/http" + "time" +) + +// Account represents an account with a service. +type Account struct { + ID int64 + DataSourceID string + UserID string + person Person + authorization []byte + checkpoint []byte + + t *Timeline + ds DataSource +} + +// NewHTTPClient returns an HTTP client that is suitable for use +// with an API associated with the account's data source. If +// OAuth2 is configured for the data source, the client has OAuth2 +// credentials. If a rate limit is configured, this client is +// rate limited. A sane default timeout is set, and any fields +// on the returned Client valule can be modified as needed. +func (acc Account) NewHTTPClient() (*http.Client, error) { + httpClient := new(http.Client) + if acc.ds.OAuth2.ProviderID != "" { + var err error + httpClient, err = acc.NewOAuth2HTTPClient() + if err != nil { + return nil, err + } + } + if acc.ds.RateLimit.RequestsPerHour > 0 { + httpClient.Transport = acc.NewRateLimitedRoundTripper(httpClient.Transport) + } + httpClient.Timeout = 30 * time.Second + return httpClient, nil +} + +// AddAccount authenticates userID with the service identified +// within the application by dataSourceID, and then stores it in the +// database. +func (t *Timeline) AddAccount(dataSourceID, userID string) error { + ds, ok := dataSources[dataSourceID] + if !ok { + return fmt.Errorf("data source not registered: %s", dataSourceID) + } + + // ensure account is not already stored in our system + var count int + err := t.db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE data_source_id=? AND user_id=? LIMIT 1`, + dataSourceID, userID).Scan(&count) + if err != nil { + return fmt.Errorf("checking if account is already stored: %v", err) + } + if count > 0 { + return fmt.Errorf("account already stored in database: %s/%s", dataSourceID, userID) + } + + // authenticate with the data source (if necessary) + var credsBytes []byte + if authFn := ds.authFunc(); authFn != nil { + credsBytes, err = authFn(userID) + if err != nil { + return fmt.Errorf("authenticating %s for %s: %v", userID, dataSourceID, err) + } + } + + // make sure the data source is registered in the DB + _, err = t.db.Exec(`INSERT OR IGNORE INTO data_sources (id, name) VALUES (?, ?)`, + dataSourceID, ds.Name) + if err != nil { + return fmt.Errorf("saving data source record: %v", err) + } + + // store the account along with our authorization to access it + _, err = t.db.Exec(`INSERT INTO accounts (data_source_id, user_id, authorization) VALUES (?, ?, ?)`, + dataSourceID, userID, credsBytes) + if err != nil { + return fmt.Errorf("inserting into DB: %v", err) + } + + return nil +} + +// NewClient returns a new Client that is ready to interact with +// the data source for the account uniquely specified by the data +// source ID and the user ID for that data source. The Client is +// actually wrapped by a type with unexported fields that are +// necessary for internal use. +func (t *Timeline) NewClient(dataSourceID, userID string) (WrappedClient, error) { + ds, ok := dataSources[dataSourceID] + if !ok { + return WrappedClient{}, fmt.Errorf("data source not registered: %s", dataSourceID) + } + if ds.NewClient == nil { + return WrappedClient{}, fmt.Errorf("impossible to make client for data source: %s", dataSourceID) + } + + acc, err := t.getAccount(dataSourceID, userID) + if err != nil { + return WrappedClient{}, fmt.Errorf("getting account: %v", err) + } + + cl, err := ds.NewClient(acc) + if err != nil { + return WrappedClient{}, fmt.Errorf("making client from data source: %v", err) + } + + return WrappedClient{ + Client: cl, + tl: t, + acc: acc, + ds: ds, + }, nil +} + +func (t *Timeline) getAccount(dsID, userID string) (Account, error) { + ds, ok := dataSources[dsID] + if !ok { + return Account{}, fmt.Errorf("data source not registered: %s", dsID) + } + acc := Account{ + ds: ds, + t: t, + } + err := t.db.QueryRow(`SELECT + id, data_source_id, user_id, authorization, checkpoint + FROM accounts WHERE data_source_id=? AND user_id=? LIMIT 1`, + dsID, userID).Scan(&acc.ID, &acc.DataSourceID, &acc.UserID, &acc.authorization, &acc.checkpoint) + if err != nil { + return acc, fmt.Errorf("querying account %s/%s from DB: %v", dsID, userID, err) + } + return acc, nil +} + +// MarshalGob is a convenient way to gob-encode v. +func MarshalGob(v interface{}) ([]byte, error) { + b := new(bytes.Buffer) + err := gob.NewEncoder(b).Encode(v) + return b.Bytes(), err +} + +// UnmarshalGob is a convenient way to gob-decode data into v. +func UnmarshalGob(data []byte, v interface{}) error { + return gob.NewDecoder(bytes.NewReader(data)).Decode(v) +} diff --git a/cmd/timeliner/main.go b/cmd/timeliner/main.go new file mode 100644 index 0000000..490d11f --- /dev/null +++ b/cmd/timeliner/main.go @@ -0,0 +1,260 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "os" + "strings" + "sync" + + "github.com/BurntSushi/toml" + "github.com/mholt/timeliner" + "github.com/mholt/timeliner/oauth2client" + "golang.org/x/oauth2" + + // plug in data sources + _ "github.com/mholt/timeliner/datasources/facebook" + _ "github.com/mholt/timeliner/datasources/googlelocation" + _ "github.com/mholt/timeliner/datasources/googlephotos" + "github.com/mholt/timeliner/datasources/twitter" +) + +func init() { + flag.StringVar(&configFile, "config", configFile, "The path to the config file to load") + flag.StringVar(&repoDir, "repo", repoDir, "The path to the folder of the repository") + + flag.BoolVar(&prune, "prune", prune, "When finishing, delete items not found on remote (download-all or import only)") + flag.BoolVar(&integrity, "integrity", integrity, "Perform integrity check on existing items and reprocess if needed (download-all or import only)") + flag.BoolVar(&reprocess, "reprocess", reprocess, "Reprocess every item that has not been modified locally (download-all or import only)") + + flag.BoolVar(&twitterRetweets, "twitter-retweets", twitterRetweets, "Twitter: include retweets") + flag.BoolVar(&twitterReplies, "twitter-replies", twitterReplies, "Twitter: include replies") +} + +func main() { + flag.Parse() + + // split the CLI arguments into subcommand and arguments + args := flag.Args() + if len(args) == 0 { + log.Fatal("[FATAL] Missing subcommand and account arguments (specify one or more of 'data_source_id/user_id')") + } + subcmd := args[0] + accountList := args[1:] + if subcmd == "import" { + // special case; import takes an extra argument before account list + if len(args) != 3 { + log.Fatal("[FATAL] Expecting: import ") + } + accountList = args[2:] + if len(args) == 0 { + log.Fatal("[FATAL] No accounts to use (specify one or more 'data_source_id/user_id' arguments)") + } + } + + // load the command config + err := loadConfig() + if err != nil { + log.Fatalf("[FATAL] Loading configuration: %v", err) + } + + // parse the accounts out of the CLI + accounts, err := getAccounts(accountList) + if err != nil { + log.Fatalf("[FATAL] %v", err) + } + if len(accounts) == 0 { + log.Fatalf("[FATAL] No accounts specified") + } + + // open the timeline + tl, err := timeliner.Open(repoDir) + if err != nil { + log.Fatalf("[FATAL] Opening timeline: %v", err) + } + defer tl.Close() + + // as a special case, handle AddAccount separately + if subcmd == "add-account" { + for _, a := range accounts { + err := tl.AddAccount(a.dataSourceID, a.userID) + if err != nil { + log.Fatalf("[FATAL] Adding account: %v", err) + } + } + return + } + + // make a client for each account + var clients []timeliner.WrappedClient + for _, a := range accounts { + wc, err := tl.NewClient(a.dataSourceID, a.userID) + if err != nil { + log.Fatalf("[FATAL][%s/%s] Creating data source client: %v", a.dataSourceID, a.userID, err) + } + + // configure the client + switch v := wc.Client.(type) { + case *twitter.Client: + v.Retweets = twitterRetweets + v.Replies = twitterReplies + } + + clients = append(clients, wc) + } + + switch subcmd { + case "get-latest": + if reprocess || prune || integrity { + log.Fatalf("[FATAL] The get-latest subcommand does not support -reprocess, -prune, or -integrity") + } + + var wg sync.WaitGroup + for _, wc := range clients { + wg.Add(1) + go func(wc timeliner.WrappedClient) { + defer wg.Done() + ctx, cancel := context.WithCancel(context.Background()) + err := wc.GetLatest(ctx) + if err != nil { + log.Printf("[ERROR][%s/%s] Pulling latest: %v", + wc.DataSourceID(), wc.UserID(), err) + } + defer cancel() // TODO: Make this useful, maybe? + }(wc) + } + wg.Wait() + + case "get-all": + var wg sync.WaitGroup + for _, wc := range clients { + wg.Add(1) + go func(wc timeliner.WrappedClient) { + defer wg.Done() + ctx, cancel := context.WithCancel(context.Background()) + err := wc.GetAll(ctx, reprocess, prune, integrity) + if err != nil { + log.Printf("[ERROR][%s/%s] Downloading all: %v", + wc.DataSourceID(), wc.UserID(), err) + } + defer cancel() // TODO: Make this useful, maybe? + }(wc) + } + wg.Wait() + + case "import": + file := args[1] + wc := clients[0] + + ctx, cancel := context.WithCancel(context.Background()) + err = wc.Import(ctx, file, reprocess, prune, integrity) + if err != nil { + log.Printf("[ERROR][%s/%s] Importing: %v", + wc.DataSourceID(), wc.UserID(), err) + } + defer cancel() // TODO: Make this useful, maybe? + + default: + log.Fatalf("[FATAL] Unrecognized subcommand: %s", subcmd) + } +} + +func loadConfig() error { + // no config file is allowed, but that might be useless + _, err := os.Stat(configFile) + if os.IsNotExist(err) { + return nil + } + + var cmdConfig commandConfig + md, err := toml.DecodeFile(configFile, &cmdConfig) + if err != nil { + return fmt.Errorf("decoding config file: %v", err) + } + if len(md.Undecoded()) > 0 { + return fmt.Errorf("unrecognized key(s) in config file: %+v", md.Undecoded()) + } + + // convert them into oauth2.Configs (the structure of + // oauth2.Config as TOML is too verbose for my taste) + // (important to not be pointer values, since the + // oauth2.Configs need to be copied and changed for + // each token source that is created) + oauth2Configs := make(map[string]oauth2.Config) + for id, prov := range cmdConfig.OAuth2.Providers { + if prov.RedirectURL == "" { + prov.RedirectURL = oauth2client.DefaultRedirectURL + } + oauth2Configs[id] = oauth2.Config{ + ClientID: prov.ClientID, + ClientSecret: prov.ClientSecret, + RedirectURL: prov.RedirectURL, + Endpoint: oauth2.Endpoint{ + AuthURL: prov.AuthURL, + TokenURL: prov.TokenURL, + }, + } + } + + // TODO: Should this be passed into timeliner.Open() instead? + timeliner.OAuth2TokenSource = func(providerID string, scopes []string) (oauth2client.App, error) { + cfg, ok := oauth2Configs[providerID] + if !ok { + return nil, fmt.Errorf("unsupported provider: %s", providerID) + } + cfg.Scopes = scopes + return oauth2client.LocalAppSource{OAuth2Config: &cfg}, nil + } + + return nil +} + +func getAccounts(args []string) ([]accountInfo, error) { + var accts []accountInfo + for _, a := range args { + parts := strings.SplitN(a, "/", 2) + if len(parts) < 2 { + return nil, fmt.Errorf("malformed account identifier '%s': expecting '/' format", a) + } + accts = append(accts, accountInfo{ + dataSourceID: parts[0], + userID: parts[1], + }) + } + return accts, nil +} + +type accountInfo struct { + dataSourceID string + userID string +} + +type commandConfig struct { + OAuth2 oauth2Config `toml:"oauth2"` +} + +type oauth2Config struct { + Providers map[string]oauth2ProviderConfig `toml:"providers"` +} + +type oauth2ProviderConfig struct { + ClientID string `toml:"client_id"` + ClientSecret string `toml:"client_secret"` + RedirectURL string `toml:"redirect_url"` + AuthURL string `toml:"auth_url"` + TokenURL string `toml:"token_url"` +} + +var ( + repoDir = "./timeliner_repo" + configFile = "config.toml" + + integrity bool + prune bool + reprocess bool + + twitterRetweets bool + twitterReplies bool +) diff --git a/datasource.go b/datasource.go new file mode 100644 index 0000000..5e3330e --- /dev/null +++ b/datasource.go @@ -0,0 +1,196 @@ +package timeliner + +import ( + "bytes" + "context" + "database/sql" + "encoding/gob" + "fmt" + "log" + "time" +) + +func init() { + tdBuf := new(bytes.Buffer) + err := gob.NewEncoder(tdBuf).Encode(Metadata{}) + if err != nil { + log.Fatalf("[FATAL] Unable to gob-encode metadata struct: %v", err) + } + metadataGobPrefix = tdBuf.Bytes() +} + +// RegisterDataSource registers ds as a data source. +func RegisterDataSource(ds DataSource) error { + if ds.ID == "" { + return fmt.Errorf("missing ID") + } + if ds.Name == "" { + return fmt.Errorf("missing Name") + } + if ds.OAuth2.ProviderID != "" && ds.Authenticate != nil { + return fmt.Errorf("conflicting ways of obtaining authorization") + } + + // register the data source + if _, ok := dataSources[ds.ID]; ok { + return fmt.Errorf("data source already registered: %s", ds.ID) + } + dataSources[ds.ID] = ds + + return nil +} + +func saveAllDataSources(db *sql.DB) error { + if len(dataSources) == 0 { + return nil + } + + query := `INSERT INTO "data_sources" ("id", "name") VALUES` + var vals []interface{} + var count int + + for _, ds := range dataSources { + if count > 0 { + query += "," + } + query += " (?, ?)" + vals = append(vals, ds.ID, ds.Name) + count++ + } + + query += " ON CONFLICT DO NOTHING" + + _, err := db.Exec(query, vals...) + if err != nil { + return fmt.Errorf("writing data sources to DB: %v", err) + } + + return nil +} + +// DataSource has information about a +// data source that can be registered. +type DataSource struct { + // A snake_cased name of the service + // that uniquely identifies it from + // all others. + ID string + + // The human-readable or brand name of + // the service. + Name string + + // If the service authenticates with + // OAuth2, fill out this field. + OAuth2 OAuth2 + + // Otherwise, if the service uses some + // other form of authentication, + // Authenticate is a function which + // returns the credentials needed to + // access an account on the service. + Authenticate AuthenticateFn + + // If the service enforces a rate limit, + // specify it here. You can abide it by + // getting an http.Client from the + // Account passed into NewClient. + RateLimit RateLimit + + // NewClient is a function which takes + // information about the account and + // returns a type which can facilitate + // transactions with the service. + NewClient NewClientFn +} + +// authFunc gets the authentication function for this +// service. If s.Authenticate is set, it returns that; +// if s.OAuth2 is set, it uses a standard OAuth2 func. +// TODO: update godoc +func (ds DataSource) authFunc() AuthenticateFn { + if ds.Authenticate != nil { + return ds.Authenticate + } else if ds.OAuth2.ProviderID != "" { + return func(userID string) ([]byte, error) { + return authorizeWithOAuth2(ds.OAuth2.ProviderID, ds.OAuth2.Scopes) + } + } + return nil +} + +// OAuth2 defines which OAuth2 provider a service +// uses and which scopes it requires. +type OAuth2 struct { + // The ID of the service must be recognized + // by the OAuth2 app configuration. + ProviderID string + + // The list of scopes to ask for during auth. + Scopes []string +} + +// AuthenticateFn is a function that authenticates userID with a service. +// It returns the authorization or credentials needed to operate. The return +// value should be byte-encoded so it can be stored in the DB to be reused. +// To store arbitrary types, encode the value as a gob, for example. +type AuthenticateFn func(userID string) ([]byte, error) + +// NewClientFn is a function that returns a client which, given +// the account passed in, can interact with a service provider. +type NewClientFn func(acc Account) (Client, error) + +// Client is a type that can interact with a data source. +type Client interface { + // ListItems lists the items on the account. Items should be + // sent on itemChan as they are discovered, but related items + // should be combined onto a single ItemGraph so that their + // relationships can be stored. If the relationships are not + // discovered until later, that's OK: item processing is + // idempotent, so repeating an item from earlier will have no + // adverse effects. + // + // Implementations must honor the context's cancellation. If + // ctx.Done() is closed, the function should return. Typically, + // this is done by having an outer loop select over ctx.Done() + // and default, where the next page or set of items is handled + // in the default case. + // + // ListItems MUST close itemChan when returning. A + // `defer close(itemChan)` will usually suffice. Closing + // this channel signals to the processing goroutine that + // no more items are coming. + // + // Further options for listing items may be passed in opt. + // + // If opt.Filename is specified, the implementation is expected + // to open and list items from that file. If this is not + // supported, an error should be returned. Conversely, if a + // filename is not specified but required, an error should be + // returned. + // + // opt.Timeframe consists of two optional timestamp values. + // If set, item listings should be bounded in the respective + // direction by that timestamp. If timeframes are not supported, + // this should be documented, but an error need not be returned. + // + // opt.Checkpoint consists of the last checkpoint for this + // account if the last call to ListItems did not finish and + // if a checkpoint was saved. If not nil, the checkpoint + // should be used to resume the listing instead of starting + // over from the beginning. Checkpoint values usually consist + // of page tokens or whatever state is required to resume. Call + // timeliner.Checkpoint to set a checkpoint. Checkpoints are not + // required, but if the implementation sets checkpoints, it + // should be able to resume from one, too. + ListItems(ctx context.Context, itemChan chan<- *ItemGraph, opt Options) error +} + +// Timeframe represents a start and end time, where +// either value could be nil, meaning unbounded in +// that direction. +type Timeframe struct { + Since, Until *time.Time +} + +var dataSources = make(map[string]DataSource) diff --git a/datasources/facebook/facebook.go b/datasources/facebook/facebook.go new file mode 100644 index 0000000..77dceef --- /dev/null +++ b/datasources/facebook/facebook.go @@ -0,0 +1,480 @@ +// Package facebook implements the Facebook service using +// the Graph API: https://developers.facebook.com/docs/graph-api +package facebook + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/url" + "strings" + "sync" + + "github.com/mholt/timeliner" +) + +// Data source name and ID. +const ( + DataSourceName = "Facebook" + DataSourceID = "facebook" +) + +var dataSource = timeliner.DataSource{ + ID: DataSourceID, + Name: DataSourceName, + OAuth2: timeliner.OAuth2{ + ProviderID: "facebook", + Scopes: []string{ + "public_profile", + "user_posts", + "user_photos", + "user_videos", + }, + }, + RateLimit: timeliner.RateLimit{ + RequestsPerHour: 200, + BurstSize: 3, + }, + NewClient: func(acc timeliner.Account) (timeliner.Client, error) { + httpClient, err := acc.NewHTTPClient() + if err != nil { + return nil, err + } + return &Client{ + httpClient: httpClient, + checkpoint: checkpointInfo{mu: new(sync.Mutex)}, + }, nil + }, +} + +func init() { + err := timeliner.RegisterDataSource(dataSource) + if err != nil { + log.Fatal(err) + } +} + +// Client implements the timeliner.Client interface. +type Client struct { + httpClient *http.Client + checkpoint checkpointInfo +} + +// ListItems lists the items on the Facebook account. +func (c *Client) ListItems(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, opt timeliner.Options) error { + defer close(itemChan) + + if opt.Filename != "" { + return fmt.Errorf("importing from a file is not supported") + } + + // load any previous checkpoint + c.checkpoint.load(opt.Checkpoint) + + errChan := make(chan error) + + // TODO: events, comments (if possible), ... + go func() { + err := c.getFeed(ctx, itemChan, opt.Timeframe) + errChan <- err + }() + go func() { + err := c.getCollections(ctx, itemChan, opt.Timeframe) + errChan <- err + }() + + // read exactly 2 errors (or nils) because we + // started 2 goroutines to do things + var errs []string + for i := 0; i < 2; i++ { + err := <-errChan + if err != nil { + errs = append(errs, err.Error()) + } + } + if len(errs) > 0 { + return fmt.Errorf("one or more errors: %s", strings.Join(errs, ", ")) + } + + return nil +} + +func (c *Client) getFeed(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, timeframe timeliner.Timeframe) error { + c.checkpoint.mu.Lock() + nextPageURL := c.checkpoint.ItemsNextPage + c.checkpoint.mu.Unlock() + + var err error + + for { + select { + case <-ctx.Done(): + return nil + default: + nextPageURL, err = c.getFeedNextPage(itemChan, nextPageURL, timeframe) + if err != nil { + return err + } + if nextPageURL == nil { + return nil + } + + c.checkpoint.mu.Lock() + c.checkpoint.ItemsNextPage = nextPageURL + c.checkpoint.save(ctx) + c.checkpoint.mu.Unlock() + } + } +} + +func (c *Client) getFeedNextPage(itemChan chan<- *timeliner.ItemGraph, + nextPageURL *string, timeframe timeliner.Timeframe) (*string, error) { + + nextPageURLStr := "" + if nextPageURL != nil { + nextPageURLStr = *nextPageURL + } + + // TODO: When requesting a page using since&until, the results + // need to be ordered differently because they start at the since, + // and if we go "next" it goes the wrong direction; furthermore, + // their "order" method is broken: https://developers.facebook.com/support/bugs/2231843933505877/ + // - that all needs to be figured out before we do much more here + // with regards to timeframes + user, err := c.requestPage(nextPageURLStr, timeframe) + if err != nil { + return nil, fmt.Errorf("requesting next page: %v", err) + } + + // TODO: Refactor this into smaller functions... + + for _, post := range user.Feed.Data { + + ig := timeliner.NewItemGraph(post) + + for _, att := range post.Attachments.Data { + if att.Type == "album" { + + // add all the items to a collection + coll := timeliner.Collection{ + OriginalID: att.Target.ID, + Name: &att.Title, + } + + for i, subatt := range att.Subattachments.Data { + mediaID := subatt.Target.ID + + media, err := c.requestMedia(subatt.Type, mediaID) + if err != nil { + log.Printf("[ERROR] Getting media: %v", err) + continue + } + + coll.Items = append(coll.Items, timeliner.CollectionItem{ + Position: i, + Item: media, + }) + + ig.Add(media, timeliner.RelAttached) + } + + ig.Collections = append(ig.Collections, coll) + } + } + + itemChan <- ig + } + + return user.Feed.Paging.Next, nil +} + +func (c *Client) requestPage(nextPageURL string, timeframe timeliner.Timeframe) (fbUser, error) { + timeConstraint := fieldTimeConstraint(timeframe) + nested := "{attachments,backdated_time,created_time,description,from,link,message,name,parent_id,place,status_type,type,with_tags}" + + v := url.Values{ + "fields": {"feed" + timeConstraint + nested}, + "order": {"reverse_chronological"}, // TODO: see https://developers.facebook.com/support/bugs/2231843933505877/ (thankfully, reverse_chronological is their default for feed) + } + + var user fbUser + err := c.apiRequest("GET", "me?"+v.Encode(), nil, &user) + return user, err +} + +func (c *Client) requestMedia(mediaType, mediaID string) (*fbMedia, error) { + if mediaType != "photo" && mediaType != "video" { + return nil, fmt.Errorf("unknown media type: %s", mediaType) + } + + fields := []string{"backdated_time", "created_time", "from", "id", "place", "updated_time"} + switch mediaType { + case "photo": + fields = append(fields, "album", "images", "name", "name_tags") + case "video": + fields = append(fields, "description", "length", "source", "status", "title") + } + + vals := url.Values{ + "fields": {strings.Join(fields, ",")}, + } + endpoint := fmt.Sprintf("%s?%s", mediaID, vals.Encode()) + + var media fbMedia + err := c.apiRequest("GET", endpoint, nil, &media) + if err != nil { + return nil, err + } + media.fillFields(mediaType) + + return &media, nil +} + +func (c *Client) getCollections(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, timeframe timeliner.Timeframe) error { + c.checkpoint.mu.Lock() + nextPageURL := c.checkpoint.AlbumsNextPage + c.checkpoint.mu.Unlock() + + var err error + for { + select { + case <-ctx.Done(): + return nil + default: + nextPageURL, err = c.getCollectionsNextPage(itemChan, nextPageURL, timeframe) + if err != nil { + return err + } + if nextPageURL == nil { + return nil + } + + c.checkpoint.mu.Lock() + c.checkpoint.AlbumsNextPage = nextPageURL + c.checkpoint.save(ctx) + c.checkpoint.mu.Unlock() + } + } +} + +func (c *Client) getCollectionsNextPage(itemChan chan<- *timeliner.ItemGraph, + nextPageURL *string, timeframe timeliner.Timeframe) (*string, error) { + + var page fbMediaPage + var err error + if nextPageURL == nil { + // get first page + timeConstraint := fieldTimeConstraint(timeframe) + v := url.Values{ + "fields": {"created_time,id,name,photos" + timeConstraint + "{album,backdated_time,created_time,from,id,images,updated_time,place,source}"}, + } + v = qsTimeConstraint(v, timeframe) + endpoint := fmt.Sprintf("me/albums?%s", v.Encode()) + err = c.apiRequest("GET", endpoint, nil, &page) + } else { + // get subsequent pages + err = c.apiRequestFullURL("GET", *nextPageURL, nil, &page) + } + if err != nil { + return nil, fmt.Errorf("requesting next page: %v", err) + } + nextPageURL = page.Paging.Next + + // iterate each album on this page + for _, album := range page.Data { + // make the collection object + var coll timeliner.Collection + coll.Name = &album.Name + coll.OriginalID = album.MediaID + + // TODO... + log.Println("ALBUM NAME:", *coll.Name) + + // add each photo to the collection, page by page + if album.Photos != nil { + var counter int + + for { + log.Println("**** NEXT PAGE ****") + for i := range album.Photos.Data { + album.Photos.Data[i].fillFields("photo") + log.Println("PHOTO:", album.Photos.Data[i].MediaID) + + coll.Items = append(coll.Items, timeliner.CollectionItem{ + Item: &album.Photos.Data[i], + Position: counter, + }) + counter++ + } + + log.Println("ALBUM LEN:", len(coll.Items), *coll.Name) + + ig := timeliner.NewItemGraph(nil) + ig.Collections = append(ig.Collections, coll) + itemChan <- ig + coll.Items = []timeliner.CollectionItem{} + + if album.Photos.Paging.Next == nil { + break + } + + log.Println("PHOTOS NEXT:", *album.Photos.Paging.Next) + + // request next page + var nextPage *fbMediaPage + err := c.apiRequestFullURL("GET", *album.Photos.Paging.Next, nil, &nextPage) + if err != nil { + return nil, fmt.Errorf("requesting next page of photos in album: %v", err) + } + album.Photos = nextPage + } + } + + } + + return page.Paging.Next, nil +} + +func (c *Client) apiRequest(method, endpoint string, reqBodyData, respInto interface{}) error { + return c.apiRequestFullURL(method, apiBase+endpoint, reqBodyData, respInto) +} + +func (c *Client) apiRequestFullURL(method, fullURL string, reqBodyData, respInto interface{}) error { + var reqBody io.Reader + if reqBodyData != nil { + reqBodyBytes, err := json.Marshal(reqBodyData) + if err != nil { + return err + } + reqBody = bytes.NewReader(reqBodyBytes) + } + log.Println(fullURL) + + req, err := http.NewRequest(method, fullURL, reqBody) + if err != nil { + return err + } + if reqBody != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return fmt.Errorf("performing API request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status) + } + + err = json.NewDecoder(resp.Body).Decode(&respInto) + if err != nil { + return fmt.Errorf("decoding JSON: %v", err) + } + + return nil +} + +// NOTE: for these timeConstraint functions... Facebook docs recommend either setting +// BOTH since and until or NEITHER "for consistent results" (but seems to work with +// just one anyways...?) +// see https://developers.facebook.com/docs/graph-api/using-graph-api#time +func fieldTimeConstraint(timeframe timeliner.Timeframe) string { + var s string + if timeframe.Since != nil { + s += fmt.Sprintf(".since(%d)", timeframe.Since.Unix()) + } + if timeframe.Until != nil { + s += fmt.Sprintf(".until(%d)", timeframe.Until.Unix()) + } + return s +} +func qsTimeConstraint(v url.Values, timeframe timeliner.Timeframe) url.Values { + if timeframe.Since != nil { + v.Set("since", fmt.Sprintf("%d", timeframe.Since.Unix())) + } + if timeframe.Until != nil { + v.Set("until", fmt.Sprintf("%d", timeframe.Until.Unix())) + } + return v +} + +type checkpointInfo struct { + ItemsNextPage *string + AlbumsNextPage *string + mu *sync.Mutex +} + +// save records the checkpoint. It is NOT thread-safe, +// so calls to this must be protected by a mutex. +func (ch *checkpointInfo) save(ctx context.Context) { + gobBytes, err := timeliner.MarshalGob(ch) + if err != nil { + log.Printf("[ERROR][%s] Encoding checkpoint: %v", DataSourceID, err) + } + timeliner.Checkpoint(ctx, gobBytes) +} + +// save records the checkpoint. It is NOT thread-safe, +// so calls to this must be protected by a mutex. +func (ch *checkpointInfo) load(checkpointGob []byte) { + if len(checkpointGob) == 0 { + return + } + err := timeliner.UnmarshalGob(checkpointGob, ch) + if err != nil { + log.Printf("[ERROR][%s] Decoding checkpoint: %v", DataSourceID, err) + } +} + +type fbUser struct { + Feed fbUserFeed `json:"feed"` + ID string `json:"id"` +} + +type fbUserFeed struct { + Data []fbPost `json:"data"` + Paging fbPaging `json:"paging"` +} + +type fbPaging struct { + Previous *string `json:"previous"` + Next *string `json:"next"` + Cursors *fbCursors `json:"cursors,omitempty"` +} + +type fbCursors struct { + Before string `json:"before,omitempty"` + After string `json:"after,omitempty"` +} + +type fbFrom struct { + Name string `json:"name,omitempty"` + ID string `json:"id,omitempty"` +} + +type fbPlace struct { + Name string `json:"name,omitempty"` + Location fbLocation `json:"location,omitempty"` + ID string `json:"id,omitempty"` +} + +type fbLocation struct { + City string `json:"city,omitempty"` + Country string `json:"country,omitempty"` + Latitude float64 `json:"latitude,omitempty"` + LocatedIn string `json:"located_in,omitempty"` + Longitude float64 `json:"longitude,omitempty"` + Name string `json:"name,omitempty"` + Region string `json:"region,omitempty"` + State string `json:"state,omitempty"` + Street string `json:"street,omitempty"` + Zip string `json:"zip,omitempty"` +} + +const apiBase = "https://graph.facebook.com/v3.2/" diff --git a/datasources/facebook/media.go b/datasources/facebook/media.go new file mode 100644 index 0000000..503f1e1 --- /dev/null +++ b/datasources/facebook/media.go @@ -0,0 +1,184 @@ +package facebook + +import ( + "fmt" + "io" + "log" + "mime" + "net/http" + "net/url" + "path" + "time" + + "github.com/mholt/timeliner" +) + +type fbMediaPage struct { + Data []fbMedia `json:"data"` + Paging fbPaging `json:"paging"` +} + +// fbMedia is used for videos, photos, and albums. +type fbMedia struct { + Album fbAlbum `json:"album,omitempty"` + BackdatedTime string `json:"backdated_time,omitempty"` + CreatedTime string `json:"created_time,omitempty"` + From fbFrom `json:"from,omitempty"` + Images []fbImage `json:"images,omitempty"` + UpdatedTime string `json:"updated_time,omitempty"` + Description string `json:"description,omitempty"` + Length float64 `json:"length,omitempty"` // in seconds + Message string `json:"message,omitempty"` + Name string `json:"name,omitempty"` + Place *fbPlace `json:"place,omitempty"` + Photos *fbMediaPage `json:"photos,omitempty"` + Source string `json:"source,omitempty"` + Status fbVideoStatus `json:"status,omitempty"` + MediaID string `json:"id,omitempty"` + + // these fields added by us and used internally + mediaType string + bestSourceURL string + bestSourceFilename string + exifData map[string]interface{} +} + +func (m *fbMedia) fillFields(mediaType string) { + m.mediaType = mediaType + + // get URL to actual media content; we'll need + // it later, and by doing this now, we only have + // to do it once + switch mediaType { + case "photo": + _, _, m.bestSourceURL = m.getLargestImage() + case "video": + m.bestSourceURL = m.Source + } + if m.bestSourceURL != "" { + sourceURL, err := url.Parse(m.bestSourceURL) + if err != nil { + // TODO: What to return in this case? return the error? + log.Printf("[ERROR] Parsing media source URL to get filename: %v", err) + } + m.bestSourceFilename = path.Base(sourceURL.Path) + } +} + +func (m *fbMedia) ID() string { + return m.MediaID +} + +func (m *fbMedia) Timestamp() time.Time { + if m.BackdatedTime != "" { + return fbTimeToGoTime(m.BackdatedTime) + } + return fbTimeToGoTime(m.CreatedTime) +} + +func (m *fbMedia) DataText() (*string, error) { + if m.Description != "" { + return &m.Description, nil + } + if m.Name != "" { + return &m.Name, nil + } + return nil, nil +} + +func (m *fbMedia) DataFileName() *string { + if m.bestSourceFilename != "" { + return &m.bestSourceFilename + } + return nil +} + +func (m *fbMedia) DataFileHash() []byte { + return nil +} + +func (m *fbMedia) DataFileReader() (io.ReadCloser, error) { + if m.bestSourceURL == "" { + return nil, fmt.Errorf("no way to get data file: no best source URL") + } + + resp, err := http.Get(m.bestSourceURL) + if err != nil { + return nil, fmt.Errorf("getting media contents: %v", err) + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status) + } + + return resp.Body, nil +} + +func (m *fbMedia) DataFileMIMEType() *string { + fmt.Println("BEST SOURCE FILENAME:", m.bestSourceFilename) + mt := mime.TypeByExtension(path.Ext(m.bestSourceFilename)) + if mt != "" { + return &mt + } + return nil +} + +func (m *fbMedia) Owner() (*string, *string) { + return &m.From.ID, &m.From.Name +} + +func (m *fbMedia) Class() timeliner.ItemClass { + switch m.mediaType { + case "photo": + return timeliner.ClassImage + case "video": + return timeliner.ClassVideo + } + return timeliner.ClassUnknown +} + +func (m *fbMedia) Metadata() (*timeliner.Metadata, error) { + // TODO + return nil, nil +} + +func (m *fbMedia) getLargestImage() (height, width int, source string) { + var largest int + for _, im := range m.Images { + size := im.Height * im.Width + if size > largest { + source = im.Source + height = im.Height + width = im.Width + largest = size + } + } + return +} + +func (m *fbMedia) Location() (*timeliner.Location, error) { + if m.Place != nil { + return &timeliner.Location{ + Latitude: &m.Place.Location.Latitude, + Longitude: &m.Place.Location.Longitude, + }, nil + } + return nil, nil +} + +type fbVideoStatus struct { + VideoStatus string `json:"video_status,omitempty"` +} + +type fbAlbum struct { + CreatedTime string `json:"created_time,omitempty"` + Name string `json:"name,omitempty"` + ID string `json:"id,omitempty"` + Photos []fbMediaPage `json:"photos,omitempty"` +} + +type fbImage struct { + Height int `json:"height,omitempty"` + Source string `json:"source,omitempty"` + Width int `json:"width,omitempty"` +} diff --git a/datasources/facebook/post.go b/datasources/facebook/post.go new file mode 100644 index 0000000..1bf0e6d --- /dev/null +++ b/datasources/facebook/post.go @@ -0,0 +1,127 @@ +package facebook + +import ( + "io" + "log" + "time" + + "github.com/mholt/timeliner" +) + +type fbPost struct { + Attachments fbPostAttachments `json:"attachments,omitempty"` + BackdatedTime string `json:"backdated_time,omitempty"` + CreatedTime string `json:"created_time,omitempty"` // example format: "2018-12-22T19:10:30+0000" + From fbFrom `json:"from,omitempty"` + Link string `json:"link,omitempty"` + Description string `json:"description,omitempty"` + Message string `json:"message,omitempty"` + Name string `json:"name,omitempty"` + ParentID string `json:"parent_id,omitempty"` + Place *fbPlace `json:"place,omitempty"` + StatusType string `json:"status_type,omitempty"` + Type string `json:"type,omitempty"` + PostID string `json:"id,omitempty"` +} + +func (p fbPost) ID() string { + return p.PostID +} + +func (p fbPost) Timestamp() time.Time { + if p.BackdatedTime != "" { + return fbTimeToGoTime(p.BackdatedTime) + } + return fbTimeToGoTime(p.CreatedTime) +} + +func (p fbPost) DataText() (*string, error) { + return &p.Message, nil +} + +func (p fbPost) DataFileName() *string { + return nil +} + +func (p fbPost) DataFileReader() (io.ReadCloser, error) { + return nil, nil +} + +func (p fbPost) DataFileHash() []byte { + return nil +} + +func (p fbPost) DataFileMIMEType() *string { + return nil +} + +func (p fbPost) Owner() (*string, *string) { + return &p.From.ID, &p.From.Name +} + +func (p fbPost) Class() timeliner.ItemClass { + return timeliner.ClassPost +} + +func (p fbPost) Metadata() (*timeliner.Metadata, error) { + return &timeliner.Metadata{ + Link: p.Link, + Description: p.Description, + Name: p.Name, + ParentID: p.ParentID, + StatusType: p.StatusType, + Type: p.Type, + }, nil +} + +func (p fbPost) Location() (*timeliner.Location, error) { + if p.Place != nil { + return &timeliner.Location{ + Latitude: &p.Place.Location.Latitude, + Longitude: &p.Place.Location.Longitude, + }, nil + } + return nil, nil +} + +type fbPostAttachments struct { + Data []fbPostAttachmentData `json:"data"` +} + +type fbPostAttachmentData struct { + Media fbPostAttachmentMedia `json:"media,omitempty"` + Target fbPostAttachmentTarget `json:"target,omitempty"` + Subattachments fbPostAttachments `json:"subattachments,omitempty"` + Title string `json:"title,omitempty"` + Type string `json:"type,omitempty"` + URL string `json:"url,omitempty"` +} + +type fbPostAttachmentMedia struct { + Image fbPostAttachmentImage `json:"image,omitempty"` +} + +type fbPostAttachmentImage struct { + Height int `json:"height,omitempty"` + Src string `json:"src,omitempty"` + Width int `json:"width,omitempty"` +} + +type fbPostAttachmentTarget struct { + ID string `json:"id,omitempty"` + URL string `json:"url,omitempty"` +} + +func fbTimeToGoTime(fbTime string) time.Time { + if fbTime == "" { + return time.Time{} + } + ts, err := time.Parse(fbTimeFormat, fbTime) + if err != nil { + log.Printf("[ERROR] Parsing timestamp from Facebook: '%s' is not in '%s' format", + fbTime, fbTimeFormat) + } + return ts +} + +const fbTimeFormat = "2006-01-02T15:04:05+0000" diff --git a/datasources/googlelocation/googlelocation.go b/datasources/googlelocation/googlelocation.go new file mode 100644 index 0000000..8233807 --- /dev/null +++ b/datasources/googlelocation/googlelocation.go @@ -0,0 +1,338 @@ +// Package googlelocation implements a Timeliner data source for +// importing data from the Google Location History (aka Google +// Maps Timeline). +package googlelocation + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log" + "os" + "sort" + "strconv" + "strings" + "time" + + "github.com/mholt/timeliner" +) + +// Data source name and ID +const ( + DataSourceName = "Google Location History" + DataSourceID = "google_location" +) + +var dataSource = timeliner.DataSource{ + ID: DataSourceID, + Name: DataSourceName, + NewClient: func(acc timeliner.Account) (timeliner.Client, error) { + return new(Client), nil + }, +} + +func init() { + err := timeliner.RegisterDataSource(dataSource) + if err != nil { + log.Fatal(err) + } +} + +// Client implements the timeliner.Client interface. +type Client struct{} + +// ListItems lists items from the data source. opt.Filename must be non-empty. +func (c *Client) ListItems(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, opt timeliner.Options) error { + defer close(itemChan) + + if opt.Filename == "" { + return fmt.Errorf("filename is required") + } + + file, err := os.Open(opt.Filename) + if err != nil { + return fmt.Errorf("opening data file: %v", err) + } + defer file.Close() + + dec := json.NewDecoder(file) + + // read the following opening tokens: + // 1. open brace '{' + // 2. "locations" field name, + // 3. the array value's opening bracket '[' + for i := 0; i < 3; i++ { + _, err := dec.Token() + if err != nil { + return fmt.Errorf("decoding opening token: %v", err) + } + } + + var prev *location + for dec.More() { + select { + case <-ctx.Done(): + return nil + default: + var err error + prev, err = c.processLocation(dec, prev, itemChan) + if err != nil { + return fmt.Errorf("processing location item: %v", err) + } + } + } + + return nil +} + +func (c *Client) processLocation(dec *json.Decoder, prev *location, + itemChan chan<- *timeliner.ItemGraph) (*location, error) { + + var l *location + err := dec.Decode(&l) + if err != nil { + return nil, fmt.Errorf("decoding location element: %v", err) + } + + // redundancy checks (lots of data points are very similar) + if prev != nil { + // if the timestamp of this location is the same + // as the previous one, it seems useless to keep + // both, so skip this one (also, we produce IDs + // based on timestamp, which must be unique -- + // hence why we compare the unix timestamp values) + if l.Timestamp().Unix() == prev.Timestamp().Unix() { + return l, nil + } + + // if this location is basically the same spot as the + // previously-seen one, and if we're sure that the + // timestamps are in order, skip it; mostly redundant + if locationsSimilar(l, prev) && l.Timestamp().Before(prev.Timestamp()) { + return l, nil + } + } + + // store this item, and possibly connect it to the + // previous one if there's a movement activity + ig := timeliner.NewItemGraph(l) + if movement := l.primaryMovement(); movement != "" && prev != nil { + // bidirectional edge, because you may want to know how you got somewhere, + // and the timestamps should make it obvious which location is the "from" + // or the "to", since you can't go backwards in time (that we know of...) + ig.Add(prev, timeliner.Relation{ + Label: strings.ToLower(movement), + Bidirectional: true, + }) + } + itemChan <- ig + + return l, nil +} + +func locationsSimilar(a, b *location) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + return similar(a.LatitudeE7, b.LatitudeE7) && + similar(a.LongitudeE7, b.LongitudeE7) +} + +func similar(a, b int) bool { + const tolerance = 1000 + if a > b { + return a-b < tolerance + } + return b-a < tolerance +} + +type location struct { + TimestampMs string `json:"timestampMs"` + LatitudeE7 int `json:"latitudeE7"` + LongitudeE7 int `json:"longitudeE7"` + Accuracy int `json:"accuracy"` + Altitude int `json:"altitude,omitempty"` + VerticalAccuracy int `json:"verticalAccuracy,omitempty"` + Activity []activities `json:"activity,omitempty"` + Velocity int `json:"velocity,omitempty"` + Heading int `json:"heading,omitempty"` +} + +func (l location) primaryMovement() string { + if len(l.Activity) == 0 { + return "" + } + + counts := make(map[string]int) + confidences := make(map[string]int) + for _, a := range l.Activity { + for _, aa := range a.Activity { + counts[aa.Type]++ + confidences[aa.Type] += aa.Confidence + } + } + + // turn confidence into average confidence, + // (ensure all activities are represented), + // and keep activities with high enough score + var top []activity + var hasOnFoot, hasWalking, hasRunning bool + for _, a := range movementActivities { + count := counts[a] + if count == 0 { + count = 1 // for the purposes of division + } + avg := confidences[a] / len(l.Activity) + avgSeen := confidences[a] / count + if avgSeen > 50 { + switch a { + case "ON_FOOT": + hasOnFoot = true + case "WALKING": + hasWalking = true + case "RUNNING": + hasRunning = true + } + top = append(top, activity{Type: a, Confidence: avg}) + } + } + sort.Slice(top, func(i, j int) bool { + return top[i].Confidence > top[j].Confidence + }) + + // consolidate ON_FOOT, WALKING, and RUNNING if more than one is present + if hasOnFoot && (hasWalking || hasRunning) { + for i := 0; i < len(top); i++ { + if hasWalking && hasRunning && + (top[i].Type == "WALKING" || top[i].Type == "RUNNING") { + // if both WALKING and RUNNING, prefer more general ON_FOOT + top = append(top[:i], top[i+1:]...) + } else if top[i].Type == "ON_FOOT" { + // if only one of WALKING or RUNNING, prefer that over ON_FOOT + top = append(top[:i], top[i+1:]...) + } + } + } + + if len(top) > 0 { + return top[0].Type + } + return "" +} + +func (l location) hasActivity(act string) bool { + for _, a := range l.Activity { + for _, aa := range a.Activity { + if aa.Type == act && aa.Confidence > 50 { + return true + } + } + } + return false +} + +type activities struct { + TimestampMs string `json:"timestampMs"` + Activity []activity `json:"activity"` +} + +type activity struct { + Type string `json:"type"` + Confidence int `json:"confidence"` +} + +// ID returns a string representation of the timestamp, +// since there is no actual ID provided by the service. +// It is assumed that one cannot be in two places at once. +func (l location) ID() string { + ts := fmt.Sprintf("loc_%d", l.Timestamp().Unix()) + return ts +} + +func (l location) Timestamp() time.Time { + ts, err := strconv.Atoi(l.TimestampMs) + if err != nil { + return time.Time{} + } + return time.Unix(int64(ts)/1000, 0) +} + +func (l location) Owner() (*string, *string) { + return nil, nil +} + +func (l location) Class() timeliner.ItemClass { + return timeliner.ClassLocation +} + +func (l location) DataText() (*string, error) { + return nil, nil +} + +func (l location) DataFileName() *string { + return nil +} + +func (l location) DataFileReader() (io.ReadCloser, error) { + return nil, nil +} + +func (l location) DataFileHash() []byte { + return nil +} + +func (l location) DataFileMIMEType() *string { + return nil +} + +func (l location) Metadata() (*timeliner.Metadata, error) { + var m timeliner.Metadata + var hasMetadata bool + + if l.Velocity > 0 { + m.Velocity = l.Velocity + hasMetadata = true + } + if l.Heading > 0 { + m.Heading = l.Heading + hasMetadata = true + } + if l.Altitude > 0 { + m.Altitude = l.Altitude + m.AltitudeAccuracy = l.VerticalAccuracy + hasMetadata = true + } + + if hasMetadata { + return &m, nil + } + return nil, nil +} + +func (l location) Location() (*timeliner.Location, error) { + lat := float64(l.LatitudeE7) / 1e7 + lon := float64(l.LongitudeE7) / 1e7 + return &timeliner.Location{ + Latitude: &lat, + Longitude: &lon, + }, nil +} + +// movementActivities is the list of activities we care about +// for drawing relationships between two locations. For example, +// we don't care about TILTING (sudden accelerometer adjustment, +// like phone set down or person standing up), UNKNOWN, or STILL +// (where there is no apparent movement detected). +// +// https://developers.google.com/android/reference/com/google/android/gms/location/DetectedActivity +var movementActivities = []string{ + "WALKING", + "RUNNING", + "IN_VEHICLE", + "ON_FOOT", + "ON_BICYCLE", +} diff --git a/datasources/googlephotos/googlephotos.go b/datasources/googlephotos/googlephotos.go new file mode 100644 index 0000000..50f9a84 --- /dev/null +++ b/datasources/googlephotos/googlephotos.go @@ -0,0 +1,396 @@ +// Package googlephotos implements the Google Photos service +// using its API, documented at https://developers.google.com/photos/. +package googlephotos + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "github.com/mholt/timeliner" +) + +// Data source name and ID. +const ( + DataSourceName = "Google Photos" + DataSourceID = "google_photos" + + apiBase = "https://photoslibrary.googleapis.com/v1" +) + +var dataSource = timeliner.DataSource{ + ID: DataSourceID, + Name: DataSourceID, + OAuth2: timeliner.OAuth2{ + ProviderID: "google", + Scopes: []string{"https://www.googleapis.com/auth/photoslibrary.readonly"}, + }, + RateLimit: timeliner.RateLimit{ + RequestsPerHour: 10000 / 24, // https://developers.google.com/photos/library/guides/api-limits-quotas + BurstSize: 3, + }, + NewClient: func(acc timeliner.Account) (timeliner.Client, error) { + httpClient, err := acc.NewHTTPClient() + if err != nil { + return nil, err + } + return &Client{ + HTTPClient: httpClient, + userID: acc.UserID, + checkpoint: checkpointInfo{mu: new(sync.Mutex)}, + }, nil + }, +} + +func init() { + err := timeliner.RegisterDataSource(dataSource) + if err != nil { + log.Fatal(err) + } +} + +// Client interacts with the Google Photos +// API. It requires an OAuth2-authorized +// HTTP client in order to work properly. +type Client struct { + HTTPClient *http.Client + + userID string + checkpoint checkpointInfo +} + +// ListItems lists items from the data source. +// opt.Timeframe precision is day-level at best. +func (c *Client) ListItems(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, opt timeliner.Options) error { + defer close(itemChan) + + if opt.Filename != "" { + return fmt.Errorf("importing data from a file is not supported") + } + + // load any previous checkpoint + c.checkpoint.load(opt.Checkpoint) + + // get items and collections + errChan := make(chan error) + go func() { + err := c.listItems(ctx, itemChan, opt.Timeframe) + errChan <- err + }() + go func() { + err := c.listCollections(ctx, itemChan, opt.Timeframe) + errChan <- err + }() + + // read exactly 2 error (or nil) values to ensure we + // block precisely until the two listers are done + var errs []string + for i := 0; i < 2; i++ { + err := <-errChan + if err != nil { + log.Printf("[ERROR][%s/%s] A listing goroutine errored: %v", DataSourceID, c.userID, err) + errs = append(errs, err.Error()) + } + } + if len(errs) > 0 { + return fmt.Errorf("one or more errors: %s", strings.Join(errs, ", ")) + } + + return nil +} + +func (c *Client) listItems(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, + timeframe timeliner.Timeframe) error { + c.checkpoint.mu.Lock() + pageToken := c.checkpoint.ItemsNextPage + c.checkpoint.mu.Unlock() + + for { + select { + case <-ctx.Done(): + return nil + default: + var err error + pageToken, err = c.getItemsNextPage(itemChan, pageToken, timeframe) + if err != nil { + return fmt.Errorf("getting items on next page: %v", err) + } + if pageToken == "" { + return nil + } + + c.checkpoint.mu.Lock() + c.checkpoint.ItemsNextPage = pageToken + c.checkpoint.save(ctx) + c.checkpoint.mu.Unlock() + } + } +} + +func (c *Client) getItemsNextPage(itemChan chan<- *timeliner.ItemGraph, + pageToken string, timeframe timeliner.Timeframe) (string, error) { + reqBody := listMediaItemsRequest{ + PageSize: 100, + PageToken: pageToken, + } + if timeframe.Since != nil || timeframe.Until != nil { + reqBody.Filters = &listMediaItemsFilter{ + DateFilter: listMediaItemsDateFilter{ + Ranges: []listMediaItemsFilterRange{dateRange(timeframe)}, + }, + } + } + + page, err := c.pageOfMediaItems(reqBody) + if err != nil { + return "", fmt.Errorf("requesting next page: %v", err) + } + + for _, item := range page.MediaItems { + itemChan <- &timeliner.ItemGraph{ + Node: item, + } + } + + return page.NextPageToken, nil +} + +// listCollections lists media items by iterating each album. As +// of Jan. 2019, the Google Photos API does not allow searching +// media items with both an album ID and filters. Because this +// search is predicated on album ID, we cannot be constrained by +// a timeframe in this search. +// +// See https://developers.google.com/photos/library/reference/rest/v1/mediaItems/search. +func (c *Client) listCollections(ctx context.Context, + itemChan chan<- *timeliner.ItemGraph, timeframe timeliner.Timeframe) error { + c.checkpoint.mu.Lock() + albumPageToken := c.checkpoint.AlbumsNextPage + c.checkpoint.mu.Unlock() + + for { + select { + case <-ctx.Done(): + return nil + default: + var err error + albumPageToken, err = c.getAlbumsAndTheirItemsNextPage(itemChan, albumPageToken, timeframe) + if err != nil { + return err + } + if albumPageToken == "" { + return nil + } + + c.checkpoint.mu.Lock() + c.checkpoint.AlbumsNextPage = albumPageToken + c.checkpoint.save(ctx) + c.checkpoint.mu.Unlock() + } + } +} + +func (c *Client) getAlbumsAndTheirItemsNextPage(itemChan chan<- *timeliner.ItemGraph, + pageToken string, timeframe timeliner.Timeframe) (string, error) { + vals := url.Values{ + "pageToken": {pageToken}, + "pageSize": {"50"}, + } + + var respBody listAlbums + err := c.apiRequest("GET", "/albums?"+vals.Encode(), nil, &respBody) + if err != nil { + return pageToken, err + } + + for _, album := range respBody.Albums { + err = c.getAlbumItems(itemChan, album, timeframe) + if err != nil { + return "", err + } + } + + return respBody.NextPageToken, nil +} + +func (c *Client) getAlbumItems(itemChan chan<- *timeliner.ItemGraph, album gpAlbum, timeframe timeliner.Timeframe) error { + var albumItemsNextPage string + var counter int + + for { + reqBody := listMediaItemsRequest{ + AlbumID: album.ID, + PageToken: albumItemsNextPage, + PageSize: 100, + } + + page, err := c.pageOfMediaItems(reqBody) + if err != nil { + return fmt.Errorf("listing album contents: %v", err) + } + + // iterate each media item on this page of the album listing + var items []timeliner.CollectionItem + for _, it := range page.MediaItems { + // since we cannot request items in an album and also filter + // by timestamp, be sure to filter here; it means we still + // have to iterate all items in all albums, but at least we + // can just skip items that fall outside the timeframe... + ts := it.Timestamp() + if timeframe.Since != nil && ts.Before(*timeframe.Since) { + continue + } + if timeframe.Until != nil && ts.After(*timeframe.Until) { + continue + } + + // otherwise, add this item to the album + items = append(items, timeliner.CollectionItem{ + Item: it, + Position: counter, + }) + counter++ + } + + // if any items remained after filtering, + // process this album now + if len(items) > 0 { + ig := timeliner.NewItemGraph(nil) + ig.Collections = append(ig.Collections, timeliner.Collection{ + OriginalID: album.ID, + Name: &album.Title, + Items: items, + }) + itemChan <- ig + } + + if page.NextPageToken == "" { + return nil + } + + albumItemsNextPage = page.NextPageToken + } +} + +func (c *Client) pageOfMediaItems(reqBody listMediaItemsRequest) (listMediaItems, error) { + var respBody listMediaItems + err := c.apiRequest("POST", "/mediaItems:search", reqBody, &respBody) + return respBody, err +} + +func (c *Client) apiRequest(method, endpoint string, reqBodyData, respInto interface{}) error { + var reqBody io.Reader + if reqBodyData != nil { + reqBodyBytes, err := json.Marshal(reqBodyData) + if err != nil { + return err + } + reqBody = bytes.NewReader(reqBodyBytes) + } + + req, err := http.NewRequest(method, apiBase+endpoint, reqBody) + if err != nil { + return err + } + if reqBody != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return fmt.Errorf("performing search request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + bodyText, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024*256)) + if err == nil { + return fmt.Errorf("HTTP %d: %s: %s", resp.StatusCode, resp.Status, bodyText) + } + return fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status) + } + + err = json.NewDecoder(resp.Body).Decode(&respInto) + if err != nil { + return fmt.Errorf("decoding JSON: %v", err) + } + + return nil +} + +func dateRange(timeframe timeliner.Timeframe) listMediaItemsFilterRange { + var start, end filterDate + if timeframe.Since == nil { + start = filterDate{ + Day: 1, + Month: 1, + Year: 1, + } + } else { + since := timeframe.Since.Add(24 * time.Hour) // to account for day precision + start = filterDate{ + Day: since.Day(), + Month: int(since.Month()), + Year: since.Year(), + } + } + if timeframe.Until == nil { + end = filterDate{ + Day: 31, + Month: 12, + Year: 9999, + } + } else { + timeframe.Until.Add(-24 * time.Hour) // to account for day precision + end = filterDate{ + Day: timeframe.Until.Day(), + Month: int(timeframe.Until.Month()), + Year: timeframe.Until.Year(), + } + } + return listMediaItemsFilterRange{ + StartDate: start, + EndDate: end, + } +} + +// Assuming checkpoints are short-lived (i.e. are resumed +// somewhat quickly, before the page tokens/cursors expire), +// we can just store the page tokens. +type checkpointInfo struct { + ItemsNextPage string + AlbumsNextPage string + mu *sync.Mutex +} + +// save records the checkpoint. It is NOT thread-safe, +// so calls to this must be protected by a mutex. +func (ch *checkpointInfo) save(ctx context.Context) { + log.Printf("CHECKPOINTING: %+v", ch) + gobBytes, err := timeliner.MarshalGob(ch) + if err != nil { + log.Printf("[ERROR][%s] Encoding checkpoint: %v", DataSourceID, err) + } + timeliner.Checkpoint(ctx, gobBytes) +} + +// save records the checkpoint. It is NOT thread-safe, +// so calls to this must be protected by a mutex. +func (ch *checkpointInfo) load(checkpointGob []byte) { + if len(checkpointGob) == 0 { + return + } + err := timeliner.UnmarshalGob(checkpointGob, ch) + if err != nil { + log.Printf("[ERROR][%s] Decoding checkpoint: %v", DataSourceID, err) + } +} diff --git a/datasources/googlephotos/media.go b/datasources/googlephotos/media.go new file mode 100644 index 0000000..e9110ee --- /dev/null +++ b/datasources/googlephotos/media.go @@ -0,0 +1,234 @@ +package googlephotos + +import ( + "fmt" + "io" + "log" + "net/http" + "strconv" + "time" + + "github.com/mholt/timeliner" +) + +// listMediaItems is the structure of the results +// of calling mediaItems in the Google Photos API. +type listMediaItems struct { + MediaItems []mediaItem `json:"mediaItems"` + NextPageToken string `json:"nextPageToken"` +} + +type mediaItem struct { + MediaID string `json:"id"` + ProductURL string `json:"productUrl"` + BaseURL string `json:"baseUrl"` + Description string `json:"description"` + MIMEType string `json:"mimeType"` + MediaMetadata mediaMetadata `json:"mediaMetadata"` + ContributorInfo mediaContributor `json:"mediaContributor"` + Filename string `json:"filename"` +} + +func (m mediaItem) ID() string { + return m.MediaID +} + +func (m mediaItem) Timestamp() time.Time { + return m.MediaMetadata.CreationTime +} + +func (m mediaItem) DataText() (*string, error) { + return &m.Description, nil +} + +func (m mediaItem) DataFileName() *string { + return &m.Filename +} + +func (m mediaItem) DataFileReader() (io.ReadCloser, error) { + if m.MediaMetadata.Video != nil && m.MediaMetadata.Video.Status != "READY" { + log.Printf("[INFO] Skipping video file because it is not ready (status=%s filename=%s)", + m.MediaMetadata.Video.Status, m.Filename) + return nil, nil + } + + u := m.BaseURL + + // configure for the download of full file with almost-full exif data; see + // https://developers.google.com/photos/library/guides/access-media-items#base-urls + if m.MediaMetadata.Photo != nil { + u += "=d" + } else if m.MediaMetadata.Video != nil { + u += "=dv" + } + + resp, err := http.Get(u) + if err != nil { + return nil, fmt.Errorf("getting media contents: %v", err) + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status) + } + + return resp.Body, nil +} + +func (m mediaItem) DataFileHash() []byte { + return nil +} + +func (m mediaItem) DataFileMIMEType() *string { + return &m.MIMEType +} + +func (m mediaItem) Owner() (*string, *string) { + // since we only download media owned by the account, + // we can leave ID nil and assume the display name + // is the account owner's name + if m.ContributorInfo.DisplayName != "" { + return nil, &m.ContributorInfo.DisplayName + } + return nil, nil +} + +func (m mediaItem) Class() timeliner.ItemClass { + if m.MediaMetadata.Video != nil { + return timeliner.ClassVideo + } + if m.MediaMetadata.Photo != nil { + return timeliner.ClassImage + } + return timeliner.ClassUnknown +} + +func (m mediaItem) Metadata() (*timeliner.Metadata, error) { + // TODO: Parse exif metadata... maybe add most important/useful + // EXIF fields to the metadata struct directly? + + widthInt, err := strconv.Atoi(m.MediaMetadata.Width) + if err != nil { + return nil, fmt.Errorf("parsing width as int: %v (width=%s)", + err, m.MediaMetadata.Width) + } + heightInt, err := strconv.Atoi(m.MediaMetadata.Height) + if err != nil { + return nil, fmt.Errorf("parsing height as int: %v (height=%s)", + err, m.MediaMetadata.Height) + } + + meta := &timeliner.Metadata{ + Width: widthInt, + Height: heightInt, + } + + if m.MediaMetadata.Photo != nil { + meta.CameraMake = m.MediaMetadata.Photo.CameraMake + meta.CameraModel = m.MediaMetadata.Photo.CameraModel + meta.FocalLength = m.MediaMetadata.Photo.FocalLength + meta.ApertureFNumber = m.MediaMetadata.Photo.ApertureFNumber + meta.ISOEquivalent = m.MediaMetadata.Photo.ISOEquivalent + if m.MediaMetadata.Photo.ExposureTime != "" { + expDur, err := time.ParseDuration(m.MediaMetadata.Photo.ExposureTime) + if err != nil { + return nil, fmt.Errorf("parsing exposure time as duration: %v (exposure_time=%s)", + err, m.MediaMetadata.Photo.ExposureTime) + } + meta.ExposureTime = expDur + } + } else if m.MediaMetadata.Video != nil { + meta.CameraMake = m.MediaMetadata.Video.CameraMake + meta.CameraModel = m.MediaMetadata.Video.CameraModel + meta.FPS = m.MediaMetadata.Video.FPS + } + + return meta, nil +} + +func (m mediaItem) Location() (*timeliner.Location, error) { + // See https://issuetracker.google.com/issues/80379228 😭 + return nil, nil +} + +type mediaMetadata struct { + CreationTime time.Time `json:"creationTime"` + Width string `json:"width"` + Height string `json:"height"` + Photo *photoMetadata `json:"photo,omitempty"` + Video *videoMetadata `json:"video,omitempty"` +} + +type photoMetadata struct { + CameraMake string `json:"cameraMake"` + CameraModel string `json:"cameraModel"` + FocalLength float64 `json:"focalLength"` + ApertureFNumber float64 `json:"apertureFNumber"` + ISOEquivalent int `json:"isoEquivalent"` + ExposureTime string `json:"exposureTime"` // TODO: Parse duration out of this...? +} + +type videoMetadata struct { + CameraMake string `json:"cameraMake"` + CameraModel string `json:"cameraModel"` + FPS float64 `json:"fps"` + Status string `json:"status"` +} + +type mediaContributor struct { + ProfilePictureBaseURL string `json:"profilePictureBaseUrl"` + DisplayName string `json:"displayName"` +} + +type listMediaItemsRequest struct { + Filters *listMediaItemsFilter `json:"filters,omitempty"` + AlbumID string `json:"albumId,omitempty"` + PageSize int `json:"pageSize,omitempty"` + PageToken string `json:"pageToken,omitempty"` +} + +type listMediaItemsFilter struct { + DateFilter listMediaItemsDateFilter `json:"dateFilter"` + IncludeArchivedMedia bool `json:"includeArchivedMedia"` + ExcludeNonAppCreatedData bool `json:"excludeNonAppCreatedData"` + ContentFilter listMediaItemsContentFilter `json:"contentFilter"` + MediaTypeFilter listMediaItemsMediaTypeFilter `json:"mediaTypeFilter"` +} + +type listMediaItemsDateFilter struct { + Ranges []listMediaItemsFilterRange `json:"ranges,omitempty"` + Dates []filterDate `json:"dates,omitempty"` +} + +type listMediaItemsFilterRange struct { + StartDate filterDate `json:"startDate"` + EndDate filterDate `json:"endDate"` +} + +type filterDate struct { + Month int `json:"month"` + Day int `json:"day"` + Year int `json:"year"` +} + +type listMediaItemsContentFilter struct { + ExcludedContentCategories []string `json:"excludedContentCategories,omitempty"` + IncludedContentCategories []string `json:"includedContentCategories,omitempty"` +} + +type listMediaItemsMediaTypeFilter struct { + MediaTypes []string `json:"mediaTypes,omitempty"` +} + +type listAlbums struct { + Albums []gpAlbum `json:"albums"` + NextPageToken string `json:"nextPageToken"` +} + +type gpAlbum struct { + ID string `json:"id"` + Title string `json:"title,omitempty"` + ProductURL string `json:"productUrl"` + MediaItemsCount string `json:"mediaItemsCount"` + CoverPhotoBaseURL string `json:"coverPhotoBaseUrl"` + CoverPhotoMediaItemID string `json:"coverPhotoMediaItemId"` +} diff --git a/datasources/twitter/models.go b/datasources/twitter/models.go new file mode 100644 index 0000000..09cd20b --- /dev/null +++ b/datasources/twitter/models.go @@ -0,0 +1,428 @@ +package twitter + +import ( + "fmt" + "io" + "net/url" + "path" + "strconv" + "strings" + "time" + + "github.com/mholt/timeliner" +) + +type tweet struct { + Retweeted bool `json:"retweeted"` // always false (at least, with the export file) + Source string `json:"source"` + Entities *tweetEntities `json:"entities,omitempty"` // DO NOT USE (https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/entities-object.html#media) + DisplayTextRange []string `json:"display_text_range"` + FavoriteCount string `json:"favorite_count"` + TweetIDStr string `json:"id_str"` + Truncated bool `json:"truncated"` + Geo *tweetGeo `json:"geo,omitempty"` // deprecated, see coordinates + Coordinates *tweetGeo `json:"coordinates,omitempty"` + RetweetCount string `json:"retweet_count"` + TweetID string `json:"id"` + InReplyToStatusID string `json:"in_reply_to_status_id,omitempty"` + InReplyToStatusIDStr string `json:"in_reply_to_status_id_str,omitempty"` + CreatedAt string `json:"created_at"` + Favorited bool `json:"favorited"` + FullText string `json:"full_text"` + Lang string `json:"lang"` + InReplyToScreenName string `json:"in_reply_to_screen_name,omitempty"` + InReplyToUserID string `json:"in_reply_to_user_id,omitempty"` + InReplyToUserIDStr string `json:"in_reply_to_user_id_str,omitempty"` + PossiblySensitive bool `json:"possibly_sensitive,omitempty"` + ExtendedEntities *extendedEntities `json:"extended_entities,omitempty"` + WithheldCopyright bool `json:"withheld_copyright,omitempty"` + WithheldInCountries []string `json:"withheld_in_countries,omitempty"` + WithheldScope string `json:"withheld_scope,omitempty"` + + createdAtParsed time.Time + ownerAccount twitterAccount +} + +func (t *tweet) ID() string { + if t.TweetID != "" { + return t.TweetID + } + return t.TweetIDStr +} + +func (t *tweet) Timestamp() time.Time { + return t.createdAtParsed +} + +func (t *tweet) Class() timeliner.ItemClass { + return timeliner.ClassPost +} + +func (t *tweet) Owner() (id *string, name *string) { + return &t.ownerAccount.AccountID, &t.ownerAccount.Username +} + +func (t *tweet) DataText() (*string, error) { + return &t.FullText, nil +} + +func (t *tweet) DataFileName() *string { + if t.hasExactlyOneMediaItem() { + return t.ExtendedEntities.Media[0].DataFileName() + } + return nil +} + +func (t *tweet) DataFileReader() (io.ReadCloser, error) { + if t.hasExactlyOneMediaItem() { + return t.ExtendedEntities.Media[0].DataFileReader() + } + return nil, nil +} + +func (t *tweet) DataFileHash() []byte { + if t.hasExactlyOneMediaItem() { + return t.ExtendedEntities.Media[0].DataFileHash() + } + return nil +} + +func (t *tweet) DataFileMIMEType() *string { + if t.hasExactlyOneMediaItem() { + return t.ExtendedEntities.Media[0].DataFileMIMEType() + } + return nil +} + +func (t *tweet) Metadata() (*timeliner.Metadata, error) { + return nil, nil // TODO +} + +func (t *tweet) Location() (*timeliner.Location, error) { + return nil, nil // TODO +} + +func (t *tweet) isRetweet() bool { + if t.Retweeted { + return true + } + // TODO: For some reason, when exporting one's Twitter data, + // it always sets "retweeted" to false, even when "full_text" + // clearly shows it's a retweet by prefixing it with "RT @" + // - this seems like a bug with Twitter's exporter + return strings.HasPrefix(t.FullText, "RT @") +} + +func (t *tweet) hasExactlyOneMediaItem() bool { + // "All Tweets with attached photos, videos and animated GIFs will include an + // extended_entities JSON object. The extended_entities object contains a single + // media array of media objects (see the entities section for its data + // dictionary). No other entity types, such as hashtags and links, are included + // in the extended_entities section." + // https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/extended-entities-object.html + return t.ExtendedEntities != nil && len(t.ExtendedEntities.Media) == 1 +} + +type tweetGeo struct { + Type string `json:"type"` + Coordinates []string `json:"coordinates"` // "latitude, then a longitude" +} + +type tweetPlace struct { + ID string `json:"id"` + URL string `json:"url"` + PlaceType string `json:"place_type"` + Name string `json:"name"` + FullName string `json:"full_name"` + CountryCode string `json:"country_code"` + Country string `json:"country"` + BoundingBox boundingBox `json:"bounding_box"` +} + +type boundingBox struct { + Type string `json:"type"` + + // "A series of longitude and latitude points, defining a box which will contain + // the Place entity this bounding box is related to. Each point is an array in + // the form of [longitude, latitude]. Points are grouped into an array per bounding + // box. Bounding box arrays are wrapped in one additional array to be compatible + // with the polygon notation." + Coordinates [][][]float64 `json:"coordinates"` +} + +type tweetEntities struct { + Hashtags []hashtagEntity `json:"hashtags"` + Symbols []symbolEntity `json:"symbols"` + UserMentions []userMentionEntity `json:"user_mentions"` + URLs []urlEntity `json:"urls"` + Polls []pollEntity `json:"polls"` +} + +type hashtagEntity struct { + Indices []string `json:"indices"` + Text string `json:"text"` +} + +type symbolEntity struct { + Indices []string `json:"indices"` + Text string `json:"text"` +} + +type urlEntity struct { + URL string `json:"url"` + ExpandedURL string `json:"expanded_url"` + DisplayURL string `json:"display_url"` + Unwound *urlEntityUnwound `json:"unwound,omitempty"` + Indices []string `json:"indices"` +} + +type urlEntityUnwound struct { + URL string `json:"url"` + Status int `json:"status"` + Title string `json:"title"` + Description string `json:"description"` +} + +type userMentionEntity struct { + Name string `json:"name"` + ScreenName string `json:"screen_name"` + Indices []string `json:"indices"` + IDStr string `json:"id_str"` + ID string `json:"id"` +} + +type pollEntity struct { + Options []pollOption `json:"options"` + EndDatetime string `json:"end_datetime"` + DurationMinutes int `json:"duration_minutes"` +} + +type pollOption struct { + Position int `json:"position"` + Text string `json:"text"` +} + +type extendedEntities struct { + Media []*mediaItem `json:"media"` +} + +type mediaItem struct { + ExpandedURL string `json:"expanded_url"` + SourceStatusID string `json:"source_status_id"` + Indices []string `json:"indices"` + URL string `json:"url"` + MediaURL string `json:"media_url"` + MediaIDStr string `json:"id_str"` + VideoInfo *videoInfo `json:"video_info,omitempty"` + SourceUserID string `json:"source_user_id"` + AdditionalMediaInfo *additionalMediaInfo `json:"additional_media_info,omitempty"` + MediaID string `json:"id"` + MediaURLHTTPS string `json:"media_url_https"` + SourceUserIDStr string `json:"source_user_id_str"` + Sizes mediaSizes `json:"sizes"` + Type string `json:"type"` + SourceStatusIDStr string `json:"source_status_id_str"` + DisplayURL string `json:"display_url"` + + parent *tweet + reader io.Reader +} + +func (m *mediaItem) ID() string { + if m.MediaID != "" { + return m.MediaID + } + return m.MediaIDStr +} + +func (m *mediaItem) Timestamp() time.Time { + return m.parent.createdAtParsed +} + +func (m *mediaItem) Class() timeliner.ItemClass { + switch m.Type { + case "photo": + return timeliner.ClassImage + case "animated_gif": + fallthrough // Twitter encodes these as video files + case "video": + return timeliner.ClassVideo + } + return timeliner.ClassUnknown +} + +func (m *mediaItem) Owner() (id *string, name *string) { + return &m.SourceUserID, nil +} + +func (m *mediaItem) DataText() (*string, error) { + return nil, nil +} + +func (m *mediaItem) DataFileName() *string { + var source string + switch m.Type { + case "animated_gif": + fallthrough + case "video": + _, _, source = m.getLargestVideo() + u, err := url.Parse(source) + if err == nil { + source = path.Base(u.Path) + } else { + source = path.Base(source) + } + case "photo": + // TODO -- how to get the largest, will there be multiple?? + mURL := m.getURL() + u, err := url.Parse(mURL) + if err == nil { + source = path.Base(u.Path) + } else { + source = path.Base(mURL) + } + } + filename := fmt.Sprintf("%s-%s", m.parent.TweetID, source) + return &filename +} + +func (m *mediaItem) DataFileReader() (io.ReadCloser, error) { + if m.reader == nil { + return nil, fmt.Errorf("missing data file reader; this is probably a bug: %+v - video info: %+v", m, m.VideoInfo) + } + return timeliner.FakeCloser(m.reader), nil +} + +func (m *mediaItem) DataFileHash() []byte { + return nil +} + +func (m *mediaItem) DataFileMIMEType() *string { + switch m.Type { + case "animated_gif": + fallthrough + case "video": + _, contentType, _ := m.getLargestVideo() + return &contentType + case "photo": + fname := m.DataFileName() + if fname == nil { + return nil + } + ext := strings.ToLower(path.Ext(*fname)) + if len(ext) == 0 { + return nil + } + suffix := ext[1:] // trim the leading dot + if suffix == "jpg" { + suffix = "jpeg" + } + mt := "image/" + suffix + return &mt + } + return nil +} + +func (m *mediaItem) Metadata() (*timeliner.Metadata, error) { + return nil, nil // TODO +} + +func (m *mediaItem) Location() (*timeliner.Location, error) { + return nil, nil // TODO +} + +// TODO: How to get the largest image file? (The importer only has a single copy available to it, but videos have multiple variants....) + +func (m *mediaItem) getLargestVideo() (bitrate int, contentType, source string) { + if m.VideoInfo == nil { + return + } + bitrate = -1 // so that greater-than comparison below works for video bitrate=0 (animated_gif) + for _, v := range m.VideoInfo.Variants { + brInt, err := strconv.Atoi(v.Bitrate) + if err != nil { + continue + } + if brInt > bitrate { + source = v.URL + contentType = v.ContentType + bitrate = brInt + } + } + + return +} + +// TODO: This works only for images... +func (m *mediaItem) getURL() string { + if m.MediaURLHTTPS != "" { + return m.MediaURLHTTPS + } + return m.MediaURL +} + +type additionalMediaInfo struct { + Monetizable bool `json:"monetizable"` +} + +type videoInfo struct { + AspectRatio []string `json:"aspect_ratio"` + DurationMillis string `json:"duration_millis"` + Variants []videoVariants `json:"variants"` +} + +type videoVariants struct { + Bitrate string `json:"bitrate,omitempty"` + ContentType string `json:"content_type,omitempty"` + URL string `json:"url"` +} + +type mediaSizes struct { + Thumb mediaSize `json:"thumb"` + Small mediaSize `json:"small"` + Medium mediaSize `json:"medium"` + Large mediaSize `json:"large"` +} + +type mediaSize struct { + W string `json:"w"` + H string `json:"h"` + Resize string `json:"resize"` // fit|crop +} + +type twitterUser struct { + ID int64 `json:"id"` + IDStr string `json:"id_str"` + Name string `json:"name"` + ScreenName string `json:"screen_name"` + Location string `json:"location"` + URL string `json:"url"` + Description string `json:"description"` + Verified bool `json:"verified"` + FollowersCount int `json:"followers_count"` + FriendsCount int `json:"friends_count"` + ListedCount int `json:"listed_count"` + FavouritesCount int `json:"favourites_count"` + StatusesCount int `json:"statuses_count"` + CreatedAt string `json:"created_at"` + UTCOffset interface{} `json:"utc_offset"` + TimeZone interface{} `json:"time_zone"` + GeoEnabled bool `json:"geo_enabled"` + Lang string `json:"lang"` + ProfileImageURLHTTPS string `json:"profile_image_url_https"` + + // TODO: more fields exist; need to get actual example to build struct from +} +type twitterAccountFile []struct { + Account twitterAccount `json:"account"` +} + +type twitterAccount struct { + PhoneNumber string `json:"phoneNumber"` + Email string `json:"email"` + CreatedVia string `json:"createdVia"` + Username string `json:"username"` + AccountID string `json:"accountId"` + CreatedAt time.Time `json:"createdAt"` + AccountDisplayName string `json:"accountDisplayName"` +} diff --git a/datasources/twitter/twitter.go b/datasources/twitter/twitter.go new file mode 100644 index 0000000..02573ca --- /dev/null +++ b/datasources/twitter/twitter.go @@ -0,0 +1,317 @@ +// Package twitter implements a Timeliner service for importing +// and downloading data from Twitter. +package twitter + +import ( + "archive/zip" + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "path" + "time" + + "github.com/mholt/archiver" + "github.com/mholt/timeliner" + cuckoo "github.com/seiflotfy/cuckoofilter" +) + +// Service name and ID. +const ( + DataSourceName = "Twitter" + DataSourceID = "twitter" +) + +var dataSource = timeliner.DataSource{ + ID: DataSourceID, + Name: DataSourceName, + NewClient: func(acc timeliner.Account) (timeliner.Client, error) { + return &Client{ + acc: acc, + topLevelTweets: cuckoo.NewFilter(1000000), + }, nil + }, +} + +func init() { + err := timeliner.RegisterDataSource(dataSource) + if err != nil { + log.Fatal(err) + } +} + +// Client implements the timeliner.Client interface. +type Client struct { + Retweets bool + + Replies bool // TODO: replies should include context, like the surrounding conversation, as part of the graph... + // Threads bool // TODO: this requires more tweets, using the API + + acc timeliner.Account + + ownerAccount twitterAccount + + topLevelTweets *cuckoo.Filter +} + +// ListItems lists items from opt.Filename. TODO: support API too +func (c *Client) ListItems(ctx context.Context, itemChan chan<- *timeliner.ItemGraph, opt timeliner.Options) error { + defer close(itemChan) + + // TODO: integrate with the API too + if opt.Filename == "" { + return fmt.Errorf("filename is required") + } + + // load the user's account ID + var err error + c.ownerAccount, err = c.getOwnerAccount(opt.Filename) + if err != nil { + return fmt.Errorf("unable to get user account ID: %v", err) + } + + // first pass - add tweets to timeline + err = c.processArchive(opt.Filename, itemChan, c.processTweet) + if err != nil { + return fmt.Errorf("processing tweets: %v", err) + } + + // second pass - add tweet relationships to timeline + err = c.processArchive(opt.Filename, itemChan, c.processReplyRelation) + if err != nil { + return fmt.Errorf("processing tweets: %v", err) + } + + return nil +} + +func (c *Client) processArchive(archiveFilename string, itemChan chan<- *timeliner.ItemGraph, processFunc processFn) error { + err := archiver.Walk(archiveFilename, func(f archiver.File) error { + defer f.Close() + if f.Name() != "tweet.js" { + return nil + } + + // consume non-JSON preface (JavaScript variable definition) + err := stripPreface(f, tweetFilePreface) + if err != nil { + return fmt.Errorf("reading tweet file preface: %v", err) + } + + err = c.processTweets(itemChan, f, archiveFilename, processFunc) + if err != nil { + return fmt.Errorf("processing tweet file: %v", err) + } + + return archiver.ErrStopWalk + }) + if err != nil { + return fmt.Errorf("walking archive file %s: %v", archiveFilename, err) + } + + return nil +} + +func (c *Client) processTweets(itemChan chan<- *timeliner.ItemGraph, f io.Reader, + archiveFilename string, processFunc processFn) error { + + dec := json.NewDecoder(f) + + // read array opening bracket '[' + _, err := dec.Token() + if err != nil { + return fmt.Errorf("decoding opening token: %v", err) + } + + for dec.More() { + var t tweet + err := dec.Decode(&t) + if err != nil { + return fmt.Errorf("decoding tweet element: %v", err) + } + + // tweets from an import file are presumed to all be from the account owner + t.ownerAccount = c.ownerAccount + + // skip tweets we aren't interested in + if !c.Retweets && t.isRetweet() { + continue // retweets + } + if !c.Replies && t.InReplyToUserID != "" && t.InReplyToUserID != t.ownerAccount.AccountID { + // TODO: Replies should have more context, like what are we replying to, etc... the whole thread, even? + // this option is about replies to tweets other than our own, which are like a continuation of one thought + continue // replies + } + + // parse Twitter's time string into an actual time value + t.createdAtParsed, err = time.Parse("Mon Jan 2 15:04:05 -0700 2006", t.CreatedAt) + if err != nil { + return fmt.Errorf("parsing created_at time: %v", err) + } + + err = processFunc(itemChan, t, archiveFilename) + if err != nil { + return fmt.Errorf("processing tweet: %v", err) + } + } + + return nil +} + +func (c *Client) processTweet(itemChan chan<- *timeliner.ItemGraph, t tweet, archiveFilename string) error { + oneMediaItem := t.hasExactlyOneMediaItem() + + // only create a tweet item if it has text OR exactly one media item + // (because we don't want an empty item; we process each media item + // as a separate item, unless there's exactly 1, in which case we + // in-line it into the tweet itself) + var ig *timeliner.ItemGraph + if t.FullText != "" || !oneMediaItem { + ig = timeliner.NewItemGraph(&t) + } + + // process the media items attached to the tweet + if t.ExtendedEntities != nil { + var collItems []timeliner.CollectionItem + + for i, m := range t.ExtendedEntities.Media { + m.parent = &t + + var dataFileName string + if dfn := m.DataFileName(); dfn == nil || *dfn == "" { + log.Printf("[ERROR][%s/%s] Tweet media has no data file name: %+v", + DataSourceID, c.acc.UserID, m) + continue + } else { + dataFileName = *dfn + } + + targetFileInArchive := path.Join("tweet_media", dataFileName) + + err := archiver.Walk(archiveFilename, func(f archiver.File) error { + if f.Header.(zip.FileHeader).Name != targetFileInArchive { + return nil + } + + buf := new(bytes.Buffer) + _, err := io.Copy(buf, f) + if err != nil { + return fmt.Errorf("copying item into memory: %v", err) + } + m.reader = buf + + if !oneMediaItem { + if ig != nil { + ig.Add(m, timeliner.RelAttached) + } + collItems = append(collItems, timeliner.CollectionItem{ + Item: m, + Position: i, + }) + } + + return archiver.ErrStopWalk + }) + if err != nil { + return fmt.Errorf("walking archive file %s in search of tweet media: %v", + archiveFilename, err) + } + + } + + if len(collItems) > 0 { + ig.Collections = append(ig.Collections, timeliner.Collection{ + OriginalID: "tweet_" + t.ID(), + Items: collItems, + }) + } + } + + // send the tweet for processing + if ig != nil { + itemChan <- ig + } + + // if this is a top-level tweet (i.e. not a reply), mark + // it so that we can use it to get replies from our own + // top level tweets, as they can be a continuation of thought + if t.InReplyToStatusID == "" { + c.topLevelTweets.InsertUnique([]byte(t.TweetID)) + } + + return nil +} + +func (c *Client) processReplyRelation(itemChan chan<- *timeliner.ItemGraph, t tweet, archiveFilename string) error { + if t.InReplyToStatusID == "" { + // current tweet is not a reply, so no relationship to add + return nil + } + if !c.topLevelTweets.Lookup([]byte(t.InReplyToStatusID)) { + // reply is not to a top-level tweet by self, so doesn't qualify for what we want + return nil + } + + ig := &timeliner.ItemGraph{ + Relations: []timeliner.RawRelation{ + { + FromItemID: t.TweetID, + ToItemID: t.InReplyToStatusID, + Relation: timeliner.RelReplyTo, + }, + }, + } + + itemChan <- ig + + return nil +} + +func (c *Client) getOwnerAccount(filename string) (twitterAccount, error) { + var ta twitterAccount + err := archiver.Walk(filename, func(f archiver.File) error { + defer f.Close() + if f.Name() != "account.js" { + return nil + } + + // consume non-JSON preface (JavaScript variable definition) + err := stripPreface(f, accountFilePreface) + if err != nil { + return fmt.Errorf("reading account file preface: %v", err) + } + + var accFile twitterAccountFile + err = json.NewDecoder(f).Decode(&accFile) + if err != nil { + return fmt.Errorf("decoding account file: %v", err) + } + if len(accFile) == 0 { + return fmt.Errorf("account file was empty") + } + + ta = accFile[0].Account + + return archiver.ErrStopWalk + }) + return ta, err +} + +func stripPreface(f io.Reader, preface string) error { + buf := make([]byte, len(preface)) + _, err := io.ReadFull(f, buf) + return err +} + +// processFn is a function that processes a tweet. +type processFn func(itemChan chan<- *timeliner.ItemGraph, t tweet, archiveFilename string) error + +// Variable definitions that are intended for +// use with JavaScript but which are of no use +// to us and would break the JSON parser. +const ( + tweetFilePreface = "window.YTD.tweet.part0 =" + accountFilePreface = "window.YTD.account.part0 =" +) diff --git a/db.go b/db.go new file mode 100644 index 0000000..821ee8e --- /dev/null +++ b/db.go @@ -0,0 +1,144 @@ +package timeliner + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + + // register the sqlite3 driver + _ "github.com/mattn/go-sqlite3" +) + +func openDB(dataDir string) (*sql.DB, error) { + var db *sql.DB + var err error + defer func() { + if err != nil && db != nil { + db.Close() + } + }() + + err = os.MkdirAll(dataDir, 0755) + if err != nil { + return nil, fmt.Errorf("making data directory: %v", err) + } + + dbPath := filepath.Join(dataDir, "index.db") + + db, err = sql.Open("sqlite3", dbPath+"?_foreign_keys=true") + if err != nil { + return nil, fmt.Errorf("opening database: %v", err) + } + + // ensure DB is provisioned + _, err = db.Exec(createDB) + if err != nil { + return nil, fmt.Errorf("setting up database: %v", err) + } + + // add all registered data sources + err = saveAllDataSources(db) + if err != nil { + return nil, fmt.Errorf("saving registered data sources to database: %v", err) + } + + return db, nil +} + +const createDB = ` +-- A data source is a content provider, like a cloud photo service, social media site, or exported archive format. +CREATE TABLE IF NOT EXISTS "data_sources" ( + "id" TEXT PRIMARY KEY, + "name" TEXT NOT NULL +); + +-- An account contains credentials necessary for accessing a data source. +CREATE TABLE IF NOT EXISTS "accounts" ( + "id" INTEGER PRIMARY KEY, + "data_source_id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "authorization" BLOB, + "checkpoint" BLOB, + FOREIGN KEY ("data_source_id") REFERENCES "data_sources"("id") ON DELETE CASCADE, + UNIQUE ("data_source_id", "user_id") +); + +CREATE TABLE IF NOT EXISTS "persons" ( + "id" INTEGER PRIMARY KEY, + "name" TEXT +); + +-- This table specifies identities (user IDs, etc.) of a person across data_sources. +CREATE TABLE IF NOT EXISTS "person_identities" ( + "id" INTEGER PRIMARY KEY, + "person_id" INTEGER NOT NULL, + "data_source_id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, -- whatever identifier a person takes on at the data source + FOREIGN KEY ("person_id") REFERENCES "persons"("id") ON DELETE CASCADE, + FOREIGN KEY ("data_source_id") REFERENCES "data_sources"("id") ON DELETE CASCADE, + UNIQUE ("person_id", "data_source_id", "user_id") +); + +-- An item is something downloaded from a specific account on a specific data source. +CREATE TABLE IF NOT EXISTS "items" ( + "id" INTEGER PRIMARY KEY, + "account_id" INTEGER NOT NULL, + "original_id" TEXT NOT NULL, -- ID provided by the data source + "person_id" INTEGER NOT NULL, + "timestamp" INTEGER, -- timestamp when item content was originally created + "stored" INTEGER NOT NULL DEFAULT (strftime('%s', CURRENT_TIME)), -- timestamp row was created - TODO not sure if needed + "modified" INTEGER, -- timestamp when item was locally modified; if not null, then item is "not clean" + "class" INTEGER, + "mime_type" TEXT, + "data_text" TEXT COLLATE NOCASE, -- item content, if text-encoded + "data_file" TEXT, -- item filename, if non-text or not suitable for storage in DB (usually media items) + "data_hash" TEXT, -- base64 encoding of SHA-256 checksum of contents of data file, if any + "metadata" BLOB, -- optional extra information + "latitude" REAL, + "longitude" REAL, + FOREIGN KEY ("account_id") REFERENCES "accounts"("id") ON DELETE CASCADE, + FOREIGN KEY ("person_id") REFERENCES "persons"("id") ON DELETE CASCADE, + UNIQUE ("original_id", "account_id") +); + +CREATE INDEX IF NOT EXISTS "idx_items_timestamp" ON "items"("timestamp"); +CREATE INDEX IF NOT EXISTS "idx_items_data_text" ON "items"("data_text"); +CREATE INDEX IF NOT EXISTS "idx_items_data_hash" ON "items"("data_hash"); + +-- Relationships draws relationships between and across items and persons. +CREATE TABLE IF NOT EXISTS "relationships" ( + "id" INTEGER PRIMARY KEY, + "from_person_id" INTEGER, + "from_item_id" INTEGER, + "to_person_id" INTEGER, + "to_item_id" INTEGER, + "directed" BOOLEAN, -- if false, the edge goes both ways + "label" TEXT, + FOREIGN KEY ("from_item_id") REFERENCES "items"("id") ON DELETE CASCADE, + FOREIGN KEY ("to_item_id") REFERENCES "items"("id") ON DELETE CASCADE, + FOREIGN KEY ("from_person_id") REFERENCES "persons"("id") ON DELETE CASCADE, + FOREIGN KEY ("to_person_id") REFERENCES "persons"("id") ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS "collections" ( + "id" INTEGER PRIMARY KEY, + "account_id" INTEGER NOT NULL, + "original_id" TEXT, + "name" TEXT, + "description" TEXT, + "modified" INTEGER, -- timestamp when collection or any of its items/ordering were modified locally; if not null, then collection is "not clean" + FOREIGN KEY ("account_id") REFERENCES "accounts"("id") ON DELETE CASCADE, + UNIQUE("account_id", "original_id") +); + +CREATE TABLE IF NOT EXISTS "collection_items" ( + "id" INTEGER PRIMARY KEY, + "item_id" INTEGER NOT NULL, + "collection_id" INTEGER NOT NULL, + "position" INTEGER NOT NULL DEFAULT 0, + FOREIGN KEY ("item_id") REFERENCES "items"("id") ON DELETE CASCADE, + FOREIGN KEY ("collection_id") REFERENCES "collections"("id") ON DELETE CASCADE, + UNIQUE("item_id", "collection_id", "position") +); +` diff --git a/itemfiles.go b/itemfiles.go new file mode 100644 index 0000000..4bee2e3 --- /dev/null +++ b/itemfiles.go @@ -0,0 +1,283 @@ +package timeliner + +import ( + "crypto/sha256" + "database/sql" + "encoding/base64" + "fmt" + "hash" + "io" + "log" + mathrand "math/rand" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "time" +) + +// downloadItemFile ... TODO. +func (t *Timeline) downloadItemFile(src io.ReadCloser, dest *os.File, h hash.Hash) error { + if src == nil { + return fmt.Errorf("missing reader with which to download file") + } + if dest == nil { + return fmt.Errorf("missing file to download into") + } + + // TODO: What if file already exists on disk (byte-for-byte)? - i.e. data_hash in DB has a duplicate + + // give the hasher a copy of the file bytes + tr := io.TeeReader(src, h) + + if _, err := io.Copy(dest, tr); err != nil { + os.Remove(dest.Name()) + return fmt.Errorf("copying contents: %v", err) + } + if err := dest.Sync(); err != nil { + os.Remove(dest.Name()) + return fmt.Errorf("syncing file: %v", err) + } + + // TODO: If mime type is photo or video, extract most important EXIF data and return it for storage in DB? + + return nil +} + +// makeUniqueCanonicalItemDataFileName returns an available +// (non-overwriting) filename for the item's data file, starting +// with its plain, canonical data file name, then improvising +// and making unique if necessary. If there is no error, the +// return value is always a usable data file name. +// TODO: fix godoc +func (t *Timeline) openUniqueCanonicalItemDataFile(it Item, dataSourceID string) (*os.File, *string, error) { + if dataSourceID == "" { + return nil, nil, fmt.Errorf("missing service ID") + } + + dir := t.canonicalItemDataFileDir(it, dataSourceID) + + err := os.MkdirAll(t.fullpath(dir), 0700) + if err != nil { + return nil, nil, fmt.Errorf("making directory for data file: %v", err) + } + + tryPath := path.Join(dir, t.canonicalItemDataFileName(it, dataSourceID)) + lastAppend := path.Ext(tryPath) + + for i := 0; i < 100; i++ { + fullFilePath := t.fullpath(filepath.FromSlash(tryPath)) + + f, err := os.OpenFile(fullFilePath, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0600) + if os.IsExist(err) { + ext := path.Ext(tryPath) + tryPath = strings.TrimSuffix(tryPath, lastAppend) + lastAppend = fmt.Sprintf("_%d%s", i+1, ext) // start at 1, but actually 2 because existing file is "1" + tryPath += lastAppend + + continue + } + if err != nil { + return nil, nil, fmt.Errorf("creating data file: %v", err) + } + + return f, &tryPath, nil + } + + return nil, nil, fmt.Errorf("unable to find available filename for item: %s", tryPath) +} + +// canonicalItemDataFileName returns the plain, canonical name of the +// data file for the item. Canonical data file names are relative to +// the base storage (repo) path (i.e. the folder of the DB file). This +// function does no improvising in case of a name missing from the item, +// nor does it do uniqueness checks. If the item does not have enough +// information to generate a deterministic file name, the returned path +// will end with a trailing slash (i.e. the path's last component empty). +// Things considered deterministic for filename construction include the +// item's filename, the item's original ID, and its timestamp. +// TODO: fix godoc +func (t *Timeline) canonicalItemDataFileName(it Item, dataSourceID string) string { + // ideally, the filename is simply the one provided with the item + var filename string + if fname := it.DataFileName(); fname != nil { + filename = t.safePathComponent(*fname) + } + + // otherwise, try a filename based on the item's ID + if filename == "" { + if itemOriginalID := it.ID(); itemOriginalID != "" { + filename = fmt.Sprintf("item_%s", itemOriginalID) + } + } + + // otherwise, try a filename based on the item's timestamp + ts := it.Timestamp() + if filename == "" && !ts.IsZero() { + filename = ts.Format("2006_01_02_150405") + } + + // otherwise, out of options; revert to a random string + // since no deterministic filename is available + if filename == "" { + filename = randomString(24, false) + } + + // shorten the name if needed (thanks for everything, Windows) + return t.ensureDataFileNameShortEnough(filename) +} + +func (t *Timeline) canonicalItemDataFileDir(it Item, dataSourceID string) string { + ts := it.Timestamp() + if ts.IsZero() { + ts = time.Now() + } + + if dataSourceID == "" { + dataSourceID = "unknown_service" + } + + // use "/" separators and adjust for the OS + // path separator when accessing disk + return path.Join("data", + fmt.Sprintf("%04d", ts.Year()), + fmt.Sprintf("%02d", ts.Month()), + t.safePathComponent(dataSourceID)) +} + +func (t *Timeline) ensureDataFileNameShortEnough(filename string) string { + // thanks for nothing, Windows + if len(filename) > 250 { + ext := path.Ext(filename) + if len(ext) > 20 { // arbitrary and unlikely, but just in case + ext = ext[:20] + } + filename = filename[:250-len(ext)] + filename += ext + } + return filename +} + +// func ensureDataFileNameUnique(canonicalDataFileName string, maxTries int) (string, error) { +// if maxTries < 1 { +// panic("maxTries must be at least 1") +// } +// lastAppend := path.Ext(canonicalDataFileName) +// for i := 0; i < maxTries; i++ { +// if !datafileExists(canonicalDataFileName) { +// return canonicalDataFileName, nil +// } +// ext := path.Ext(canonicalDataFileName) +// canonicalDataFileName = strings.TrimSuffix(canonicalDataFileName, lastAppend) +// lastAppend = fmt.Sprintf("_%d%s", i+2, ext) // start at 1, but actually 2 because first file is "1" +// canonicalDataFileName += lastAppend +// } +// return "", fmt.Errorf("could not find an available filename for %s in %d iterations", +// canonicalDataFileName, maxTries) +// } + +// TODO/NOTE: If changing a file name, all items with same data_hash must also be updated to use same file name +func (t *Timeline) replaceWithExisting(canonical *string, checksumBase64 string, itemRowID int64) error { + if canonical == nil || *canonical == "" || checksumBase64 == "" { + return fmt.Errorf("missing data filename and/or hash of contents") + } + + var existingDatafile *string + err := t.db.QueryRow(`SELECT data_file FROM items + WHERE data_hash = ? AND id != ? LIMIT 1`, + checksumBase64, itemRowID).Scan(&existingDatafile) + if err == sql.ErrNoRows { + return nil // file is unique; carry on + } + if err != nil { + return fmt.Errorf("querying DB: %v", err) + } + + // file is a duplicate! + + if existingDatafile == nil { + // ... that's weird, how's this possible? it has a hash but no file name recorded + return fmt.Errorf("item with matching hash is missing data file name; hash: %s", checksumBase64) + } + + // ensure the existing file is still the same + h := sha256.New() + f, err := os.Open(t.fullpath(*existingDatafile)) + if err != nil { + return fmt.Errorf("opening existing file: %v", err) + } + defer f.Close() + + _, err = io.Copy(h, f) + if err != nil { + return fmt.Errorf("checking file integrity: %v", err) + } + + existingFileHash := h.Sum(nil) + b64ExistingFileHash := base64.StdEncoding.EncodeToString(existingFileHash) + + // if the existing file was modified; restore it with + // what we just downloaded, which presumably succeeded + if checksumBase64 != b64ExistingFileHash { + log.Printf("[INFO] Restoring modified data file: %s was '%s' but is now '%s'", + *existingDatafile, checksumBase64, existingFileHash) + err := os.Rename(t.fullpath(*canonical), t.fullpath(*existingDatafile)) + if err != nil { + return fmt.Errorf("replacing modified data file: %v", err) + } + } + + // everything checks out; delete the newly-downloaded file + // and use the existing file instead of duplicating it + err = os.Remove(t.fullpath(*canonical)) + if err != nil { + return fmt.Errorf("removing duplicate data file: %v", err) + } + + canonical = existingDatafile + + return nil +} + +// randomString returns a string of n random characters. +// It is not even remotely secure or a proper distribution. +// But it's good enough for some things. It excludes certain +// confusing characters like I, l, 1, 0, O, etc. If sameCase +// is true, then uppercase letters are excluded. +func randomString(n int, sameCase bool) string { + if n <= 0 { + return "" + } + dict := []byte("abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY23456789") + if sameCase { + dict = []byte("abcdefghijkmnpqrstuvwxyz0123456789") + } + b := make([]byte, n) + for i := range b { + b[i] = dict[mathrand.Int63()%int64(len(dict))] + } + return string(b) +} + +func (t *Timeline) fullpath(canonicalDatafileName string) string { + return filepath.Join(t.repoDir, filepath.FromSlash(canonicalDatafileName)) +} + +func (t *Timeline) datafileExists(canonicalDatafileName string) bool { + _, err := os.Stat(t.fullpath(canonicalDatafileName)) + return !os.IsNotExist(err) +} + +func (t *Timeline) safePathComponent(s string) string { + s = safePathRE.ReplaceAllLiteralString(s, "") + s = strings.Replace(s, "..", "", -1) + if s == "." { + s = "" + } + return s +} + +// safePathRER matches any undesirable characters in a filepath. +// Note that this allows dots, so you'll have to strip ".." manually. +var safePathRE = regexp.MustCompile(`[^\w.-]`) diff --git a/itemgraph.go b/itemgraph.go new file mode 100644 index 0000000..662b806 --- /dev/null +++ b/itemgraph.go @@ -0,0 +1,407 @@ +package timeliner + +import ( + "bytes" + "encoding/gob" + "io" + "time" +) + +// Item is the central concept of a piece of content +// from a service or data source. Take note of which +// methods are required to return non-empty values. +// +// The actual content of an item is stored either in +// the database or on disk as a file. Generally, +// content that is text-encoded can and should be +// stored in the database where it will be indexed. +// However, if the item's content (for example, the +// bytes of a photo or video) are not text or if the +// text is too large to store well in a database (for +// example, an entire novel), it should be stored +// on disk, and this interface has methods to +// accommodate both. Note that an item may have both +// text and non-text content, too: for example, photos +// and videos may have descriptions that are as much +// "content" as the media iteself. One part of an item +// is not mutually exclusive with any other. +type Item interface { + // The unique ID of the item assigned by the service. + // If the service does not assign one, then invent + // one such that the ID is unique to the content or + // substance of the item (for example, an ID derived + // from timestamp or from the actual content of the + // item -- whatever makes it unique). The ID need + // only be unique for the account it is associated + // with, although more unique is, of course, acceptable. + // + // REQUIRED. + ID() string + + // The originating timestamp of the item, which + // may be different from when the item was posted + // or created. For example, a photo may be taken + // one day but uploaded a week later. Prefer the + // time when the original item content was captured. + // + // REQUIRED. + Timestamp() time.Time + + // A classification of the item's kind. + // + // REQUIRED. + Class() ItemClass + + // The user/account ID of the owner or + // originator of the content, along with their + // username or real name. The ID is used to + // relate the item with the person behind it; + // the name is used to make the person + // recognizable to the human reader. If the + // ID is nil, the current account owner will + // be assumed. (Use the ID as given by the + // data source.) If the data source only + // provides a name but no ID, you may return + // the name as the ID with the understanding + // that a different name will be counted as a + // different person. You may also return the + // name as the name and leave the ID nil and + // have correct results if it is safe to assume + // the name belongs to the current account owner. + Owner() (id *string, name *string) + + // Returns the text of the item, if any. + // This field is indexed in the DB, so don't + // use for unimportant metadata or huge + // swaths of text; if there is a large + // amount of text, use an item file instead. + DataText() (*string, error) + + // For primary content which is not text or + // which is too large to be stored well in a + // database, the content can be downloaded + // into a file. If so, the following methods + // should return the necessary information, + // if available from the service, so that a + // data file can be obtained, stored, and + // later read successfully. + // + // DataFileName returns the filename (NOT full + // path or URL) of the file; prefer the original + // filename if it originated as a file. If the + // filename is not unique on disk when downloaded, + // it will be made unique by modifying it. If + // this value is nil/empty, a filename will be + // generated from the item's other data. + // + // DataFileReader returns a way to read the data. + // It will be closed when the read is completed. + // + // DataFileHash returns the checksum of the + // content as provided by the service. If the + // service (or data source) does not provide a + // hash, leave this field empty, but note that + // later it will be impossible to efficiently + // know whether the content has changed on the + // service from what is stored locally. + // + // DataFileMIMEType returns the MIME type of + // the data file, if known. + DataFileName() *string + DataFileReader() (io.ReadCloser, error) + DataFileHash() []byte + DataFileMIMEType() *string + + // Metadata returns any optional metadata. + // Feel free to leave as many fields empty + // as you'd like: the less fields that are + // filled out, the smaller the storage size. + // Metadata is not indexed by the DB but is + // rendered in projections and queries + // according to the item's classification. + Metadata() (*Metadata, error) + + // Location returns an item's location, + // if known. For now, only Earth + // coordinates are accepted, but we can + // improve this later. + Location() (*Location, error) +} + +// ItemClass classifies an item. +type ItemClass int + +// Various classes of items. +const ( + ClassUnknown ItemClass = iota + ClassImage + ClassVideo + ClassAudio + ClassPost + ClassLocation + ClassEmail + ClassPrivateMessage +) + +// These are the standard relationships that Timeliner +// recognizes. Using these known relationships is not +// required, but it makes it easier to translate them +// human-friendly phrases when visualizing the timeline. +var ( + RelReplyTo = Relation{Label: "reply_to"} // " is in reply " + RelAttached = Relation{Label: "attached", Bidirectional: true} // " is attached " +) + +// ItemRow mirrors an item's row in our DB. +type ItemRow struct { + ID int64 + AccountID int64 + OriginalID string + PersonID int64 + Timestamp time.Time + Stored time.Time + Modified *time.Time + Class ItemClass + MIMEType *string + DataText *string + DataFile *string + DataHash *string // base64-encoded SHA-256 + Metadata *Metadata + Location + + metaGob []byte // use Metadata.(encode/decode) +} + +// Location contains location information. +type Location struct { + Latitude *float64 + Longitude *float64 +} + +// ItemGraph is an item with optional connections to other items. +// All ItemGraph values should be pointers to ensure consistency. +// The usual weird/fun thing about representing graph data structures +// in memory is that a graph is a node, and a node is a graph. 🤓 +type ItemGraph struct { + // The node item. This can be nil, but note that + // Edges will not be traversed if Node is nil, + // because there must be a node on both ends of + // an edge. + // + // Optional. + Node Item + + // Edges are represented as 1:many relations + // to other "graphs" (nodes in the graph). + // Fill this out to add multiple items to the + // timeline at once, while drawing the + // designated relationships between them. + // Useful when processing related items in + // batches. + // + // If the items involved in a relationship are + // not efficiently available at the same time + // (i.e. if loading both items involved in the + // relationship would take a non-trivial amount + // of time or API calls), you can use the + // Relations field instead, but only after the + // items have been added to the timeline. + // + // Optional. + Edges map[*ItemGraph][]Relation + + // If items in the graph belong to a collection, + // specify them here. If the collection does not + // exist (by row ID or AccountID+OriginalID), it + // will be created. If it already exists, the + // collection in the DB will be unioned with the + // collection specified here. Collections are + // processed regardless of Node and Edges. + // + // Optional. + Collections []Collection + + // Relationships between existing items in the + // timeline can be represented here in a list + // of item IDs that are connected by a label. + // This field is useful when relationships and + // the items involved in them are not discovered + // at the same time. Relations in this list will + // be added to the timeline, joined by the item + // IDs described in the RawRelations, only if + // the items having those IDs (as provided by + // the data source; we're not talking about DB + // row IDs here) already exist in the timeline. + // In other words, this is a best-effort field; + // useful for forming relationships of existing + // items, but without access to the actual items + // themselves. If you have the items involved in + // the relationships, use Edges instead. + // + // Optional. + Relations []RawRelation +} + +// NewItemGraph returns a new node/graph. +func NewItemGraph(node Item) *ItemGraph { + return &ItemGraph{ + Node: node, + Edges: make(map[*ItemGraph][]Relation), + } +} + +// Add adds item to the graph ig by making an edge described +// by rel from the node ig to a new node for item. +// +// This method is for simple inserts, where the only thing to add +// to the graph at this moment is a single item, since the graph +// it inserts contains only a single node populated by item. To +// add a full graph with multiple items (i.e. a graph with edges), +// call ig.Connect directly. +func (ig *ItemGraph) Add(item Item, rel Relation) { + ig.Connect(NewItemGraph(item), rel) +} + +// Connect is a simple convenience function that adds a graph (node) +// to ig by an edge described by rel. +func (ig *ItemGraph) Connect(node *ItemGraph, rel Relation) { + if ig.Edges == nil { + ig.Edges = make(map[*ItemGraph][]Relation) + } + ig.Edges[node] = append(ig.Edges[node], rel) +} + +// RawRelation represents a relationship between +// two items from the same data source (but not +// necessarily the same accounts; assuming that +// a data source's item IDs are globally unique +// across accounts). The item IDs should be those +// which are assigned/provided by the data source, +// NOT a database row ID. +type RawRelation struct { + FromItemID string + ToItemID string + Relation +} + +// Relation describes how two nodes in a graph are related. +// It's essentially an edge on a graph. +type Relation struct { + Label string + Bidirectional bool +} + +// Collection represents a group of items. +type Collection struct { + // The ID of the collection as given + // by the service; for example, the + // album ID. If the service does not + // provide an ID for the collection, + // invent one such that the next time + // the collection is encountered and + // processed, its ID will be the same. + // An ID is necessary here to ensure + // uniqueness. + // + // REQUIRED. + OriginalID string + + // The name of the collection as + // given by the service; for example, + // the album title. + // + // Optional. + Name *string + + // The description, caption, or any + // other relevant text describing + // the collection. + // + // Optional. + Description *string + + // The items for the collection; + // if ordering is significant, + // specify each item's Position + // field; the order of elememts + // of this slice will not be + // considered important. + Items []CollectionItem +} + +// CollectionItem represents an item +// stored in a collection. +type CollectionItem struct { + // The item to add to the collection. + Item Item + + // Specify if ordering is important. + Position int + + // Used when processing; this will + // store the row ID of the item + // after the item has been inserted + // into the DB. + itemRowID int64 +} + +// Metadata is a unified structure for storing +// item metadata in the DB. +type Metadata struct { + // A hash or etag provided by the service to + // make it easy to know if it has changed + ServiceHash []byte + + // Locations + LocationAccuracy int + Altitude int // meters + AltitudeAccuracy int + Heading int // degrees + Velocity int + + // Photos and videos + EXIF map[string]interface{} + // TODO: Should we have some of the "most important" EXIF fields explicitly here? + + Width int + Height int + + // TODO: Google Photos (how many of these belong in EXIF?) + CameraMake string + CameraModel string + FocalLength float64 + ApertureFNumber float64 + ISOEquivalent int + ExposureTime time.Duration + + FPS float64 // Frames Per Second + + // Posts (Facebook so far) + Link string + Description string + Name string + ParentID string + StatusType string + Type string +} + +func (m *Metadata) encode() ([]byte, error) { + // then encode the actual data, and trim off + // schema from the beginning + buf := new(bytes.Buffer) + err := gob.NewEncoder(buf).Encode(m) + if err != nil { + return nil, err + } + return buf.Bytes()[len(metadataGobPrefix):], nil +} + +func (m *Metadata) decode(b []byte) error { + if b == nil { + return nil + } + fullGob := append(metadataGobPrefix, b...) + return gob.NewDecoder(bytes.NewReader(fullGob)).Decode(m) +} + +var metadataGobPrefix []byte diff --git a/mapmutex.go b/mapmutex.go new file mode 100644 index 0000000..16edb8b --- /dev/null +++ b/mapmutex.go @@ -0,0 +1,39 @@ +package timeliner + +import "sync" + +// Modified from https://medium.com/@petrlozhkin/kmutex-lock-mutex-by-unique-id-408467659c24 + +type mapMutex struct { + cond *sync.Cond + set map[interface{}]struct{} +} + +func newMapMutex() *mapMutex { + return &mapMutex{ + cond: sync.NewCond(new(sync.Mutex)), + set: make(map[interface{}]struct{}), + } +} + +func (mmu *mapMutex) Lock(key interface{}) { + mmu.cond.L.Lock() + defer mmu.cond.L.Unlock() + for mmu.locked(key) { + mmu.cond.Wait() + } + mmu.set[key] = struct{}{} + return +} + +func (mmu *mapMutex) Unlock(key interface{}) { + mmu.cond.L.Lock() + defer mmu.cond.L.Unlock() + delete(mmu.set, key) + mmu.cond.Broadcast() +} + +func (mmu *mapMutex) locked(key interface{}) (ok bool) { + _, ok = mmu.set[key] + return +} diff --git a/oauth2.go b/oauth2.go new file mode 100644 index 0000000..85b7302 --- /dev/null +++ b/oauth2.go @@ -0,0 +1,100 @@ +package timeliner + +import ( + "context" + "fmt" + "net/http" + + "github.com/mholt/timeliner/oauth2client" + "golang.org/x/oauth2" +) + +// OAuth2TokenSource returns a TokenSource for the OAuth2 provider +// with the given ID. Programs using data sources that authenticate +// with OAuth2 MUST set this field, or the program will panic. +var OAuth2TokenSource func(providerID string, scopes []string) (oauth2client.App, error) + +// NewOAuth2HTTPClient returns a new HTTP client which performs +// HTTP requests that are authenticated with an oauth2.Token +// stored with the account acc. +func (acc Account) NewOAuth2HTTPClient() (*http.Client, error) { + // load the existing token for this account from the database + var tkn *oauth2.Token + err := UnmarshalGob(acc.authorization, &tkn) + if err != nil { + return nil, fmt.Errorf("gob-decoding OAuth2 token: %v", err) + } + if tkn == nil || tkn.AccessToken == "" { + return nil, fmt.Errorf("OAuth2 token is empty: %+v", tkn) + } + + // load the service's "oauth app", which can provide both tokens and + // oauth configs -- in this case, we need the oauth config; we should + // already have a token + oapp, err := OAuth2TokenSource(acc.ds.OAuth2.ProviderID, acc.ds.OAuth2.Scopes) + if err != nil { + return nil, fmt.Errorf("getting token source for %s: %v", acc.DataSourceID, err) + } + + // obtain a token source from the oauth's config so that it can keep + // the token refreshed if it expires + src := oapp.Config().TokenSource(context.Background(), tkn) + + // finally, create an HTTP client that authenticates using the token, + // but wrapping the underlying token source so we can persist any + // changes to the database + return oauth2.NewClient(context.Background(), &persistedTokenSource{ + tl: acc.t, + ts: src, + accountID: acc.ID, + token: tkn, + }), nil +} + +// authorizeWithOAuth2 gets an initial OAuth2 token from the user. It +// panics if OAuth2TokenSource +func authorizeWithOAuth2(providerID string, scopes []string) ([]byte, error) { + src, err := OAuth2TokenSource(providerID, scopes) + if err != nil { + return nil, fmt.Errorf("getting token source: %v", err) + } + tkn, err := src.Token() + if err != nil { + return nil, fmt.Errorf("getting token from source: %v", err) + } + return MarshalGob(tkn) +} + +// persistedTokenSource wraps a TokenSource for +// a particular account and persists any changes +// to the account's token to the database. +type persistedTokenSource struct { + tl *Timeline + ts oauth2.TokenSource + accountID int64 + token *oauth2.Token +} + +func (ps *persistedTokenSource) Token() (*oauth2.Token, error) { + tkn, err := ps.ts.Token() + if err != nil { + return tkn, err + } + + // store an updated token in the DB + if tkn.AccessToken != ps.token.AccessToken { + ps.token = tkn + + authBytes, err := MarshalGob(tkn) + if err != nil { + return nil, fmt.Errorf("gob-encoding new OAuth2 token: %v", err) + } + + _, err = ps.tl.db.Exec(`UPDATE accounts SET authorization=? WHERE id=?`, authBytes, ps.accountID) + if err != nil { + return nil, fmt.Errorf("storing refreshed OAuth2 token: %v", err) + } + } + + return tkn, nil +} diff --git a/oauth2client/browser.go b/oauth2client/browser.go new file mode 100644 index 0000000..b5f78eb --- /dev/null +++ b/oauth2client/browser.go @@ -0,0 +1,137 @@ +package oauth2client + +import ( + "bytes" + "fmt" + "net" + "net/http" + "net/url" + "os/exec" + "runtime" + "strings" +) + +// Browser gets an OAuth2 code via the web browser. +type Browser struct { + // RedirectURL is the URL to redirect the browser + // to after the code is obtained; it is usually a + // loopback address. If empty, DefaultRedirectURL + // will be used instead. + RedirectURL string +} + +// Get opens a browser window to authCodeURL for the user to +// authorize the application, and it returns the resulting +// OAuth2 code. It rejects requests where the "state" param +// does not match expectedStateVal. +func (b Browser) Get(expectedStateVal, authCodeURL string) (string, error) { + redirURLStr := b.RedirectURL + if redirURLStr == "" { + redirURLStr = DefaultRedirectURL + } + redirURL, err := url.Parse(redirURLStr) + if err != nil { + return "", err + } + + ln, err := net.Listen("tcp", redirURL.Host) + if err != nil { + return "", err + } + defer ln.Close() + + ch := make(chan string) + errCh := make(chan error) + + go func() { + http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + state := r.FormValue("state") + code := r.FormValue("code") + + if r.Method != "GET" || r.URL.Path != redirURL.Path || state == "" || code == "" { + http.Error(w, "This endpoint is for OAuth2 callbacks only", http.StatusNotFound) + return + } + + if state != expectedStateVal { + http.Error(w, "invalid state", http.StatusUnauthorized) + errCh <- fmt.Errorf("invalid OAuth2 state; expected '%s' but got '%s'", + expectedStateVal, state) + return + } + + ch <- code + + w.WriteHeader(http.StatusOK) + fmt.Fprintln(w, successBody) + })) + }() + + err = openBrowser(authCodeURL) + if err != nil { + return "", err + } + + select { + case code := <-ch: + return code, nil + case err := <-errCh: + return "", err + } +} + +// openBrowser opens the browser to url. +func openBrowser(url string) error { + osCommand := map[string][]string{ + "darwin": []string{"open"}, + "freebsd": []string{"xdg-open"}, + "linux": []string{"xdg-open"}, + "netbsd": []string{"xdg-open"}, + "openbsd": []string{"xdg-open"}, + "windows": []string{"cmd", "/c", "start"}, + } + + if runtime.GOOS == "windows" { + // escape characters not allowed by cmd + url = strings.Replace(url, "&", `^&`, -1) + } + + all := osCommand[runtime.GOOS] + exe := all[0] + args := all[1:] + + buf := new(bytes.Buffer) + + cmd := exec.Command(exe, append(args, url)...) + cmd.Stdout = buf + cmd.Stderr = buf + err := cmd.Run() + + if err != nil { + return fmt.Errorf("%v: %s", err, buf.String()) + } + + return nil +} + +const successBody = ` + + + OAuth2 Success + + + + +

Code obtained, thank you!

+

+ You may now close this page and return to the application. +

+ + +` + +var _ Getter = Browser{} diff --git a/oauth2client/localapp.go b/oauth2client/localapp.go new file mode 100644 index 0000000..d287329 --- /dev/null +++ b/oauth2client/localapp.go @@ -0,0 +1,57 @@ +package oauth2client + +import ( + "context" + "fmt" + + "golang.org/x/oauth2" +) + +// LocalAppSource implements oauth2.TokenSource for +// OAuth2 client apps that have the client app +// credentials (Client ID and Secret) available +// locally. The OAuth2 provider is accessed directly +// using the OAuth2Config field value. +// +// LocalAppSource values can be ephemeral. +type LocalAppSource struct { + // OAuth2Config is the OAuth2 configuration. + OAuth2Config *oauth2.Config + + // AuthCodeGetter is how the auth code + // is obtained. If not set, a default + // oauth2code.Browser is used. + AuthCodeGetter Getter +} + +// Config returns an OAuth2 config. +func (s LocalAppSource) Config() *oauth2.Config { + return s.OAuth2Config +} + +// Token obtains a token using s.OAuth2Config. +func (s LocalAppSource) Token() (*oauth2.Token, error) { + if s.OAuth2Config == nil { + return nil, fmt.Errorf("missing OAuth2Config") + } + if s.AuthCodeGetter == nil { + s.AuthCodeGetter = Browser{} + } + + cfg := s.Config() + + stateVal := State() + authURL := cfg.AuthCodeURL(stateVal, oauth2.AccessTypeOffline) + + code, err := s.AuthCodeGetter.Get(stateVal, authURL) + if err != nil { + return nil, fmt.Errorf("getting code via browser: %v", err) + } + + ctx := context.WithValue(context.Background(), + oauth2.HTTPClient, httpClient) + + return cfg.Exchange(ctx, code) +} + +var _ App = LocalAppSource{} diff --git a/oauth2client/oauth2.go b/oauth2client/oauth2.go new file mode 100644 index 0000000..39e3203 --- /dev/null +++ b/oauth2client/oauth2.go @@ -0,0 +1,62 @@ +package oauth2client + +import ( + mathrand "math/rand" + "net/http" + "time" + + "golang.org/x/oauth2" +) + +func init() { + mathrand.Seed(time.Now().UnixNano()) +} + +// Getter is a type that can get an OAuth2 auth code. +// It must enforce that the state parameter of the +// redirected request matches expectedStateVal. +type Getter interface { + Get(expectedStateVal, authCodeURL string) (code string, err error) +} + +// State returns a random string suitable as a state value. +func State() string { + return randString(14) +} + +// randString is not safe for cryptographic use. +func randString(n int) string { + const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + b := make([]byte, n) + for i := range b { + b[i] = letterBytes[mathrand.Intn(len(letterBytes))] + } + return string(b) +} + +type ( + // OAuth2Info contains information for obtaining an auth code. + OAuth2Info struct { + StateValue string + AuthCodeURL string + } + + // App provides methods for obtaining an + // OAuth2 config and an initial token. + App interface { + oauth2.TokenSource + Config() *oauth2.Config + } +) + +// httpClient is the HTTP client to use for OAuth2 requests. +var httpClient = &http.Client{ + Timeout: 10 * time.Second, +} + +// DefaultRedirectURL is the default URL to +// which to redirect clients after a code +// has been obtained. Redirect URLs may +// have to be registered with your OAuth2 +// provider. +const DefaultRedirectURL = "http://localhost:8008/oauth2-redirect" diff --git a/oauth2client/oauth2proxy/cmd/oauth2proxy/main.go b/oauth2client/oauth2proxy/cmd/oauth2proxy/main.go new file mode 100644 index 0000000..0e5afd4 --- /dev/null +++ b/oauth2client/oauth2proxy/cmd/oauth2proxy/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "flag" + "log" + "net/http" + + "github.com/BurntSushi/toml" + "github.com/mholt/timeliner/oauth2client/oauth2proxy" + "golang.org/x/oauth2" +) + +func init() { + flag.StringVar(&credentialsFile, "credentials", credentialsFile, "The path to the file containing the OAuth2 app credentials for each provider") + flag.StringVar(&addr, "addr", addr, "The address to listen on") + flag.StringVar(&basePath, "path", basePath, "The base path on which to serve the proxy endpoints") +} + +var ( + credentialsFile = "credentials.toml" + addr = ":7233" + basePath = "/oauth2" +) + +func main() { + flag.Parse() + + if credentialsFile == "" { + log.Fatal("[FATAL] No credentials file specified (use -credentials)") + } + if addr == "" { + log.Fatal("[FATAL] No address specified (use -addr)") + } + + // decode app credentials + var creds oauth2Credentials + md, err := toml.DecodeFile(credentialsFile, &creds) + if err != nil { + log.Fatalf("[FATAL] Decoding credentials file: %v", err) + } + if len(md.Undecoded()) > 0 { + log.Fatalf("[FATAL] Unrecognized key(s) in credentials file: %+v", md.Undecoded()) + } + + // convert them into oauth2.Configs (the structure of + // oauth2.Config as TOML is too verbose for my taste) + oauth2Configs := make(map[string]oauth2.Config) + for id, prov := range creds.Providers { + oauth2Configs[id] = oauth2.Config{ + ClientID: prov.ClientID, + ClientSecret: prov.ClientSecret, + Endpoint: oauth2.Endpoint{ + AuthURL: prov.AuthURL, + TokenURL: prov.TokenURL, + }, + } + log.Println("Provider:", id) + } + + log.Println("Serving OAuth2 proxy on", addr) + + p := oauth2proxy.New(basePath, oauth2Configs) + http.ListenAndServe(addr, p) +} + +type oauth2Credentials struct { + Providers map[string]oauth2ProviderConfig `toml:"providers"` +} + +type oauth2ProviderConfig struct { + ClientID string `toml:"client_id"` + ClientSecret string `toml:"client_secret"` + AuthURL string `toml:"auth_url"` + TokenURL string `toml:"token_url"` +} diff --git a/oauth2client/oauth2proxy/proxy.go b/oauth2client/oauth2proxy/proxy.go new file mode 100644 index 0000000..f593775 --- /dev/null +++ b/oauth2client/oauth2proxy/proxy.go @@ -0,0 +1,191 @@ +package oauth2proxy + +import ( + "encoding/json" + "io" + "io/ioutil" + "net/http" + "net/url" + "path" + "strings" + + "github.com/mholt/timeliner/oauth2client" + "golang.org/x/oauth2" +) + +// New returns a new OAuth2 proxy that serves its endpoints +// under the given basePath and which replaces credentials +// and endpoints with those found in the configs given in +// the providers map. +// +// The map value does not use pointers, so that temporary +// manipulations of the value can occur without modifying +// the original template value. +func New(basePath string, providers map[string]oauth2.Config) http.Handler { + basePath = path.Join("/", basePath) + + proxy := oauth2Proxy{providers: providers} + + mux := http.NewServeMux() + mux.HandleFunc(path.Join(basePath, "auth-code-url"), proxy.handleAuthCodeURL) + mux.HandleFunc(path.Join(basePath, "proxy")+"/", proxy.handleOAuth2) + + return mux +} + +type oauth2Proxy struct { + providers map[string]oauth2.Config +} + +func (proxy oauth2Proxy) handleAuthCodeURL(w http.ResponseWriter, r *http.Request) { + providerID := r.FormValue("provider") + redir := r.FormValue("redirect") + scopes := r.URL.Query()["scope"] + + oauth2CfgCopy, ok := proxy.providers[providerID] + if !ok { + http.Error(w, "unknown service ID", http.StatusBadRequest) + return + } + + // augment the template config with parameters specific to this + // request (this is why it's important that the configs aren't + // pointers; we should be mutating only copies here) + oauth2CfgCopy.Scopes = scopes + oauth2CfgCopy.RedirectURL = redir + + stateVal := oauth2client.State() + url := oauth2CfgCopy.AuthCodeURL(stateVal, oauth2.AccessTypeOffline) + + info := oauth2client.OAuth2Info{ + StateValue: stateVal, + AuthCodeURL: url, + } + + json.NewEncoder(w).Encode(info) +} + +func (proxy oauth2Proxy) handleOAuth2(w http.ResponseWriter, r *http.Request) { + // knead the URL into its two parts: the service + // ID and which endpoint to proxy to + // reqURL := strings.TrimPrefix(r.URL.Path, basePath+"/proxy") + // reqURL = path.Clean(strings.TrimPrefix(reqURL, "/")) + + // we want the last two components of the path + urlParts := strings.Split(r.URL.Path, "/") + if len(urlParts) < 2 { + http.Error(w, "bad path length", http.StatusBadRequest) + return + } + + providerID := urlParts[len(urlParts)-2] + whichEndpoint := urlParts[len(urlParts)-1] + + // get the OAuth2 config matching the service ID + oauth2Config, ok := proxy.providers[providerID] + if !ok { + http.Error(w, "unknown service: "+providerID, http.StatusBadRequest) + return + } + + // figure out which endpoint we'll use for upstream + var upstreamEndpoint string + switch whichEndpoint { + case "auth": + upstreamEndpoint = oauth2Config.Endpoint.AuthURL + case "token": + upstreamEndpoint = oauth2Config.Endpoint.TokenURL + } + + // read the body so we can replace values if necessary + // (don't use r.ParseForm because we need to keep body + // and query string distinct) + reqBodyBytes, err := ioutil.ReadAll(r.Body) //http.MaxBytesReader(w, r.Body, 64*1024)) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // if the request body is form-encoded, replace any + // credential placeholders with the real credentials + var upstreamBody io.Reader + if strings.Contains(r.Header.Get("Content-Type"), "x-www-form-urlencoded") { + bodyForm, err := url.ParseQuery(string(reqBodyBytes)) + if err != nil { + http.Error(w, "error parsing request body", http.StatusBadRequest) + return + } + replaceCredentials(bodyForm, oauth2Config) + upstreamBody = strings.NewReader(bodyForm.Encode()) + } + + // now do the same thing for the query string + qs := r.URL.Query() + replaceCredentials(qs, oauth2Config) + + // make outgoing URL + upstreamURL, err := url.Parse(upstreamEndpoint) + if err != nil { + http.Error(w, "bad upstream URL", http.StatusInternalServerError) + return + } + upstreamURL.RawQuery = qs.Encode() + + // set the real credentials -- this has to be done + // carefully because apparently a lot of OAuth2 + // providers are broken (against RFC 6749), so + // the downstream OAuth2 client lib must be sure + // to set the credentials in the right place, and + // we should be sure to mirror that behavior; + // this means that even though the downstream may + // not have the real client ID and secret, they + // need to provide SOMETHING as bogus placeholder + // values to signal to us where to put the real + // credentials + if r.Header.Get("Authorization") != "" { + r.SetBasicAuth(oauth2Config.ClientID, oauth2Config.ClientSecret) + } + + // prepare the request to upstream + upstream, err := http.NewRequest(r.Method, upstreamURL.String(), upstreamBody) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + upstream.Header = r.Header + delete(upstream.Header, "Content-Length") + + // perform the upstream request + resp, err := http.DefaultClient.Do(upstream) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer resp.Body.Close() + + // copy the upstream headers to the response downstream + for key, vals := range resp.Header { + for _, val := range vals { + w.Header().Add(key, val) + } + } + + // carry over the status code + w.WriteHeader(resp.StatusCode) + + // copy the response body downstream + _, err = io.Copy(w, resp.Body) + if err != nil { + http.Error(w, "writing body: "+err.Error(), http.StatusBadGateway) + return + } +} + +func replaceCredentials(form url.Values, oauth2Config oauth2.Config) { + if form.Get("client_id") != "" { + form.Set("client_id", oauth2Config.ClientID) + } + if form.Get("client_secret") != "" { + form.Set("client_secret", oauth2Config.ClientSecret) + } +} diff --git a/oauth2client/remoteapp.go b/oauth2client/remoteapp.go new file mode 100644 index 0000000..377c6d8 --- /dev/null +++ b/oauth2client/remoteapp.go @@ -0,0 +1,192 @@ +package oauth2client + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + + "golang.org/x/oauth2" +) + +// RemoteAppSource implements oauth2.TokenSource for +// OAuth2 client apps that have their credentials +// (Client ID and Secret, as well as endpoint info) +// stored remotely. Thus, this type obtains tokens +// through a remote proxy that presumably has the +// client app credentials, which it will replace +// before proxying to the provider. +// +// RemoteAppSource values can be ephemeral. +type RemoteAppSource struct { + // How to obtain the auth URL. + // Default: DirectAuthURLMode + AuthURLMode AuthURLMode + + // The URL to the proxy server (its + // address + base path). + ProxyURL string + + // The ID of the OAuth2 provider. + ProviderID string + + // The scopes for which to obtain + // authorization. + Scopes []string + + // The URL to redirect to to finish + // the ceremony. + RedirectURL string + + // How the auth code is obtained. + // If not set, a default + // oauth2code.Browser is used. + AuthCodeGetter Getter +} + +// Config returns an OAuth2 config. +func (s RemoteAppSource) Config() *oauth2.Config { + redirURL := s.RedirectURL + if redirURL == "" { + redirURL = DefaultRedirectURL + } + + return &oauth2.Config{ + ClientID: "placeholder", + ClientSecret: "placeholder", + RedirectURL: redirURL, + Scopes: s.Scopes, + Endpoint: oauth2.Endpoint{ + AuthURL: s.ProxyURL + "/proxy/" + s.ProviderID + "/auth", + TokenURL: s.ProxyURL + "/proxy/" + s.ProviderID + "/token", + }, + } +} + +// Token obtains a token. +func (s RemoteAppSource) Token() (*oauth2.Token, error) { + if s.AuthCodeGetter == nil { + s.AuthCodeGetter = Browser{} + } + if s.AuthURLMode == "" { + s.AuthURLMode = DirectAuthURLMode + } + + cfg := s.Config() + + // obtain a state value and auth URL + var stateVal, authURL string + var err error + switch s.AuthURLMode { + case DirectAuthURLMode: + stateVal, authURL, err = s.getDirectAuthURLFromProxy() + case ProxiedAuthURLMode: + stateVal, authURL, err = s.getProxiedAuthURL(cfg) + default: + return nil, fmt.Errorf("unknown AuthURLMode: %s", s.AuthURLMode) + } + if err != nil { + return nil, err + } + + // now obtain the code + code, err := s.AuthCodeGetter.Get(stateVal, authURL) + if err != nil { + return nil, fmt.Errorf("getting code via browser: %v", err) + } + + // and complete the ceremony + ctx := context.WithValue(context.Background(), + oauth2.HTTPClient, httpClient) + + return cfg.Exchange(ctx, code) +} + +// getDirectAuthURLFromProxy returns an auth URL that goes directly to the +// OAuth2 provider server, but it gets that URL by querying the proxy server +// for what it should be ("DirectAuthURLMode"). +func (s RemoteAppSource) getDirectAuthURLFromProxy() (state string, authURL string, err error) { + redirURL := s.RedirectURL + if redirURL == "" { + redirURL = DefaultRedirectURL + } + + v := url.Values{ + "provider": {s.ProviderID}, + "scope": s.Scopes, + "redirect": {redirURL}, + } + + proxyURL := strings.TrimSuffix(s.ProxyURL, "/") + resp, err := http.Get(proxyURL + "/auth-code-url?" + v.Encode()) + if err != nil { + return "", "", err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return "", "", fmt.Errorf("requesting auth code URL from proxy: HTTP %d: %s", + resp.StatusCode, resp.Status) + } + + var info OAuth2Info + err = json.NewDecoder(resp.Body).Decode(&info) + if err != nil { + return "", "", err + } + + return info.StateValue, info.AuthCodeURL, nil +} + +// getProxiedAuthURL returns an auth URL that goes to the remote proxy ("ProxiedAuthURLMode"). +func (s RemoteAppSource) getProxiedAuthURL(cfg *oauth2.Config) (state string, authURL string, err error) { + state = State() + authURL = cfg.AuthCodeURL(state, oauth2.AccessTypeOffline) + return +} + +// AuthURLMode describes what kind of auth URL a +// RemoteAppSource should obtain. +type AuthURLMode string + +const ( + // DirectAuthURLMode queries the remote proxy to get + // an auth URL that goes directly to the OAuth2 provider + // web page the user must go to in order to obtain + // authorization. Although this mode incurs one extra + // HTTP request (that is not part of the OAuth2 spec, + // it is purely our own), it is perhaps more robust in + // more environments, since the browser will access the + // auth provider's site directly, meaning that any HTML + // or JavaScript on the page that expects HTTPS or a + // certain hostname will be able to function correctly. + DirectAuthURLMode AuthURLMode = "direct" + + // ProxiedAuthURLMode makes an auth URL that goes to + // the remote proxy, not directly to the provider. + // This is perhaps a "purer" approach than + // DirectAuthURLMode, but it may not work if HTML or + // JavaScript on the provider's auth page expects + // a certain scheme or hostname in the page's URL. + // This mode usually works when the proxy is running + // over HTTPS, but this mode may break depending on + // the provider, when the proxy uses HTTP (which + // should only be in dev environments of course). + // + // For example, Google's OAuth2 page will try to set a + // secure-context cookie using JavaScript, which fails + // if the auth page is proxied through a plaintext HTTP + // localhost endpoint, which is what we do during + // development for convenience; the lack of HTTPS caused + // the page to reload infinitely because, even though + // the request was reverse-proxied, the JS on the page + // expected HTTPS. (See my self-congratulatory tweet: + // https://twitter.com/mholt6/status/1078518306045231104) + // Using DirectAuthURLMode is the easiest way around + // this problem. + ProxiedAuthURLMode AuthURLMode = "proxied" +) + +var _ App = RemoteAppSource{} diff --git a/persons.go b/persons.go new file mode 100644 index 0000000..bf980ee --- /dev/null +++ b/persons.go @@ -0,0 +1,75 @@ +package timeliner + +import ( + "database/sql" + "fmt" +) + +// getPerson returns the person mapped to userID on service. +// If the person does not exist, it is created. +func (t *Timeline) getPerson(dataSourceID, userID, name string) (Person, error) { + // first, load the person + var p Person + err := t.db.QueryRow(`SELECT persons.id, persons.name + FROM persons, person_identities + WHERE person_identities.data_source_id=? + AND person_identities.user_id=? + AND persons.id = person_identities.person_id + LIMIT 1`, dataSourceID, userID).Scan(&p.ID, &p.Name) + if err == sql.ErrNoRows { + // person does not exist; create this mapping - TODO: do in a transaction + p = Person{Name: name} + res, err := t.db.Exec(`INSERT INTO persons (name) VALUES (?)`, p.Name) + if err != nil { + return Person{}, fmt.Errorf("adding new person: %v", err) + } + p.ID, err = res.LastInsertId() + if err != nil { + return Person{}, fmt.Errorf("getting person ID: %v", err) + } + _, err = t.db.Exec(`INSERT INTO person_identities + (person_id, data_source_id, user_id) VALUES (?, ?, ?)`, + p.ID, dataSourceID, userID) + if err != nil { + return Person{}, fmt.Errorf("adding new person identity mapping: %v", err) + } + } else if err != nil { + return Person{}, fmt.Errorf("selecting person identity: %v", err) + } + + // now get all the person's identities + rows, err := t.db.Query(`SELECT id, person_id, data_source_id, user_id + FROM person_identities WHERE person_id=?`, p.ID) + if err != nil { + return Person{}, fmt.Errorf("selecting person's known identities: %v", err) + } + defer rows.Close() + for rows.Next() { + var ident PersonIdentity + err := rows.Scan(&ident.ID, &ident.PersonID, &ident.DataSourceID, &ident.UserID) + if err != nil { + return Person{}, fmt.Errorf("loading person's identity: %v", err) + } + p.Identities = append(p.Identities, ident) + } + if err = rows.Err(); err != nil { + return Person{}, fmt.Errorf("scanning identity rows: %v", err) + } + + return p, nil +} + +// Person represents a person. +type Person struct { + ID int64 + Name string + Identities []PersonIdentity +} + +// PersonIdentity is a way to map a user ID on a service to a person. +type PersonIdentity struct { + ID int64 + PersonID string + DataSourceID string + UserID string +} diff --git a/processing.go b/processing.go new file mode 100644 index 0000000..0c63e9c --- /dev/null +++ b/processing.go @@ -0,0 +1,544 @@ +package timeliner + +import ( + "bytes" + "crypto/sha256" + "database/sql" + "encoding/base64" + "fmt" + "io" + "log" + "os" + "sync" + "time" +) + +// beginProcessing starts workers to process items that are +// obtained from ac. It returns a WaitGroup which blocks until +// all workers have finished, and a channel into which the +// service should pipe its items. +func (wc *WrappedClient) beginProcessing(cc concurrentCuckoo, reprocess, integrity bool) (*sync.WaitGroup, chan<- *ItemGraph) { + wg := new(sync.WaitGroup) + ch := make(chan *ItemGraph) + + const workers = 2 // TODO: Make configurable? + for i := 0; i < workers; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + for ig := range ch { + if ig == nil { + continue + } + _, err := wc.processItemGraph(ig, &recursiveState{ + timestamp: time.Now(), + reprocess: reprocess, + integrityCheck: integrity, + seen: make(map[*ItemGraph]int64), + idmap: make(map[string]int64), + cuckoo: cc, + }) + if err != nil { + log.Printf("[ERROR][%s/%s] Processing item graph: %v", + wc.ds.ID, wc.acc.UserID, err) + } + } + }(i) + } + + return wg, ch +} + +type recursiveState struct { + timestamp time.Time + reprocess bool + integrityCheck bool + seen map[*ItemGraph]int64 // value is the item's row ID + idmap map[string]int64 // map an item's service ID to the row ID -- TODO: I don't love this... any better way? + + // the cuckoo filter pointer lives for + // the duration of the entire operation; + // it is often nil, but if it is set, + // then the service-produced ID of each + // item should be added to the filter so + // that a prune can take place when the + // entire operation is complete + cuckoo concurrentCuckoo +} + +func (wc *WrappedClient) processItemGraph(ig *ItemGraph, state *recursiveState) (int64, error) { + // don't visit a node twice + if igID, ok := state.seen[ig]; ok { + return igID, nil + } + + var igRowID int64 + + if ig.Node == nil { + // mark this node as visited + state.seen[ig] = 0 + } else { + // process root node + var err error + igRowID, err = wc.processSingleItemGraphNode(ig.Node, state) + if err != nil { + return 0, fmt.Errorf("processing node of item graph: %v", err) + } + + // mark this node as visited + state.seen[ig] = igRowID + + // map individual items to their row IDs + state.idmap[ig.Node.ID()] = igRowID + + // process all connected nodes + if ig.Edges != nil { + for connectedIG, relations := range ig.Edges { + // if node not yet visited, process it now + connectedIGRowID, visited := state.seen[connectedIG] + if !visited { + connectedIGRowID, err = wc.processItemGraph(connectedIG, state) + if err != nil { + return igRowID, fmt.Errorf("processing node of item graph: %v", err) + } + state.seen[connectedIG] = connectedIGRowID + } + + // store this item's ID for later + state.idmap[connectedIG.Node.ID()] = connectedIGRowID + + // insert relations to this connected node into DB + for _, rel := range relations { + _, err = wc.tl.db.Exec(`INSERT INTO relationships + (from_item_id, to_item_id, directed, label) + VALUES (?, ?, ?, ?)`, + igRowID, connectedIGRowID, !rel.Bidirectional, rel.Label) + if err != nil { + return igRowID, fmt.Errorf("storing item relationship: %v (from_item=%d to_item=%d directed=%t label=%v)", + err, igRowID, connectedIGRowID, !rel.Bidirectional, rel.Label) + } + } + } + } + } + + // process collections, if any + for _, coll := range ig.Collections { + // attach the item's row ID to each item in the collection + // to speed up processing; we won't have to query the database + // again for items that were already processed from the graph + for i, it := range coll.Items { + coll.Items[i].itemRowID = state.idmap[it.Item.ID()] + } + + err := wc.processCollection(coll, state.timestamp) + if err != nil { + return 0, fmt.Errorf("processing collection: %v (original_id=%s)", err, coll.OriginalID) + } + } + + // process raw relations, if any + for _, rr := range ig.Relations { + // get each item's row ID from their data source item ID + fromItemRowID, err := wc.itemRowIDFromOriginalID(rr.FromItemID) + if err == sql.ErrNoRows { + continue // item does not exist in timeline; skip this relation + } + if err != nil { + return 0, fmt.Errorf("querying 'from' item row ID: %v", err) + } + toItemRowID, err := wc.itemRowIDFromOriginalID(rr.ToItemID) + if err == sql.ErrNoRows { + continue // item does not exist in timeline; skip this relation + } + if err != nil { + return 0, fmt.Errorf("querying 'to' item row ID: %v", err) + } + + // store the relation + _, err = wc.tl.db.Exec(`INSERT INTO relationships + (from_item_id, to_item_id, directed, label) + VALUES (?, ?, ?, ?)`, + fromItemRowID, toItemRowID, rr.Bidirectional, rr.Label) + if err != nil { + return 0, fmt.Errorf("storing raw item relationship: %v (from_item=%d to_item=%d directed=%t label=%v)", + err, fromItemRowID, toItemRowID, !rr.Bidirectional, rr.Label) + } + } + + return igRowID, nil +} + +// TODO: is this function useful? +func (wc *WrappedClient) processSingleItemGraphNode(it Item, state *recursiveState) (int64, error) { + if itemID := it.ID(); itemID != "" && state.cuckoo.Filter != nil { + state.cuckoo.Lock() + state.cuckoo.InsertUnique([]byte(itemID)) + state.cuckoo.Unlock() + } + + return wc.storeItemFromService(it, state.timestamp, state.reprocess, state.integrityCheck) +} + +func (wc *WrappedClient) storeItemFromService(it Item, timestamp time.Time, reprocess, integrity bool) (int64, error) { + if it == nil { + return 0, nil + } + + // process this item only one at a time + itemOriginalID := it.ID() + itemLockID := fmt.Sprintf("%s_%d_%s", wc.ds.ID, wc.acc.ID, itemOriginalID) + itemLocks.Lock(itemLockID) + defer itemLocks.Unlock(itemLockID) + + // if there is a data file, prepare to download it + // and get its file name; but don't actually begin + // downloading it until after it is in the DB, since + // we need to know, if we encounter this item later, + // whether it was downloaded successfully; if not, + // like if the download was interrupted and we didn't + // have a chance to clean up, we can overwrite any + // existing file by that name. + rc, err := it.DataFileReader() + if err != nil { + return 0, fmt.Errorf("getting item's data file content stream: %v", err) + } + if rc != nil { + defer rc.Close() + } + + // if the item is already in our DB, load it + var ir ItemRow + if itemOriginalID != "" { + ir, err = wc.loadItemRow(wc.acc.ID, itemOriginalID) + if err != nil { + return 0, fmt.Errorf("checking for item in database: %v", err) + } + if ir.ID > 0 { + // already have it + + if !wc.shouldProcessExistingItem(it, ir, reprocess, integrity) { + return ir.ID, nil + } + + // at this point, we will be replacing the existing + // file, so move it temporarily as a safe measure, + // and also because our filename-generator will not + // allow a file to be overwritten, but we want to + // replace the existing file in this case + if ir.DataFile != nil && rc != nil { + origFile := wc.tl.fullpath(*ir.DataFile) + bakFile := wc.tl.fullpath(*ir.DataFile + ".bak") + err = os.Rename(origFile, bakFile) + if err != nil && !os.IsNotExist(err) { + return 0, fmt.Errorf("temporarily moving data file: %v", err) + } + + // if this function returns with an error, + // restore the original file in case it was + // partially written or something; otherwise + // delete the old file altogether + defer func() { + if err == nil { + err := os.Remove(bakFile) + if err != nil && !os.IsNotExist(err) { + log.Printf("[ERROR] Deleting data file backup: %v", err) + } + } else { + err := os.Rename(bakFile, origFile) + if err != nil && !os.IsNotExist(err) { + log.Printf("[ERROR] Restoring original data file from backup: %v", err) + } + } + }() + } + } + } + + var dataFileName *string + var datafile *os.File + if rc != nil { + datafile, dataFileName, err = wc.tl.openUniqueCanonicalItemDataFile(it, wc.ds.ID) + if err != nil { + return 0, fmt.Errorf("opening output data file: %v", err) + } + defer datafile.Close() + } + + // prepare the item's DB row values + err = wc.fillItemRow(&ir, it, timestamp, dataFileName) + if err != nil { + return 0, fmt.Errorf("assembling item for storage: %v", err) + } + + // TODO: Insert modified time too, if edited locally? + // TODO: On conflict, maybe we just want to ignore -- make this configurable... + _, err = wc.tl.db.Exec(`INSERT INTO items + (account_id, original_id, person_id, timestamp, stored, + class, mime_type, data_text, data_file, data_hash, metadata, + latitude, longitude) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (account_id, original_id) DO UPDATE + SET person_id=?, timestamp=?, stored=?, class=?, mime_type=?, data_text=?, + data_file=?, data_hash=?, metadata=?, latitude=?, longitude=?`, + ir.AccountID, ir.OriginalID, ir.PersonID, ir.Timestamp.Unix(), ir.Stored.Unix(), + ir.Class, ir.MIMEType, ir.DataText, ir.DataFile, ir.DataHash, ir.metaGob, + ir.Latitude, ir.Longitude, + ir.PersonID, ir.Timestamp.Unix(), ir.Stored.Unix(), ir.Class, ir.MIMEType, ir.DataText, + ir.DataFile, ir.DataHash, ir.metaGob, ir.Latitude, ir.Longitude) + if err != nil { + return 0, fmt.Errorf("storing item in database: %v (item_id=%v)", err, ir.OriginalID) + } + + // get the item's row ID (this works regardless of whether + // the last query was an insert or an update) + var itemRowID int64 + err = wc.tl.db.QueryRow(`SELECT id FROM items + WHERE account_id=? AND original_id=? LIMIT 1`, + ir.AccountID, ir.OriginalID).Scan(&itemRowID) + if err != nil && err != sql.ErrNoRows { + return 0, fmt.Errorf("getting item row ID: %v", err) + } + + // if there is a data file, download it and compute its checksum; + // then update the item's row in the DB with its name and checksum + if rc != nil && dataFileName != nil { + h := sha256.New() + err := wc.tl.downloadItemFile(rc, datafile, h) + if err != nil { + return 0, fmt.Errorf("downloading data file: %v (item_id=%v)", err, itemRowID) + } + + // now that download is complete, compute its hash + dfHash := h.Sum(nil) + b64hash := base64.StdEncoding.EncodeToString(dfHash) + + // if the exact same file (byte-for-byte) already exists, + // delete this copy and reuse the existing one + err = wc.tl.replaceWithExisting(dataFileName, b64hash, itemRowID) + if err != nil { + return 0, fmt.Errorf("replacing data file with identical existing file: %v", err) + } + + // save the file's name and hash to confirm it was downloaded successfully + _, err = wc.tl.db.Exec(`UPDATE items SET data_hash=? WHERE id=?`, // TODO: LIMIT 1... + b64hash, itemRowID) + if err != nil { + log.Printf("[ERROR][%s/%s] Updating item's data file hash in DB: %v; cleaning up data file: %s (item_id=%d)", + wc.ds.ID, wc.acc.UserID, err, datafile.Name(), itemRowID) + os.Remove(wc.tl.fullpath(*dataFileName)) + } + } + + return itemRowID, nil +} + +func (wc *WrappedClient) shouldProcessExistingItem(it Item, dbItem ItemRow, reprocess, integrity bool) bool { + // if integrity check is enabled and checksum mismatches, always reprocess + if integrity && dbItem.DataFile != nil && dbItem.DataHash != nil { + datafile, err := os.Open(wc.tl.fullpath(*dbItem.DataFile)) + if err != nil { + log.Printf("[ERROR][%s/%s] Integrity check: opening existing data file: %v; reprocessing (item_id=%d)", + wc.ds.ID, wc.acc.UserID, err, dbItem.ID) + return true + } + defer datafile.Close() + h := sha256.New() + _, err = io.Copy(h, datafile) + if err != nil { + log.Printf("[ERROR][%s/%s] Integrity check: reading existing data file: %v; reprocessing (item_id=%d)", + wc.ds.ID, wc.acc.UserID, err, dbItem.ID) + return true + } + b64hash := base64.StdEncoding.EncodeToString(h.Sum(nil)) + if b64hash != *dbItem.DataHash { + log.Printf("[ERROR][%s/%s] Integrity check: checksum mismatch: expected %s, got %s; reprocessing (item_id=%d)", + wc.ds.ID, wc.acc.UserID, *dbItem.DataHash, b64hash, dbItem.ID) + return true + } + } + + // if modified locally, do not overwrite changes + if dbItem.Modified != nil { + return false + } + + // if a data file is expected, but no completed file exists + // (i.e. its hash is missing), then reprocess to allow download + // to complete successfully this time + if dbItem.DataFile != nil && dbItem.DataHash == nil { + return true + } + + // if service reports hashes/etags and we see that it + // has changed, reprocess + if serviceHash := it.DataFileHash(); serviceHash != nil && + dbItem.Metadata != nil && + dbItem.Metadata.ServiceHash != nil && + !bytes.Equal(serviceHash, dbItem.Metadata.ServiceHash) { + return true + } + + // finally, if the user wants to reprocess anyway, then do so + return reprocess +} + +func (wc *WrappedClient) fillItemRow(ir *ItemRow, it Item, timestamp time.Time, canonicalDataFileName *string) error { + // unpack the item's information into values to use in the row + + ownerID, ownerName := it.Owner() + if ownerID == nil { + ownerID = &wc.acc.UserID // assume current account + } + if ownerName == nil { + empty := "" + ownerName = &empty + } + person, err := wc.tl.getPerson(wc.ds.ID, *ownerID, *ownerName) + if err != nil { + return fmt.Errorf("getting person associated with item: %v", err) + } + + txt, err := it.DataText() + if err != nil { + return fmt.Errorf("getting item text: %v", err) + } + + loc, err := it.Location() + if err != nil { + return fmt.Errorf("getting item location data: %v", err) + } + if loc == nil { + loc = new(Location) // avoid nil pointer dereference below + } + + // metadata (optional) needs to be gob-encoded + metadata, err := it.Metadata() + if err != nil { + return fmt.Errorf("getting item metadata: %v", err) + } + if serviceHash := it.DataFileHash(); serviceHash != nil { + metadata.ServiceHash = serviceHash + } + var metaGob []byte + if metadata != nil { + metaGob, err = metadata.encode() // use special encoding method for massive space savings + if err != nil { + return fmt.Errorf("gob-encoding metadata: %v", err) + } + } + + ir.AccountID = wc.acc.ID + ir.OriginalID = it.ID() + ir.PersonID = person.ID + ir.Timestamp = it.Timestamp() + ir.Stored = timestamp + ir.Class = it.Class() + ir.MIMEType = it.DataFileMIMEType() + ir.DataText = txt + ir.DataFile = canonicalDataFileName + ir.Metadata = metadata + ir.metaGob = metaGob + ir.Location = *loc + + return nil +} + +func (wc *WrappedClient) processCollection(coll Collection, timestamp time.Time) error { + _, err := wc.tl.db.Exec(`INSERT INTO collections + (account_id, original_id, name) VALUES (?, ?, ?) + ON CONFLICT (account_id, original_id) + DO UPDATE SET name=?`, + wc.acc.ID, coll.OriginalID, coll.Name, + coll.Name) + if err != nil { + return fmt.Errorf("inserting collection: %v", err) + } + + // get the collection's row ID, regardless of whether it was inserted or updated + var collID int64 + err = wc.tl.db.QueryRow(`SELECT id FROM collections + WHERE account_id=? AND original_id=? LIMIT 1`, + wc.acc.ID, coll.OriginalID).Scan(&collID) + if err != nil { + return fmt.Errorf("getting existing collection's row ID: %v", err) + } + + // now add all the items + // (TODO: could batch this for faster inserts) + for _, cit := range coll.Items { + if cit.itemRowID == 0 { + itID, err := wc.storeItemFromService(cit.Item, timestamp, false, false) // never reprocess or check integrity here + if err != nil { + return fmt.Errorf("adding item from collection to storage: %v", err) + } + cit.itemRowID = itID + } + + _, err = wc.tl.db.Exec(`INSERT OR IGNORE INTO collection_items + (item_id, collection_id, position) + VALUES (?, ?, ?)`, + cit.itemRowID, collID, cit.Position, cit.Position) + if err != nil { + return fmt.Errorf("adding item to collection: %v", err) + } + } + + return nil +} + +func (wc *WrappedClient) loadItemRow(accountID int64, originalID string) (ItemRow, error) { + var ir ItemRow + var metadataGob []byte + var ts, stored int64 // will convert from Unix timestamp + var modified *int64 + err := wc.tl.db.QueryRow(`SELECT + id, account_id, original_id, person_id, timestamp, stored, + modified, class, mime_type, data_text, data_file, data_hash, + metadata, latitude, longitude + FROM items WHERE account_id=? AND original_id=? LIMIT 1`, accountID, originalID).Scan( + &ir.ID, &ir.AccountID, &ir.OriginalID, &ir.PersonID, &ts, &stored, + &modified, &ir.Class, &ir.MIMEType, &ir.DataText, &ir.DataFile, &ir.DataHash, + &metadataGob, &ir.Latitude, &ir.Longitude) + if err == sql.ErrNoRows { + return ItemRow{}, nil + } + if err != nil { + return ItemRow{}, fmt.Errorf("loading item: %v", err) + } + + // the metadata is gob-encoded; decode it into the struct + ir.Metadata = new(Metadata) + err = ir.Metadata.decode(metadataGob) + if err != nil { + return ItemRow{}, fmt.Errorf("gob-decoding metadata: %v", err) + } + + ir.Timestamp = time.Unix(ts, 0) + ir.Stored = time.Unix(stored, 0) + if modified != nil { + modTime := time.Unix(*modified, 0) + ir.Modified = &modTime + } + + return ir, nil +} + +// itemRowIDFromOriginalID returns an item's row ID from the ID +// associated with the data source of wc, along with its original +// item ID from that data source. If the item does not exist, +// sql.ErrNoRows will be returned. +func (wc *WrappedClient) itemRowIDFromOriginalID(originalID string) (int64, error) { + var rowID int64 + err := wc.tl.db.QueryRow(`SELECT items.id + FROM items, accounts + WHERE items.original_id=? + AND accounts.data_source_id=? + AND items.account_id = accounts.id + LIMIT 1`, originalID, wc.ds.ID).Scan(&rowID) + return rowID, err +} + +// itemLocks is used to ensure that an item +// is not processed twice at the same time. +var itemLocks = newMapMutex() diff --git a/ratelimit.go b/ratelimit.go new file mode 100644 index 0000000..0491053 --- /dev/null +++ b/ratelimit.go @@ -0,0 +1,59 @@ +package timeliner + +import ( + "net/http" + "time" +) + +// RateLimit describes a rate limit. +type RateLimit struct { + RequestsPerHour int + BurstSize int + + ticker *time.Ticker + token chan struct{} +} + +// NewRateLimitedRoundTripper adds rate limiting to rt based on the rate +// limiting policy registered by the data source associated with acc. +func (acc Account) NewRateLimitedRoundTripper(rt http.RoundTripper) http.RoundTripper { + rlKey := acc.DataSourceID + "_" + acc.UserID + + rl, ok := acc.t.rateLimiters[rlKey] + + if !ok && acc.ds.RateLimit.RequestsPerHour > 0 { + secondsBetweenReqs := 60.0 / (float64(acc.ds.RateLimit.RequestsPerHour) / 60.0) + reqInterval := time.Duration(secondsBetweenReqs) * time.Second + + rl.ticker = time.NewTicker(reqInterval) + rl.token = make(chan struct{}, rl.BurstSize) + + for i := 0; i < cap(rl.token); i++ { + rl.token <- struct{}{} + } + go func() { + for range rl.ticker.C { + rl.token <- struct{}{} + } + }() + + acc.t.rateLimiters[rlKey] = rl + } + + return rateLimitedRoundTripper{ + RoundTripper: rt, + token: rl.token, + } +} + +type rateLimitedRoundTripper struct { + http.RoundTripper + token <-chan struct{} +} + +func (rt rateLimitedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + <-rt.token + return rt.RoundTripper.RoundTrip(req) +} + +var rateLimiters = make(map[string]RateLimit) diff --git a/timeliner.go b/timeliner.go new file mode 100644 index 0000000..4510a6f --- /dev/null +++ b/timeliner.go @@ -0,0 +1,133 @@ +// Timeliner - A personal data aggregation utility +// Copyright (C) 2019 Matthew Holt +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +// TODO: Apply license to all files + +package timeliner + +import ( + "context" + "database/sql" + "fmt" + "io" + "log" + mathrand "math/rand" + "sync" + "time" + + cuckoo "github.com/seiflotfy/cuckoofilter" +) + +func init() { + mathrand.Seed(time.Now().UnixNano()) +} + +// Timeline represents an opened timeline repository. +// The zero value is NOT valid; use Open() to obtain +// a valid value. +type Timeline struct { + db *sql.DB + repoDir string + rateLimiters map[string]RateLimit +} + +// Open creates/opens a timeline at the given +// repository directory. Timelines should always +// be Close()'d for a clean shutdown when done. +func Open(repo string) (*Timeline, error) { + db, err := openDB(repo) + if err != nil { + return nil, fmt.Errorf("opening database: %v", err) + } + return &Timeline{ + db: db, + repoDir: repo, + rateLimiters: make(map[string]RateLimit), + }, nil +} + +// Close frees up resources allocated from Open. +func (t *Timeline) Close() error { + for key, rl := range t.rateLimiters { + if rl.ticker != nil { + rl.ticker.Stop() + rl.ticker = nil + } + delete(t.rateLimiters, key) + } + if t.db != nil { + return t.db.Close() + } + return nil +} + +type concurrentCuckoo struct { + *cuckoo.Filter + *sync.Mutex +} + +// Options specifies parameters for listing items from a +// data source. Some data sources may not honor all fields. +type Options struct { + Filename string + Timeframe Timeframe + Checkpoint []byte +} + +// FakeCloser turns an io.Reader into an io.ReadCloser +// where the Close() method does nothing. +func FakeCloser(r io.Reader) io.ReadCloser { + return fakeCloser{r} +} + +type fakeCloser struct { + io.Reader +} + +// Close does nothing except satisfy io.Closer. +func (fc fakeCloser) Close() error { return nil } + +// ctxKey is used for contexts, as recommended by +// https://golang.org/pkg/context/#WithValue. It +// is unexported so values stored by this package +// can only be accessed by this package. +type ctxKey string + +// wrappedClientCtxKey is how the context value is accessed. +var wrappedClientCtxKey ctxKey = "wrapped_client" + +// CheckpointFn is a function that saves a checkpoint. +type CheckpointFn func(checkpoint []byte) error + +// Checkpoint saves a checkpoint for the processing associated +// with the provided context. It overwrites any previous +// checkpoint. Any errors are logged. +func Checkpoint(ctx context.Context, checkpoint []byte) { + wc, ok := ctx.Value(wrappedClientCtxKey).(WrappedClient) + + if !ok { + log.Printf("[ERROR][%s/%s] Checkpoint function not available; got %T", + wc.ds.ID, wc.acc.UserID, wc) + return + } + + _, err := wc.tl.db.Exec(`UPDATE accounts SET checkpoint=? WHERE id=?`, // TODO: LIMIT 1 (see https://github.com/mattn/go-sqlite3/pull/564) + checkpoint, wc.acc.ID) + if err != nil { + log.Printf("[ERROR][%s/%s] Checkpoint: %v", wc.ds.ID, wc.acc.UserID, err) + return + } +} diff --git a/wrappedclient.go b/wrappedclient.go new file mode 100644 index 0000000..4d0d569 --- /dev/null +++ b/wrappedclient.go @@ -0,0 +1,276 @@ +package timeliner + +import ( + "context" + "database/sql" + "fmt" + "log" + "os" + "sync" + "time" + + cuckoo "github.com/seiflotfy/cuckoofilter" +) + +// WrappedClient wraps a Client instance with unexported +// fields that contain necessary state for performing +// data collection operations. Do not craft this type +// manually; use Timeline.NewClient() to obtain one. +type WrappedClient struct { + Client + tl *Timeline + acc Account + ds DataSource +} + +// GetLatest gets the most recent items from wc. It does not prune or +// reprocess; only meant for a quick pull. If there are no items pulled +// yet, all items will be pulled. This is only for data sources that +// support ListItems. +func (wc *WrappedClient) GetLatest(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } + ctx = context.WithValue(ctx, wrappedClientCtxKey, wc) + + // get date of most recent item for this account + var mostRecent int64 + err := wc.tl.db.QueryRow(`SELECT timestamp FROM items + WHERE account_id=? + ORDER BY timestamp DESC + LIMIT 1`, wc.acc.ID).Scan(&mostRecent) + if err != nil && err != sql.ErrNoRows { + return fmt.Errorf("getting most recent item timestamp: %v", err) + } + + // constrain the pull to the recent timeframe + timeframe := Timeframe{} + if mostRecent > 0 { + ts := time.Unix(mostRecent, 0) + timeframe.Since = &ts + } + + wg, ch := wc.beginProcessing(concurrentCuckoo{}, false, false) + + err = wc.Client.ListItems(ctx, ch, Options{ + Timeframe: timeframe, + Checkpoint: wc.acc.checkpoint, + }) + if err != nil { + return fmt.Errorf("getting items from service: %v", err) + } + + wg.Wait() + + // processing completed successfully; clear checkpoint + _, err = wc.tl.db.Exec(`UPDATE accounts SET checkpoint=NULL WHERE id=?`, wc.acc.ID) // TODO: limit 1 + if err != nil { + return fmt.Errorf("processing completed, but error clearing checkpoint: %v", err) + } + wc.acc.checkpoint = nil + + return nil +} + +// GetAll gets all the items using wc. If reprocess is true, items that +// are already in the timeline will be re-processed. If prune is true, +// items that are not listed on the data source by wc will be removed +// from the timeline at the end of the listing. If integrity is true, +// all items that are listed by wc that exist in the timeline and which +// consist of a data file will be opened and checked for integrity; if +// the file has changed, it will be reprocessed. This is only for data +// sources that support ListItems. +func (wc *WrappedClient) GetAll(ctx context.Context, reprocess, prune, integrity bool) error { + if wc.Client == nil { + return fmt.Errorf("no client") + } + if ctx == nil { + ctx = context.Background() + } + ctx = context.WithValue(ctx, wrappedClientCtxKey, wc) + + var cc concurrentCuckoo + if prune { + cc.Filter = cuckoo.NewFilter(10000000) // 10mil = ~16 MB on 64-bit + cc.Mutex = new(sync.Mutex) + } + + wg, ch := wc.beginProcessing(cc, reprocess, integrity) + + err := wc.Client.ListItems(ctx, ch, Options{Checkpoint: wc.acc.checkpoint}) + if err != nil { + return fmt.Errorf("getting items from service: %v", err) + } + + wg.Wait() + + // processing completed successfully; clear checkpoint + _, err = wc.tl.db.Exec(`UPDATE accounts SET checkpoint=NULL WHERE id=?`, wc.acc.ID) // TODO: limit 1 + if err != nil { + return fmt.Errorf("processing completed, but error clearing checkpoint: %v", err) + } + wc.acc.checkpoint = nil + + // commence prune, if requested + if prune { + err := wc.doPrune(cc) + if err != nil { + return fmt.Errorf("processing completed, but error pruning: %v", err) + } + } + + return nil +} + +// Import is like GetAll but for a locally-stored archive or export file that can +// simply be opened and processed, rather than needing to run over a network. See +// the godoc for GetAll. This is only for data sources that support Import. +func (wc *WrappedClient) Import(ctx context.Context, filename string, reprocess, prune, integrity bool) error { + if wc.Client == nil { + return fmt.Errorf("no client") + } + + var cc concurrentCuckoo + if prune { + cc.Filter = cuckoo.NewFilter(10000000) // 10mil = ~16 MB on 64-bit + cc.Mutex = new(sync.Mutex) + } + + wg, ch := wc.beginProcessing(cc, reprocess, integrity) + + err := wc.Client.ListItems(ctx, ch, Options{ + Filename: filename, + Checkpoint: wc.acc.checkpoint, + }) + if err != nil { + return fmt.Errorf("importing: %v", err) + } + + wg.Wait() + + // processing completed successfully; clear checkpoint + _, err = wc.tl.db.Exec(`UPDATE accounts SET checkpoint=NULL WHERE id=?`, wc.acc.ID) // TODO: limit 1 + if err != nil { + return fmt.Errorf("processing completed, but error clearing checkpoint: %v", err) + } + wc.acc.checkpoint = nil + + // commence prune, if requested + if prune { + err := wc.doPrune(cc) + if err != nil { + return fmt.Errorf("processing completed, but error pruning: %v", err) + } + } + + return nil +} + +func (wc *WrappedClient) doPrune(cuckoo concurrentCuckoo) error { + // absolutely do not allow a prune to happen if the account + // has a checkpoint; this is because we don't store the cuckoo + // filter with checkpoints, meaning that the list of items + // that have been seen is INCOMPLETE, and pruning on that + // would lead to data loss. TODO: Find a way to store the + // cuckoo filter with a checkpoint... + var ckpt []byte + err := wc.tl.db.QueryRow(`SELECT checkpoint FROM accounts WHERE id=? LIMIT 1`, + wc.acc.ID).Scan(&ckpt) + if err != nil { + return fmt.Errorf("querying checkpoint: %v", err) + } + if len(ckpt) > 0 { + return fmt.Errorf("checkpoint exists; refusing to prune for fear of incomplete item listing") + } + + // deleting items can't happen while iterating the rows + // since the database table locks; i.e. those two operations + // are in conflict, so we can't do the delete until we + // close the result rows; hence, we have to load each + // item to delete into memory (sigh) and then delete after + // the listing is complete + itemsToDelete, err := wc.listItemsToDelete(cuckoo) + if err != nil { + return fmt.Errorf("listing items to delete: %v", err) + } + + for _, rowID := range itemsToDelete { + err := wc.deleteItem(rowID) + if err != nil { + log.Printf("[ERROR][%s/%s] Deleting item: %v (item_id=%d)", + wc.ds.ID, wc.acc.UserID, err, rowID) + } + } + + return nil +} + +func (wc *WrappedClient) listItemsToDelete(cuckoo concurrentCuckoo) ([]int64, error) { + rows, err := wc.tl.db.Query(`SELECT id, original_id FROM items WHERE account_id=?`, wc.acc.ID) + if err != nil { + return nil, fmt.Errorf("selecting all items from account: %v (account_id=%d)", err, wc.acc.ID) + } + defer rows.Close() + + var itemsToDelete []int64 + for rows.Next() { + var rowID int64 + var originalID string + err := rows.Scan(&rowID, &originalID) + if err != nil { + return nil, fmt.Errorf("scanning item: %v", err) + } + if originalID == "" { + continue + } + cuckoo.Lock() + existsOnService := cuckoo.Lookup([]byte(originalID)) + cuckoo.Unlock() + if !existsOnService { + itemsToDelete = append(itemsToDelete, rowID) + } + } + if err = rows.Err(); err != nil { + return nil, fmt.Errorf("iterating item rows: %v", err) + } + + return itemsToDelete, nil +} + +func (wc *WrappedClient) deleteItem(rowID int64) error { + // before deleting the row, find out whether this item + // has a data file and is the only one referencing it + var count int + var dataFile string + err := wc.tl.db.QueryRow(`SELECT COUNT(*), data_file FROM items + WHERE data_file = (SELECT data_file FROM items + WHERE id=? AND data_file IS NOT NULL + AND data_file != "" LIMIT 1)`, + rowID).Scan(&count, &dataFile) + if err != nil { + return fmt.Errorf("querying count of rows sharing data file: %v", err) + } + + _, err = wc.tl.db.Exec(`DELETE FROM items WHERE id=?`, rowID) // TODO: limit 1 + if err != nil { + return fmt.Errorf("deleting item from DB: %v", err) + } + + if count == 1 { + err := os.Remove(wc.tl.fullpath(dataFile)) + if err != nil { + return fmt.Errorf("deleting associated data file from disk: %v", err) + } + } + + return nil +} + +// DataSourceName returns the name of the data source wc was created from. +func (wc *WrappedClient) DataSourceName() string { return wc.ds.Name } + +// DataSourceID returns the ID of the data source wc was created from. +func (wc *WrappedClient) DataSourceID() string { return wc.ds.ID } + +// UserID returns the ID of the user associated with this client. +func (wc *WrappedClient) UserID() string { return wc.acc.UserID }