-
Notifications
You must be signed in to change notification settings - Fork 0
/
updateRecentMovies.go
220 lines (197 loc) · 6.15 KB
/
updateRecentMovies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"os"
"path"
"regexp"
"strings"
"text/template"
"github.com/spf13/cobra"
"github.com/timothyrenner/movies-app/database"
)
// updateMoviesCmd represents the updateMovies command
var updateRecentMoviesCmd = &cobra.Command{
Use: "update-recent-movies",
Short: "Runs the data pipeline for pulling movies.",
Long: `Pulls new movie watches from the vault and updates the local database.
Hydrates the movies with additional info from OMDB if required.
`,
Run: updateRecentMovies,
Args: cobra.RangeArgs(1, 1),
}
var WATCHED_DATE_EXTRACTOR *regexp.Regexp = regexp.MustCompile(
`watched::\s*\[\[(\d{4}-\d{2}-\d{2})\]\]`,
)
var IMDB_ID_EXTRACTOR *regexp.Regexp = regexp.MustCompile(
`imdb_id::\s+(tt\d{7})`,
)
func GetMovieTitleFromWatchFile(fileContents []byte) (string, error) {
matches := WATCHED_DATE_EXTRACTOR.FindSubmatch(fileContents)
if len(matches) != 2 {
return "", errors.New("unable to match watched date")
}
return string(matches[1]), nil
}
func GetMovieImdbIdFromWatchFile(fileContents []byte) (string, error) {
matches := IMDB_ID_EXTRACTOR.FindSubmatch(fileContents)
if len(matches) != 2 {
return "", errors.New("unable to match watched date")
}
return string(matches[1]), nil
}
func updateRecentMovies(cmd *cobra.Command, args []string) {
vaultDir := args[0]
checkAll, err := cmd.Flags().GetBool("check-all")
if err != nil {
log.Panicf("Error getting value of check-all: %v", err)
}
if OMDB_KEY == "" {
log.Panic("OMDB_KEY must be present for this script to run.")
}
omdbClient := NewOmdbClient(OMDB_KEY)
ctx := context.Background()
db, err := sql.Open("sqlite3", DB)
if err != nil {
log.Panicf("Error opening database %v: %v", DB, err)
}
defer db.Close()
queries := database.New(db)
latestMovieWatchRow, err := queries.GetLatestMovieWatchDate(ctx)
if err != nil {
log.Panicf("Error getting latest movie watch date: %v", err)
}
// Panics if the conversion doesn't work.
latestMovieWatch := latestMovieWatchRow.(string)
newMovieWatchFiles := make([]string, 0)
allWatches, err := os.ReadDir(path.Join(vaultDir, "Watches"))
if err != nil {
log.Panicf("Error reading dir %v", path.Join(vaultDir, "Watches"))
}
for ii := range allWatches {
watchDate := strings.Split(allWatches[ii].Name(), " ")[0]
if !checkAll && (watchDate < latestMovieWatch) {
continue
} else {
newMovieWatchFiles = append(
newMovieWatchFiles,
path.Join(vaultDir, "Watches", allWatches[ii].Name()),
)
}
}
log.Printf("Found %v possibly new watches", len(newMovieWatchFiles))
// Initialize the parser.
movieWatchParser, err := CreateMovieWatchParser()
if err != nil {
log.Panicf("Error creating movie watch parser: %v", err)
}
// Initialize the template for movie pages.
movieTemplate, err := template.New("movie").Parse(MOVIE_TEMPLATE)
if err != nil {
log.Panicf("Unable to parse movie template: %v", err)
}
newMovies := 0
for ii := range newMovieWatchFiles {
watchFile := newMovieWatchFiles[ii]
// Parse the watch file.
log.Printf("Parsing %v", watchFile)
movieWatchPage, err := movieWatchParser.ParsePage(watchFile)
if err != nil {
log.Panicf("Error parsing page %v: %v", watchFile, err)
}
// Determine if it's already in the database.
movieWatchUuid, err := queries.FindMovieWatch(
ctx, database.FindMovieWatchParams{
ImdbID: movieWatchPage.ImdbId,
Watched: movieWatchPage.Watched,
},
)
if err == sql.ErrNoRows {
log.Println("Movie watch not found.")
} else if err != nil {
log.Panicf("Encountered error obtaining movie watch: %v", err)
}
// If there's a uuid for the movie watch in the database, skip it.
if movieWatchUuid != "" {
log.Printf(
"Already found %v - %v in database, skipping.",
movieWatchPage.Title, movieWatchPage.Watched,
)
continue
}
// See if the movie and details are already in the database.
movieUuid, err := queries.FindMovie(ctx, movieWatchPage.ImdbId)
if err == sql.ErrNoRows {
log.Println("Movie not found. Creating.")
} else if err != nil {
log.Panicf("Error finding movie: %v", err)
}
// If the movie's not in the database, we need to insert it and the
// details.
if movieUuid == "" {
log.Printf("Fetching %v from OMDB.", movieWatchPage.Title)
omdbResponse, err := omdbClient.GetMovie(movieWatchPage.ImdbId)
if err != nil {
log.Panicf("Error fetching movie from OMDB: %v", err)
}
moviePage, err := CreateMoviePage(omdbResponse, movieWatchPage)
if err != nil {
log.Panicf("Error creating movie page: %v", err)
}
movieDetailUuids, err := InsertMovieDetails(
db, ctx, queries, moviePage, omdbResponse.Ratings,
)
if err != nil {
log.Panicf(
"Error inserting movie details into database: %v", err,
)
}
movieUuid = movieDetailUuids.Movie
moviePageFileName := fmt.Sprintf(
"%v (%v).md", movieWatchPage.FileTitle, movieWatchPage.ImdbId,
)
moviePageFilePath := path.Join(vaultDir, "Movies", moviePageFileName)
moviePageFile, skipMovie, err := createOrOpenFile(
false, moviePageFilePath,
)
if err != nil {
log.Panicf("Error opening file %v: %v", moviePageFilePath, err)
}
defer moviePageFile.Close()
if !skipMovie {
log.Printf("Creating page %v", moviePageFileName)
if err := movieTemplate.Execute(
moviePageFile, moviePage,
); err != nil {
log.Panicf(
"Error writing movie page %v: %v",
moviePageFilePath, err,
)
}
} else {
log.Printf("Page %v already exists, skipping.", moviePageFileName)
}
moviePageFile.Close()
}
// Now that we have a movie uuid for the foreign key we can insert the
// movie watch itself.
movieWatchParams := CreateInsertMovieWatchParams(movieWatchPage, movieUuid)
if err := queries.InsertMovieWatch(ctx, *movieWatchParams); err != nil {
log.Panicf("Error inserting movie watch into database: %v", err)
}
newMovies += 1
}
log.Printf("Completed. Inserted %v new movie watches.", newMovies)
}
func init() {
rootCmd.AddCommand(updateRecentMoviesCmd)
updateRecentMoviesCmd.Flags().BoolP(
"check-all", "c", false, "Whether to check all the movie watches or not.",
)
}