├── .gitignore ├── LICENSE ├── README.md ├── docs └── bear.jpg ├── go.mod ├── grizzly ├── go.mod └── grizzly.go └── libgrizzly.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | grizzly/grizzly 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # grizzly 2 | 3 | ![](docs/bear.jpg) 4 | 5 | Extra utilities for [Bear.app](https://bear.app/). 6 | 7 | ## Library 8 | 9 | To use `grizzly` as a library, just do `go get github.com/ruivieira/grizzly` or add it 10 | to your `go.mod`. 11 | 12 | ## CLI 13 | 14 | To use the CLI, just do 15 | 16 | ```shell 17 | $ cd grizlly 18 | $ go build 19 | ``` 20 | 21 | ### CLI commands 22 | 23 | * `-d`, Show duplicate titles and counts 24 | * `-ts`, Suggest tag for given title (based on your data) 25 | * `--tail n`, `--head n`, Show first or last `n` entries, in order 26 | * `-m`, Show all marked text for all notes 27 | * `-u`, Show all notes which are not referenced anywhere 28 | * `-s`, `--search`, Search notes using partial title -------------------------------------------------------------------------------- /docs/bear.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruivieira/grizzly/ef6702bf282d56459640b46cb6a13f32a92bb4f3/docs/bear.jpg -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ruivieira/grizzly 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/jinzhu/gorm v1.9.12 7 | github.com/mattn/go-sqlite3 v2.0.3+incompatible 8 | ) 9 | -------------------------------------------------------------------------------- /grizzly/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ruivieira/grizzly/grizzly 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/jawher/mow.cli v1.1.0 7 | github.com/jbrukh/bayesian v0.0.0-20200318221351-d726b684ca4a 8 | github.com/jinzhu/gorm v1.9.12 9 | github.com/mattn/go-colorable v0.1.6 // indirect 10 | github.com/olekukonko/tablewriter v0.0.4 11 | github.com/ruivieira/color v1.7.0 12 | github.com/ruivieira/grizzly v0.0.0-20200219172227-8301b96bab05 13 | ) 14 | 15 | replace github.com/ruivieira/grizzly v0.0.0-20200219172227-8301b96bab05 => ../ 16 | -------------------------------------------------------------------------------- /grizzly/grizzly.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "regexp" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/jinzhu/gorm" 11 | "github.com/ruivieira/color" 12 | 13 | cli "github.com/jawher/mow.cli" 14 | "github.com/jbrukh/bayesian" 15 | "github.com/olekukonko/tablewriter" 16 | "github.com/ruivieira/grizzly" 17 | ) 18 | 19 | var db *gorm.DB 20 | 21 | func cmdDuplicate(cmd *cli.Cmd) { 22 | cmd.Action = func() { 23 | 24 | var notes []grizzly.NoteDuplicate 25 | grizzly.GetDuplicates(db, ¬es) 26 | 27 | total := 0 28 | for _, note := range notes { 29 | total = total + note.Count - 1 30 | } 31 | 32 | if total > 0 { 33 | table := tablewriter.NewWriter(os.Stdout) 34 | table.SetHeader([]string{"title", "duplicates"}) 35 | 36 | for _, note := range notes { 37 | 38 | table.Append([]string{note.Title, strconv.Itoa(note.Count - 1)}) 39 | } 40 | table.SetFooter([]string{"total", strconv.Itoa(total)}) // Add Footer 41 | table.Render() 42 | 43 | } else { 44 | println("👍 no duplicates found.") 45 | } 46 | } 47 | } 48 | 49 | func cmdNaiveBayes(cmd *cli.Cmd) { 50 | cmd.Spec = "TITLE" 51 | title := cmd.StringArg("TITLE", "", "Title to auto-suggest") 52 | cmd.Action = func() { 53 | var notes []grizzly.NoteTag 54 | grizzly.GetAllWithTags(db, ¬es) 55 | 56 | // unique tags 57 | set := make(map[string]bool) 58 | for _, note := range notes { 59 | for _, tag := range note.Tags { 60 | set[tag] = true 61 | } 62 | } 63 | keys := make([]string, 0) 64 | for k := range set { 65 | keys = append(keys, k) 66 | } 67 | classes := make([]bayesian.Class, 0) 68 | for _, v := range keys { 69 | classes = append(classes, bayesian.Class(v)) 70 | } 71 | classifier := bayesian.NewClassifier(classes...) 72 | // train the classifier 73 | for _, note := range notes { 74 | titleTokens := strings.Split(note.Title, " ") 75 | for _, tag := range note.Tags { 76 | classifier.Learn(titleTokens, bayesian.Class(tag)) 77 | } 78 | } 79 | 80 | scores, _, _ := classifier.LogScores(strings.Split(*title, " ")) 81 | 82 | max := scores[0] // assume first value is the smallest 83 | index := 0 84 | 85 | for i, value := range scores { 86 | if value > max { 87 | max = value 88 | index = i 89 | } 90 | } 91 | 92 | fmt.Printf("Suggest tag for: \"%s\":\n", *title) 93 | fmt.Printf("\t🏷️ %s (score: %f)\n", keys[index], max) 94 | 95 | } 96 | } 97 | 98 | func cmdTail(cmd *cli.Cmd) { 99 | cmd.Spec = "NUMBER" 100 | number := cmd.IntArg("NUMBER", 10, "Number of entries (default 10)") 101 | 102 | cmd.Action = func() { 103 | 104 | var notes []grizzly.NoteTag 105 | grizzly.GetTailWithTags(db, ¬es, *number) 106 | 107 | table := tablewriter.NewWriter(os.Stdout) 108 | table.SetHeader([]string{"id", "title", "tags"}) 109 | 110 | for _, note := range notes { 111 | 112 | table.Append([]string{strconv.Itoa(note.Id), note.Title, strings.Join(note.Tags, ", ")}) 113 | } 114 | table.Render() 115 | 116 | } 117 | } 118 | 119 | func cmdHead(cmd *cli.Cmd) { 120 | cmd.Spec = "NUMBER" 121 | number := cmd.IntArg("NUMBER", 10, "Number of entries (default 10)") 122 | 123 | cmd.Action = func() { 124 | 125 | var notes []grizzly.NoteTag 126 | grizzly.GetHeadWithTags(db, ¬es, *number) 127 | 128 | table := tablewriter.NewWriter(os.Stdout) 129 | table.SetHeader([]string{"id", "title", "tags"}) 130 | 131 | for _, note := range notes { 132 | 133 | table.Append([]string{strconv.Itoa(note.Id), note.Title, strings.Join(note.Tags, ", ")}) 134 | } 135 | table.Render() 136 | 137 | } 138 | } 139 | 140 | func cmdMarkedAll(cmd *cli.Cmd) { 141 | 142 | cmd.Action = func() { 143 | 144 | var notes []grizzly.Note 145 | grizzly.GetAllMarked(db, ¬es) 146 | 147 | r, _ := regexp.Compile("::(.*)::") 148 | cb, _ := regexp.Compile("```[a-z]*\\n[\\s\\S]*?\\n```") 149 | 150 | for _, note := range notes { 151 | // replace code blocks 152 | text := cb.ReplaceAllLiteralString(note.Text, "") 153 | matches := r.FindAllString(text, -1) 154 | var tags string 155 | if note.Tags == nil { 156 | tags = "" 157 | } else { 158 | tags = fmt.Sprintf("🏷️ %s", strings.Join(note.Tags, ", ")) 159 | } 160 | fmt.Printf("[#%d %s] %s\n", note.Id, note.Title, tags) 161 | for _, mark := range matches { 162 | fmt.Printf("\t%s\n", strings.TrimSuffix(strings.TrimPrefix(mark, "::"), "::")) 163 | } 164 | } 165 | 166 | //table := tablewriter.NewWriter(os.Stdout) 167 | //table.SetHeader([]string{"id", "title", "tags"}) 168 | // 169 | //for _, note := range notes { 170 | // 171 | // table.Append([]string{strconv.Itoa(note.Id), note.Title, strings.Join(note.Tags, ", ")}) 172 | //} 173 | //table.Render() 174 | 175 | } 176 | } 177 | 178 | func cmdUnlinked(cmd *cli.Cmd) { 179 | 180 | cmd.Action = func() { 181 | var unlinked []string 182 | grizzly.GetUnlinked(db, &unlinked) 183 | for _, note := range unlinked { 184 | fmt.Printf("bear://x-callback-url/open-note?id=%s\n", note) 185 | } 186 | } 187 | } 188 | 189 | func cmdSearchTitle(cmd *cli.Cmd) { 190 | cmd.Spec = "TITLE" 191 | title := cmd.StringArg("TITLE", "", "Partial title") 192 | cmd.Action = func() { 193 | var notes []grizzly.NoteTag 194 | grizzly.SearchTitles(db, *title, ¬es) 195 | bold := color.New(color.FgWhite, color.Bold) 196 | italic := color.New(color.FgWhite, color.Italic) 197 | for _, note := range notes { 198 | _, _ = bold.Printf(note.Title) 199 | _, _ = italic.Printf("\n🔗 bear://x-callback-url/open-note?id=%s\n┈┈\n", note.Identifier) 200 | } 201 | } 202 | } 203 | 204 | func main() { 205 | 206 | db = grizzly.OpenDB() 207 | defer db.Close() 208 | 209 | // create an app 210 | app := cli.App("grizzly", "Bear.app extra utilities") 211 | 212 | // Define our command structure for usage like this: 213 | app.Command("-d --duplicate", "Find duplicate entries", cmdDuplicate) 214 | app.Command("-m", "Show all marked passages", cmdMarkedAll) 215 | app.Command("-ts --tag-suggest", "Suggest tag for title", cmdNaiveBayes) 216 | app.Command("--tail", "Show oldest notes (by id)", cmdTail) 217 | app.Command("--head", "Show newest notes (by id)", cmdHead) 218 | app.Command("-u --unlinked", "Show unlinked notes", cmdUnlinked) 219 | app.Command("-s --search", "Search notes by partial title", cmdSearchTitle) 220 | 221 | app.Run(os.Args) 222 | } 223 | -------------------------------------------------------------------------------- /libgrizzly.go: -------------------------------------------------------------------------------- 1 | package grizzly 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "log" 7 | "os/user" 8 | "regexp" 9 | "strings" 10 | "time" 11 | 12 | "github.com/jinzhu/gorm" 13 | _ "github.com/jinzhu/gorm/dialects/sqlite" 14 | _ "github.com/mattn/go-sqlite3" 15 | ) 16 | 17 | type NoteTag struct { 18 | Id int 19 | Title string 20 | Tags []string 21 | Identifier string 22 | CreationDate time.Time `gorm:"type:timestamp"` 23 | } 24 | 25 | type Note struct { 26 | Id int 27 | Title string 28 | Text string 29 | Tags []string 30 | Identifier string 31 | } 32 | 33 | func OpenDB() *gorm.DB { 34 | homeDirStr := homeDir() + "/Library/Group Containers/9K33E3U3T4.net.shinyfrog.bear/Application Data/database.sqlite" 35 | db, err := gorm.Open("sqlite3", homeDirStr) 36 | if err != nil { 37 | log.Fatal(err) 38 | } 39 | return db 40 | } 41 | 42 | type NoteDuplicate struct { 43 | Id int 44 | Title string 45 | Count int 46 | } 47 | 48 | func GetAllNotes(db *gorm.DB, notes *[]Note) { 49 | rows, err := db.Raw(` 50 | select n.Z_PK as id, 51 | n.ZTEXT as text, 52 | n.ZTITLE as title, 53 | n.ZUNIQUEIDENTIFIER as identifier, 54 | group_concat(t.ZTITLE) as tags 55 | from ZSFNOTE as n left join Z_7TAGS as tn on n.Z_PK=tn.Z_7NOTES 56 | left join ZSFNOTETAG as t on tn.Z_14TAGS=t.Z_PK 57 | group by id;`).Rows() 58 | defer rows.Close() 59 | if err != nil { 60 | log.Fatal("Could not process query") 61 | } 62 | for rows.Next() { 63 | var note Note 64 | var text sql.NullString 65 | var tagStr sql.NullString 66 | err = rows.Scan(¬e.Id, &text, ¬e.Title, ¬e.Identifier, &tagStr) 67 | if text.Valid { 68 | note.Text = text.String 69 | } 70 | if tagStr.Valid { 71 | note.Tags = strings.Split(tagStr.String, ",") 72 | } 73 | *notes = append(*notes, note) 74 | if err != nil { 75 | log.Fatal(err) 76 | } 77 | } 78 | } 79 | 80 | func GetAllWithTags(db *gorm.DB, notes *[]NoteTag) { 81 | rows, err := db.Raw(` 82 | select n.Z_PK as id, 83 | n.ZTITLE as title, 84 | n.ZUNIQUEIDENTIFIER as identifier, 85 | group_concat(t.ZTITLE) as tags, 86 | n.ZCREATIONDATE 87 | from ZSFNOTE as n left join Z_7TAGS as tn on n.Z_PK=tn.Z_7NOTES 88 | left join ZSFNOTETAG as t on tn.Z_14TAGS=t.Z_PK 89 | where t.ZTITLE is not null 90 | group by id;`).Rows() 91 | defer rows.Close() 92 | if err != nil { 93 | log.Fatal("Could not process query") 94 | } 95 | for rows.Next() { 96 | var note NoteTag 97 | var tagStr sql.NullString 98 | var creationDate sql.NullFloat64 99 | err = rows.Scan(¬e.Id, ¬e.Title, ¬e.Identifier, &tagStr, &creationDate) 100 | if tagStr.Valid { 101 | note.Tags = strings.Split(tagStr.String, ",") 102 | } 103 | if creationDate.Valid { 104 | //note.CreationDate = creationDate.Time 105 | //fmt.Println(creationDate.Time) 106 | seconds, _ := time.ParseDuration(fmt.Sprintf("%fs", creationDate.Float64)) 107 | start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) 108 | fmt.Printf("start: %s, seconds: %d, now: %s\n", start, seconds, start.Add(seconds)) 109 | note.CreationDate = start.Add(seconds) 110 | } 111 | *notes = append(*notes, note) 112 | if err != nil { 113 | log.Fatal(err) 114 | } 115 | } 116 | } 117 | 118 | func GetAllMarked(db *gorm.DB, notes *[]Note) { 119 | db.Raw(` 120 | select n.Z_PK as id, 121 | n.ZTEXT as text, 122 | n.ZTITLE as title, 123 | group_concat(t.ZTITLE) as tags, 124 | n.ZUNIQUEIDENTIFIER as identifier 125 | from ZSFNOTE as n left join Z_7TAGS as tn on n.Z_PK=tn.Z_7NOTES 126 | left join ZSFNOTETAG as t on tn.Z_14TAGS=t.Z_PK 127 | where text like "%::%::%" 128 | group by id;`).Scan(notes) 129 | } 130 | 131 | func GetTailWithTags(db *gorm.DB, notes *[]NoteTag, limit int) { 132 | rows, err := db.Raw(` 133 | select n.Z_PK as id, 134 | n.ZTITLE as title, 135 | n.ZUNIQUEIDENTIFIER as identifier, 136 | group_concat(t.ZTITLE) as tags 137 | from ZSFNOTE as n left join Z_7TAGS as tn on n.Z_PK=tn.Z_7NOTES 138 | left join ZSFNOTETAG as t on tn.Z_14TAGS=t.Z_PK 139 | group by id 140 | order by id asc 141 | limit ?;`, limit).Rows() 142 | defer rows.Close() 143 | if err != nil { 144 | log.Fatal("Could not process query") 145 | } 146 | for rows.Next() { 147 | var note NoteTag 148 | var tagStr sql.NullString 149 | err = rows.Scan(¬e.Id, ¬e.Title, ¬e.Identifier, &tagStr) 150 | if tagStr.Valid { 151 | note.Tags = strings.Split(tagStr.String, ",") 152 | } 153 | *notes = append(*notes, note) 154 | if err != nil { 155 | log.Fatal(err) 156 | } 157 | } 158 | } 159 | 160 | func GetHeadWithTags(db *gorm.DB, notes *[]NoteTag, limit int) { 161 | rows, err := db.Raw(` 162 | select n.Z_PK as id, 163 | n.ZTITLE as title, 164 | n.ZUNIQUEIDENTIFIER as identifier, 165 | group_concat(t.ZTITLE) as tags 166 | from ZSFNOTE as n left join Z_7TAGS as tn on n.Z_PK=tn.Z_7NOTES 167 | left join ZSFNOTETAG as t on tn.Z_14TAGS=t.Z_PK 168 | group by id 169 | order by id desc 170 | limit ?;`, limit).Rows() 171 | defer rows.Close() 172 | if err != nil { 173 | log.Fatal("Could not process query") 174 | } 175 | for rows.Next() { 176 | var note NoteTag 177 | var tagStr sql.NullString 178 | err = rows.Scan(¬e.Id, ¬e.Title, ¬e.Identifier, &tagStr) 179 | if tagStr.Valid { 180 | note.Tags = strings.Split(tagStr.String, ",") 181 | } 182 | *notes = append(*notes, note) 183 | if err != nil { 184 | log.Fatal(err) 185 | } 186 | } 187 | } 188 | 189 | func homeDir() string { 190 | usr, err := user.Current() 191 | if err != nil { 192 | log.Fatal(err) 193 | } 194 | return usr.HomeDir 195 | } 196 | 197 | func GetDuplicates(db *gorm.DB, notes *[]NoteDuplicate) { 198 | db.Raw(` 199 | select Z_PK as id, ZTITLE as title, count(ZTITLE) as count 200 | from ZSFNOTE 201 | group by ZTITLE having ( count > 1 ); 202 | `).Scan(notes) 203 | } 204 | 205 | func GetUnlinked(db *gorm.DB, unlinked *[]string) { 206 | var allNotes []Note 207 | GetAllNotes(db, &allNotes) 208 | reference := make(map[string][]string) 209 | r, _ := regexp.Compile("\\(bear:\\/\\/x-callback-url\\/open-note?(.*)\\)") 210 | idr, _ := regexp.Compile("bear:\\/\\/x-callback-url\\/open-note\\?id=([^&)]*)?") 211 | for _, note := range allNotes { 212 | reference[note.Identifier] = make([]string, 0) 213 | matches := r.FindAllString(note.Text, -1) 214 | for _, mark := range matches { 215 | 216 | idMatches := idr.FindStringSubmatch(mark) 217 | if len(idMatches) >= 2 { 218 | reference[idMatches[1]] = append(reference[idMatches[1]], note.Identifier) 219 | } 220 | 221 | } 222 | } 223 | // filter out entries with no backlinks 224 | for note, backlinks := range reference { 225 | if len(backlinks) == 0 { 226 | *unlinked = append(*unlinked, note) 227 | } 228 | } 229 | } 230 | 231 | func SearchTitles(db *gorm.DB, partialTitle string, notes *[]NoteTag) { 232 | rows, err := db.Raw(`select n.Z_PK as id, 233 | n.ZTITLE as title, 234 | n.ZUNIQUEIDENTIFIER as identifier, 235 | group_concat(t.ZTITLE) as tags 236 | from ZSFNOTE as n left join Z_7TAGS as tn on n.Z_PK=tn.Z_7NOTES 237 | left join ZSFNOTETAG as t on tn.Z_14TAGS=t.Z_PK 238 | where n.ZTITLE like ? 239 | group by id;`, "%"+partialTitle+"%").Rows() 240 | if err != nil { 241 | log.Fatal(err) 242 | } 243 | defer rows.Close() 244 | 245 | for rows.Next() { 246 | var row NoteTag 247 | var tagStr sql.NullString 248 | err = rows.Scan(&row.Id, &row.Title, &row.Identifier, &tagStr) 249 | if tagStr.Valid { 250 | row.Tags = strings.Split(tagStr.String, ",") 251 | } 252 | *notes = append(*notes, row) 253 | if err != nil { 254 | log.Fatal(err) 255 | } 256 | } 257 | 258 | err = rows.Err() 259 | if err != nil { 260 | log.Fatal(err) 261 | } 262 | } 263 | --------------------------------------------------------------------------------