aboutsummaryrefslogtreecommitdiffstats
path: root/hypervideo_dl/extractor/stageplus.py
blob: 4bed4d646a2fdf4d25513589e6304d7b8c57f2eb (plain)
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import json
import uuid

from .common import InfoExtractor
from ..utils import (
    float_or_none,
    traverse_obj,
    try_call,
    unified_timestamp,
    url_or_none,
)


class StagePlusVODConcertIE(InfoExtractor):
    _NETRC_MACHINE = 'stageplus'
    _VALID_URL = r'https?://(?:www\.)?stage-plus\.com/video/(?P<id>vod_concert_\w+)'
    _TESTS = [{
        'url': 'https://www.stage-plus.com/video/vod_concert_APNM8GRFDPHMASJKBSPJACG',
        'playlist_count': 6,
        'info_dict': {
            'id': 'vod_concert_APNM8GRFDPHMASJKBSPJACG',
            'title': 'Yuja Wang plays Rachmaninoff\'s Piano Concerto No. 2 – from Odeonsplatz',
            'description': 'md5:50f78ec180518c9bdb876bac550996fc',
            'artist': ['Yuja Wang', 'Lorenzo Viotti'],
            'upload_date': '20230331',
            'timestamp': 1680249600,
            'release_date': '20210709',
            'release_timestamp': 1625788800,
            'thumbnails': 'count:3',
        },
        'playlist': [{
            'info_dict': {
                'id': 'performance_work_A1IN4PJFE9MM2RJ3CLBMUSJBBSOJAD9O',
                'ext': 'mp4',
                'title': 'Piano Concerto No. 2 in C Minor, Op. 18',
                'description': 'md5:50f78ec180518c9bdb876bac550996fc',
                'upload_date': '20230331',
                'timestamp': 1680249600,
                'release_date': '20210709',
                'release_timestamp': 1625788800,
                'duration': 2207,
                'chapters': 'count:5',
                'artist': ['Yuja Wang'],
                'composer': ['Sergei Rachmaninoff'],
                'album': 'Yuja Wang plays Rachmaninoff\'s Piano Concerto No. 2 – from Odeonsplatz',
                'album_artist': ['Yuja Wang', 'Lorenzo Viotti'],
                'track': 'Piano Concerto No. 2 in C Minor, Op. 18',
                'track_number': 1,
                'genre': 'Instrumental Concerto',
            },
        }],
        'params': {'skip_download': 'm3u8'},
    }]

    # TODO: Prune this after livestream and/or album extractors are added
    _GRAPHQL_QUERY = '''query videoDetailPage($videoId: ID!, $sliderItemsFirst: Int = 24) {
  node(id: $videoId) {
    __typename
    ...LiveConcertFields
    ... on LiveConcert {
      artists {
        edges {
          role {
            ...RoleFields
          }
          node {
            id
            name
            sortName
          }
        }
      }
      isAtmos
      maxResolution
      groups {
        id
        name
        typeDisplayName
      }
      shortDescription
      performanceWorks {
        ...livePerformanceWorkFields
      }
      totalDuration
      sliders {
        ...contentContainerFields
      }
      vodConcert {
        __typename
        id
      }
    }
    ...VideoFields
    ... on Video {
      artists {
        edges {
          role {
            ...RoleFields
          }
          node {
            id
            name
            sortName
          }
        }
      }
      isAtmos
      maxResolution
      isLossless
      description
      productionDate
      takedownDate
      sliders {
        ...contentContainerFields
      }
    }
    ...VodConcertFields
    ... on VodConcert {
      artists {
        edges {
          role {
            ...RoleFields
          }
          node {
            id
            name
            sortName
          }
        }
      }
      isAtmos
      maxResolution
      groups {
        id
        name
        typeDisplayName
      }
      performanceWorks {
        ...PerformanceWorkFields
      }
      shortDescription
      productionDate
      takedownDate
      sliders {
        ...contentContainerFields
      }
    }
  }
}

fragment LiveConcertFields on LiveConcert {
  endTime
  id
  pictures {
    ...PictureFields
  }
  reruns {
    ...liveConcertRerunFields
  }
  publicationLevel
  startTime
  streamStartTime
  subtitle
  title
  typeDisplayName
  stream {
    ...liveStreamFields
  }
  trailerStream {
    ...streamFields
  }
  geoAccessCountries
  geoAccessMode
}

fragment PictureFields on Picture {
  id
  url
  type
}

fragment liveConcertRerunFields on LiveConcertRerun {
  streamStartTime
  endTime
  startTime
  stream {
    ...rerunStreamFields
  }
}

fragment rerunStreamFields on RerunStream {
  publicationLevel
  streamType
  url
}

fragment liveStreamFields on LiveStream {
  publicationLevel
  streamType
  url
}

fragment streamFields on Stream {
  publicationLevel
  streamType
  url
}

fragment RoleFields on Role {
  __typename
  id
  type
  displayName
}

fragment livePerformanceWorkFields on LivePerformanceWork {
  __typename
  id
  artists {
    ...artistWithRoleFields
  }
  groups {
    edges {
      node {
        id
        name
        typeDisplayName
      }
    }
  }
  work {
    ...workFields
  }
}

fragment artistWithRoleFields on ArtistWithRoleConnection {
  edges {
    role {
      ...RoleFields
    }
    node {
      id
      name
      sortName
    }
  }
}

fragment workFields on Work {
  id
  title
  movements {
    id
    title
  }
  composers {
    id
    name
  }
  genre {
    id
    title
  }
}

fragment contentContainerFields on CuratedContentContainer {
  __typename
  ...SliderFields
  ...BannerFields
}

fragment SliderFields on Slider {
  id
  headline
  items(first: $sliderItemsFirst) {
    edges {
      node {
        id
        __typename
        ...AlbumFields
        ...ArtistFields
        ...EpochFields
        ...GenreFields
        ...GroupFields
        ...LiveConcertFields
        ...PartnerFields
        ...PerformanceWorkFields
        ...VideoFields
        ...VodConcertFields
      }
    }
  }
}

fragment AlbumFields on Album {
  artistAndGroupDisplayInfo
  id
  pictures {
    ...PictureFields
  }
  title
}

fragment ArtistFields on Artist {
  id
  name
  roles {
    ...RoleFields
  }
  pictures {
    ...PictureFields
  }
}

fragment EpochFields on Epoch {
  id
  endYear
  pictures {
    ...PictureFields
  }
  startYear
  title
}

fragment GenreFields on Genre {
  id
  pictures {
    ...PictureFields
  }
  title
}

fragment GroupFields on Group {
  id
  name
  typeDisplayName
  pictures {
    ...PictureFields
  }
}

fragment PartnerFields on Partner {
  id
  name
  typeDisplayName
  subtypeDisplayName
  pictures {
    ...PictureFields
  }
}

fragment PerformanceWorkFields on PerformanceWork {
  __typename
  id
  artists {
    ...artistWithRoleFields
  }
  groups {
    edges {
      node {
        id
        name
        typeDisplayName
      }
    }
  }
  work {
    ...workFields
  }
  stream {
    ...streamFields
  }
  vodConcert {
    __typename
    id
  }
  duration
  cuePoints {
    mark
    title
  }
}

fragment VideoFields on Video {
  id
  archiveReleaseDate
  title
  subtitle
  pictures {
    ...PictureFields
  }
  stream {
    ...streamFields
  }
  trailerStream {
    ...streamFields
  }
  duration
  typeDisplayName
  duration
  geoAccessCountries
  geoAccessMode
  publicationLevel
  takedownDate
}

fragment VodConcertFields on VodConcert {
  id
  archiveReleaseDate
  pictures {
    ...PictureFields
  }
  subtitle
  title
  typeDisplayName
  totalDuration
  geoAccessCountries
  geoAccessMode
  trailerStream {
   ...streamFields
  }
  publicationLevel
  takedownDate
}

fragment BannerFields on Banner {
  description
  link
  pictures {
    ...PictureFields
  }
  title
}'''

    _TOKEN = None

    def _perform_login(self, username, password):
        auth = self._download_json('https://audience.api.stageplus.io/oauth/token', None, headers={
            'Content-Type': 'application/json',
            'Origin': 'https://www.stage-plus.com',
        }, data=json.dumps({
            'grant_type': 'password',
            'username': username,
            'password': password,
            'device_info': 'Chrome (Windows)',
            'client_device_id': str(uuid.uuid4()),
        }, separators=(',', ':')).encode(), note='Logging in')

        if auth.get('access_token'):
            self._TOKEN = auth['access_token']

    def _real_initialize(self):
        if self._TOKEN:
            return

        self._TOKEN = try_call(
            lambda: self._get_cookies('https://www.stage-plus.com/')['dgplus_access_token'].value)
        if not self._TOKEN:
            self.raise_login_required()

    def _real_extract(self, url):
        concert_id = self._match_id(url)

        data = self._download_json('https://audience.api.stageplus.io/graphql', concert_id, headers={
            'authorization': f'Bearer {self._TOKEN}',
            'content-type': 'application/json',
            'Origin': 'https://www.stage-plus.com',
        }, data=json.dumps({
            'query': self._GRAPHQL_QUERY,
            'variables': {'videoId': concert_id},
            'operationName': 'videoDetailPage'
        }, separators=(',', ':')).encode())['data']['node']

        metadata = traverse_obj(data, {
            'title': 'title',
            'description': ('shortDescription', {str}),
            'artist': ('artists', 'edges', ..., 'node', 'name'),
            'timestamp': ('archiveReleaseDate', {unified_timestamp}),
            'release_timestamp': ('productionDate', {unified_timestamp}),
        })

        thumbnails = traverse_obj(data, ('pictures', lambda _, v: url_or_none(v['url']), {
            'id': 'name',
            'url': 'url',
        })) or None

        entries = []
        for idx, video in enumerate(traverse_obj(data, (
                'performanceWorks', lambda _, v: v['id'] and url_or_none(v['stream']['url']))), 1):
            formats, subtitles = self._extract_m3u8_formats_and_subtitles(
                video['stream']['url'], video['id'], 'mp4', m3u8_id='hls', query={'token': self._TOKEN})
            entries.append({
                'id': video['id'],
                'formats': formats,
                'subtitles': subtitles,
                'album': metadata.get('title'),
                'album_artist': metadata.get('artist'),
                'track_number': idx,
                **metadata,
                **traverse_obj(video, {
                    'title': ('work', 'title'),
                    'track': ('work', 'title'),
                    'duration': ('duration', {float_or_none}),
                    'chapters': (
                        'cuePoints', lambda _, v: float_or_none(v['mark']) is not None, {
                            'title': 'title',
                            'start_time': ('mark', {float_or_none}),
                        }),
                    'artist': ('artists', 'edges', ..., 'node', 'name'),
                    'composer': ('work', 'composers', ..., 'name'),
                    'genre': ('work', 'genre', 'title'),
                }),
            })

        return self.playlist_result(entries, concert_id, thumbnails=thumbnails, **metadata)