-
Notifications
You must be signed in to change notification settings - Fork 0
/
vogue.js
248 lines (225 loc) · 10.9 KB
/
vogue.js
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import fsp from 'fs/promises';
import fs from "fs"
import fetch from 'node-fetch';
import {pipeline} from "stream"
import { promisify } from 'util';
import cliProgress from "cli-progress";
class Vogue {
constructor (rateLimit, season = null, designer = null) {
this.season = season
if (season != null) {
this.season = season.toLowerCase()
}
this.rateLimit = rateLimit
// Master object
this.showImages = {}
this.designer
if (designer != null) {
this.designer = designer.toLowerCase()
}
this.multibar = new cliProgress.MultiBar({
clearOnComplete: false,
hideCursor: true,
format: '{task} [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | {filename}'
}, cliProgress.Presets.shades_grey)
}
async httpRequest (params) {
try {
let host = 'https://graphql.vogue.com/graphql?query='
let fullUrl = host + params
fullUrl = fullUrl.replace(/\s/g, "%20");
let options = {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Host": "graphql.vogue.com",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
},
referrerPolicy: "origin",
}
const response = await fetch(fullUrl, options)
const json = await response.json()
return json.data
} catch (error) {
console.log(error)
}
}
getAllBrands () {
let allBrands = 'query{allBrands{Brand{name%20slug}}}'
return this.httpRequest()
}
getAllSeasons () {
let allSeasons = 'query{allSeasons{Season{name%20slug}}}'
return this.httpRequest()
}
async getSeasonContent (season) {
let allContent = 'query{ allContent( type: ["FashionShowV2"], first: 1000, filter: { season: { slug:"' + season + '" } }) { Content { id GMTPubDate url title slug _cursor_ ... on FashionShowV2 { instantShow brand { name slug } season { name slug year } photosTout { ... on Image { url } } } } pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }'
return await this.httpRequest(allContent)
}
async getBrandConent(brand) {
let allContent = 'query { allContent(type: ["FashionShowV2"], first: 1000, filter: { brand: { slug: "' + brand + '" } }) { Content { id GMTPubDate url title slug _cursor_ ... on FashionShowV2 { instantShow brand { name slug } season { name slug year } photosTout { ... on Image { url } } } } pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }'
return await this.httpRequest(allContent)
}
async getNextpage(brand, cursor) {
let allContent = 'query { allContent(type: ["FashionShowV2"], first: 100, filter: { brand: { slug: "' + brand + '" } }) { Content { id GMTPubDate url title slug _cursor_ ... on FashionShowV2 { instantShow brand { name slug } season { name slug year } photosTout { ... on Image { url } } } } pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }'
return await this.httpRequest(allContent)
}
async getSeasonBrandCollections (season = null, brand = null, slug) {
let querySlug = slug
if (season != null && brand != null) {
querySlug = season + '/' + brand
}
let collections = 'query{ fashionShowV2(slug: "' + querySlug + '") { GMTPubDate url title slug id instantShow city { name } brand { name slug } season { name slug year } photosTout { ... on Image { url } } review { pubDate body contributor { author { name photosTout { ... on Image { url } } } } } galleries { collection { ... GalleryFragment } atmosphere { ... GalleryFragment } beauty { ... GalleryFragment } detail { ... GalleryFragment } frontRow { ... GalleryFragment } } video { url cneId title } } } fragment GalleryFragment on FashionShowGallery { title meta { ...metaFields } slidesV2 { ... on GallerySlidesConnection { slide { ... on Slide { id credit photosTout { ...imageFields } } ... on CollectionSlide { id type credit title photosTout { ...imageFields } } __typename } } } } fragment imageFields on Image { id url caption credit width height } fragment metaFields on Meta { facebook { title description } twitter { title description } }'
return await this.httpRequest(collections)
}
async parseContent (content) {
let nextCursor = null
if(content.allContent.pageInfo.hasNextPage == true) {
nextCursor = content.allContent.pageInfo.endCursor
// console.log(nextCursor)
}
return content.allContent.Content
}
async parseCollections (collections) {
// TODO: What if there are more galleries?
// collection, atmosphere, beauty, detail, frontRow, video
let galleries = collections.fashionShowV2.galleries
let slides = []
for await(const [ gallery, slide ] of Object.entries(galleries)) {
if(slide != null) {
slides = slides.concat(slide.slidesV2.slide)
}
}
return slides
}
// TODO: Retval typing
async parseImageUrl (image) {
return image.photosTout.url.toString()
}
async downloadImageTest (url, dir, subFolder, designer, number) {
let fileExt = url.split('.').pop()
const streamPipeline = promisify(pipeline)
const response = await fetch(url)
if (!response.ok) throw new Error(`unexpected response ${response.statusText}`)
await streamPipeline(response.body, fs.createWriteStream(`images/${dir}/${subFolder}/${designer}_${number}.${fileExt}`))
return `${designer}_${number}.${fileExt}`
}
async loadFile (fileName, dir, subFolder) {
if (!fs.existsSync(`images/${dir}`)){
fs.mkdirSync(`images/${dir}`)
}
if (!fs.existsSync(`images/${dir}/${subFolder}`)){
fs.mkdirSync(`images/${dir}/${subFolder}`)
}
let fileHandle = await fsp.open(`images/${dir}/${subFolder}/${fileName}`, 'a+')
let fileContents = await fsp.readFile(`images/${dir}/${subFolder}/${fileName}`, 'utf8')
if (fileContents) {
fileContents = fileContents.split(',')
} else {
fileContents = []
}
fileHandle.close()
return fileContents
}
async writeToFile (fileName, dir, subFolder, data, imageUrl) {
try{
await fsp.writeFile(`images/${dir}/${subFolder}/${fileName}`, data)
return `added ${imageUrl} to processed list`
} catch (error) {
throw new Error(`unable to write to file ${error}`)
}
}
// TODO: Add in progress bar
// TODO: Add in folder selection
// TODO: Add in naming selection
// TODO: Setup so you can run commands specifically
// TODO: Fetch all of everything (brands / seasons)
// TODO: Add in specific url or designer / season you want to select
// TODO: Add in terminal output for season / designer to autocomplete?
async run () {
if (this.season != null) {
console.log(`season has been defined, running season collector.....`)
let response = await this.getSeasonContent(this.season)
let seasonArray = await this.parseContent(response)
const seasonBar = this.multibar.create(seasonArray.length, 0, {task: "Designers", filename: this.season})
for (let i = 0; seasonArray.length > i; i++) {
let designer = seasonArray[i].brand.slug
// console.log(`found designer ${designer} processing...`)
let season = seasonArray[i].season.slug
// console.log(`found season ${season} processing...`)
seasonBar.update(i, {filename: designer})
let collections = await this.getSeasonBrandCollections(null, null, seasonArray[i].slug)
try {
let images = await this.parseCollections(collections)
let fileName = `${designer}_${season}.txt`
const imageBar = this.multibar.create(images.length, 0, {task: "Images"})
for (let j = 0; images.length > j; j++) {
let imageUrl = await this.parseImageUrl(images[j])
let fileContents = await this.loadFile(fileName, season, designer)
if (fileContents.includes(imageUrl)) {
// console.log('we already have the file skipping...')
imageBar.update(j, {filename: `skipping ${imageUrl}`})
continue
}
// console.log(`downloading ${imageUrl}...`)
let image = await this.downloadImageTest(imageUrl, season, designer, designer, j)
fileContents.push(imageUrl)
// console.log(await this.writeToFile(fileName, season, designer, fileContents, imageUrl))
// console.log(`waiting ${this.rateLimit}...`)
imageBar.update(j, {filename: imageUrl})
await this.sleep(this.rateLimit)
}
this.multibar.remove(imageBar)
} catch (error) {
console.error(`there was an error with fetching the collections ${error}`)
seasonBar.update(i, {filename: season})
continue
}
}
} else if (this.designer != null) {
console.log(`designer has been defined, running designer collector.....`)
let response = await this.getBrandConent(this.designer)
let brandSeasonArray = await this.parseContent(response)
const seasonBar = this.multibar.create(brandSeasonArray.length, 0, {task: "Seasons", filename: this.designer})
for (let i = 0; brandSeasonArray.length > i; i++) {
let designer = brandSeasonArray[i].brand.slug
// console.log(`found designer ${designer} processing...`)
let season = brandSeasonArray[i].season.slug
// console.log(`found season ${season} processing...`)
seasonBar.update(i, {filename: season})
let collections = await this.getSeasonBrandCollections(null, null, brandSeasonArray[i].slug)
try {
let images = await this.parseCollections(collections)
let fileName = `${designer}_${season}.txt`
const imageBar = this.multibar.create(images.length, 0, {task: "Images"})
for (let j = 0; images.length > j; j++) {
let imageUrl = await this.parseImageUrl(images[j])
let fileContents = await this.loadFile(fileName, designer, season)
if (fileContents.includes(imageUrl)) {
// console.log('we already have the file skipping...')
imageBar.update(j, {filename: `skipping ${imageUrl}`})
continue
}
// console.log(`downloading ${imageUrl}...`)
let image = await this.downloadImageTest(imageUrl, designer, season, designer, j)
fileContents.push(imageUrl)
// console.log(await this.writeToFile(fileName, designer, season, fileContents, imageUrl))
// console.log(`waiting ${this.rateLimit}...`)
imageBar.update(j, {filename: imageUrl})
await this.sleep(this.rateLimit)
}
this.multibar.remove(imageBar)
} catch (error) {
console.error(`there was an error with fetching the collections ${error}`)
seasonBar.update(i, {filename: season})
continue
}
}
}
this.multibar.stop()
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
export default Vogue;