webtoon 0.9.0

Client for interacting with various webtoon websites.
Documentation
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
//! Represents a client abstraction for `webtoons.com`.

pub(super) mod likes;
pub(super) mod posts;
pub mod search;

use crate::stdx::http::{DEFAULT_USER_AGENT, IRetry};

use super::{
    Language, Type, Webtoon,
    canvas::{self, Sort},
    creator::{self, Creator},
    errors::{
        CanvasError, ClientError, CreatorError, OriginalsError, PostError, SearchError,
        WebtoonError,
    },
    meta::Scope,
    originals::{self},
    webtoon::episode::{
        Episode,
        posts::{Post, Reaction},
    },
};
use anyhow::{Context, anyhow};
use parking_lot::RwLock;
use posts::id::Id;
use reqwest::Response;
use search::Item;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{collections::HashMap, ops::RangeBounds, str::FromStr, sync::Arc};

/// A builder for configuring and creating instances of [`Client`] with custom settings.
///
/// The `ClientBuilder` provides an API for fine-tuning various aspects of the `Client`
/// configuration and custom user agents. It enables a more controlled construction
/// of the `Client` when the default configuration isn't sufficient.
///
/// # Usage
///
/// The builder allows for method chaining to incrementally configure the client, with the final
/// step being a call to [`build()`](ClientBuilder::build()), which consumes the builder and returns a [`Client`].
///
/// # Example
///
/// ```
/// # use webtoon::platform::webtoons::ClientBuilder;
/// let client = ClientBuilder::new()
///     .user_agent("custom-agent/1.0")
///     .build()?;
/// # Ok::<(), webtoon::platform::webtoons::errors::ClientError>(())
/// ```
///
/// # Notes
///
/// This builder is the preferred way to create clients when needing custom configurations, and
/// should be used instead of `Client::new()` for more advanced setups.
#[derive(Debug)]
pub struct ClientBuilder {
    builder: reqwest::ClientBuilder,
    session: Option<Arc<str>>,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ClientBuilder {
    /// Creates a new `ClientBuilder` with default settings.
    ///
    /// This includes a default user agent (`$CARGO_PKG_NAME/$CARGO_PKG_VERSION`), and is the starting point for configuring a `Client`.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::ClientBuilder;
    /// let builder = ClientBuilder::new();
    /// ```
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        let builder = reqwest::Client::builder()
            .user_agent(DEFAULT_USER_AGENT)
            .use_rustls_tls()
            .https_only(true)
            .brotli(true);

        Self {
            builder,
            session: None,
        }
    }

    /// Configures the `ClientBuilder` to use the specified session token for authentication.
    ///
    /// This method is useful when creating a `Client` that needs to make authenticated requests. The session token will
    /// be included in all subsequent requests made by the resulting `Client`, where needed.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use webtoon::platform::webtoons::ClientBuilder;
    /// let builder = ClientBuilder::new().with_session("session-token");
    /// ```
    #[inline]
    #[must_use]
    pub fn with_session(mut self, session: &str) -> Self {
        self.session = Some(Arc::from(session));
        self
    }

    /// Sets a custom `User-Agent` header for the [`Client`].
    ///
    /// By default, the user agent is set to (`$CARGO_PKG_NAME/$CARGO_PKG_VERSION`), but this can be overridden using this method.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::ClientBuilder;
    /// let builder = ClientBuilder::new().user_agent("custom-agent/1.0");
    /// ```
    #[inline]
    #[must_use]
    pub fn user_agent(self, user_agent: &str) -> Self {
        let builder = self.builder.user_agent(user_agent);
        Self { builder, ..self }
    }

    /// Consumes the `ClientBuilder` and returns a fully-configured [`Client`].
    ///
    /// This method finalizes the configuration of the `ClientBuilder` and attempts to build
    /// a `Client` based on the current settings. If there are issues with the underlying
    /// configuration (e.g., TLS backend failure or resolver issues), an error is returned.
    ///
    /// # Errors
    ///
    /// This method returns a [`ClientError`] if the underlying HTTP client could not be built,
    /// such as when TLS initialization fails or the DNS resolver cannot load the system configuration.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use webtoon::platform::webtoons::{ClientBuilder, Client};
    /// let client: Client = ClientBuilder::new().build()?;
    /// # Ok::<(), webtoon::platform::webtoons::errors::ClientError>(())
    /// ```
    pub fn build(self) -> Result<Client, ClientError> {
        Ok(Client {
            http: self
                .builder
                .build()
                .map_err(|err| ClientError::Unexpected(err.into()))?,
            session: self.session,
        })
    }
}

/// A high-level, asynchronous client to interact with `webtoons.com`.
///
/// The `Client` is designed for efficient, reusable interactions, and internally
/// manages connection pooling for optimal performance.
///
/// # Configuration
///
/// Default settings for the `Client` are tuned for general usage scenarios, but you can
/// customize the behavior by utilizing the `Client::builder()` method, which provides
/// advanced configuration options.
///
/// # Example
///
/// ```
/// # use webtoon::platform::webtoons::Client;
/// let client = Client::new();
/// ```
#[derive(Debug, Clone)]
pub struct Client {
    pub(super) http: reqwest::Client,
    pub(super) session: Option<Arc<str>>,
}

// Creation impls
impl Client {
    /// Instantiates a new [`Client`] with the default user agent: (`$CARGO_PKG_NAME/$CARGO_PKG_VERSION`).
    ///
    /// This method configures a basic `Client` with standard settings. If default
    /// configurations are sufficient, this is the simplest way to create a `Client`.
    ///
    /// # Panics
    ///
    /// This function will panic if the TLS backend cannot be initialized or if the DNS resolver
    /// fails to load the system's configuration. For a safer alternative that returns a `Result`
    /// instead of panicking, consider using the [`ClientBuilder`] for more controlled error handling.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::Client;
    /// let client = Client::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        ClientBuilder::new().build().expect("Client::new()")
    }

    /// Instantiates a new [`Client`] with a provided session token, allowing authenticated requests.
    ///
    /// Use this method when you have an active session that you wish to reuse for API calls requiring
    /// authentication. This allows the client to automatically include the session in requests.
    ///
    /// # Panics
    ///
    /// This function will panic if the TLS backend cannot be initialized or if the DNS resolver
    /// fails to load the system's configuration. For a safer alternative that returns a `Result`
    /// instead of panicking, consider using the [`ClientBuilder`] for more controlled error handling.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::Client;
    /// let client = Client::with_session("my-session-token");
    /// ```
    #[inline]
    #[must_use]
    pub fn with_session(session: &str) -> Self {
        ClientBuilder::new()
            .with_session(session)
            .build()
            .expect("Client::with_session()")
    }

    /// Returns a [`ClientBuilder`] for creating a custom-configured `Client`.
    ///
    /// The builder pattern allows for greater flexibility in configuring a `Client`.
    /// You can specify other options by chaining methods on the builder before finalizing it with [`ClientBuilder::build()`].
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{Client, ClientBuilder};
    /// let builder: ClientBuilder = Client::builder();
    /// ```
    #[inline]
    #[must_use]
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }
}

// Public facing impls
impl Client {
    /// Fetches info for the [`Creator`] of a given `profile`.
    ///
    /// The `profile` can be found from the community page URL: [`https://www.webtoons.com/p/community/en/u/w7m5o`]
    ///
    /// **NOTE**: Not all Webtoon creators have a community page. This is usually denoted by green check mark next to
    /// their name on the Webtoon's page.
    ///
    /// # Supported & Unsupported Languages
    ///
    /// Some languages, such as French (`fr`), German (`de`), and Chinese (`zh-hant`), do not currently
    /// support creator pages. As a result, this method will return an error, specifically
    /// [`CreatorError::UnsupportedLanguage`], when a creator page is requested in these languages.
    ///
    /// For languages where a creator page is supported, the function returns an `Option<Creator>`:
    ///
    /// - `Ok(Some(creator))`: A valid creator profile page was found, and the returned `Creator`
    ///   can be used for further interactions.
    /// - `Ok(None)`: No creator profile page exists for the given `profile` in the selected
    ///   supported language. In this case, even though the language is supported, the creator
    ///   does not have a profile page.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{Client, Language, errors::{Error, CreatorError}};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// match client.creator("w7m5o", Language::En).await {
    ///     Ok(Some(creator)) => println!("Creator found: {creator:?}"),
    ///     Ok(None) => unreachable!("profile is known to exist"),
    ///     Err(CreatorError::UnsupportedLanguage) => println!("This language does not support creator profiles."),
    ///     Err(err) => panic!("An error occurred: {err:?}"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`https://www.webtoons.com/p/community/en/u/w7m5o`]: https://www.webtoons.com/p/community/en/u/w7m5o
    pub async fn creator(
        &self,
        profile: &str,
        language: Language,
    ) -> Result<Option<Creator>, CreatorError> {
        if matches!(language, Language::Zh | Language::De | Language::Fr) {
            return Err(CreatorError::UnsupportedLanguage);
        }

        let Some(page) = creator::page(language, profile, self).await? else {
            return Ok(None);
        };

        Ok(Some(Creator {
            client: self.clone(),
            language,
            profile: Some(profile.into()),
            username: page.username.clone(),
            page: Arc::new(RwLock::new(Some(page))),
        }))
    }

    /// Searches for Webtoons on `webtoons.com`.
    ///
    /// This method performs a search on the Webtoons platform using the provided query string and [`Language`].
    /// It returns a list of [`Item`] that match the search criteria.
    ///
    /// # Notes
    ///
    /// - The search query is case-insensitive and will return webtoons that partially or fully match the provided string.
    /// - The search is specific to the language provided in the `language` parameter. Only webtoons available in the chosen language will be returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{Client, Language, errors::Error};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let search = client.search("Monsters And", Language::En).await?;
    ///
    /// for webtoon in search {
    ///     println!("Webtoon: {}", webtoon.title());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::too_many_lines)]
    pub async fn search(&self, query: &str, language: Language) -> Result<Vec<Item>, SearchError> {
        if query.is_empty() {
            return Ok(Vec::new());
        }

        let mut webtoons = Vec::new();

        let lang = match language {
            Language::En => "ENGLISH",
            Language::Zh => "TRADITIONAL_CHINESE",
            Language::Th => "THAI",
            Language::Id => "INDONESIAN",
            Language::Es => "SPANISH",
            Language::Fr => "FRENCH",
            Language::De => "GERMAN",
        };

        // nextSize max is 50. Anything else is a BAD_REQUEST.
        // contentSubType:
        // - ALL
        // - CHALLENGE
        // - WEBTOON
        let url = format!(
            "https://www.webtoons.com/p/api/community/v1/content/TITLE/GW/search?criteria=KEYWORD_SEARCH&contentSubType=WEBTOON&nextSize=50&language={lang}&query={query}"
        );

        let response = self.http.get(&url).retry().send().await?;

        let api = serde_json::from_str::<search::Api>(&response.text().await?)
            .context("Failed to deserialize search api response")?;

        let Some(originals) = api.result.webtoon_title_list else {
            return Err(SearchError::Unexpected(anyhow!(
                "Original search result didnt have `webtoonTitleList` field in result"
            )));
        };

        for data in originals.data {
            let id: u32 = data
                .content_id
                .parse()
                .context("Failed to parse webtoon id to u32")?;

            let webtoon = Item {
                client: self.clone(),
                id,
                r#type: Type::Original,
                title: data.name,
                thumbnail: format!("https://swebtoon-phinf.pstatic.net{}", data.thumbnail.path),
                creator: data.extra.writer.nickname,
            };

            webtoons.push(webtoon);
        }

        let mut next = originals.pagination.next;
        while let Some(ref cursor) = next {
            let url = format!(
                "https://www.webtoons.com/p/api/community/v1/content/TITLE/GW/search?criteria=KEYWORD_SEARCH&contentSubType=WEBTOON&nextSize=50&language={lang}&query={query}&cursor={cursor}"
            );

            let response = self.http.get(&url).retry().send().await?;

            let api = serde_json::from_str::<search::Api>(&response.text().await?)
                .context("Failed to deserialize search api response")?;

            let Some(originals) = api.result.webtoon_title_list else {
                return Err(SearchError::Unexpected(anyhow!(
                    "Original search result didnt have `webtoonTitleList` field in result"
                )));
            };

            for data in originals.data {
                let id: u32 = data
                    .content_id
                    .parse()
                    .context("Failed to parse webtoon id to u32")?;

                let webtoon = Item {
                    client: self.clone(),
                    id,
                    r#type: Type::Original,
                    title: data.name,
                    thumbnail: format!("https://swebtoon-phinf.pstatic.net{}", data.thumbnail.path),
                    creator: data.extra.writer.nickname,
                };

                webtoons.push(webtoon);
            }
            next = originals.pagination.next;
        }

        let url = format!(
            "https://www.webtoons.com/p/api/community/v1/content/TITLE/GW/search?criteria=KEYWORD_SEARCH&contentSubType=CHALLENGE&nextSize=50&language={lang}&query={query}"
        );

        let response = self.http.get(&url).retry().send().await?;

        let api = serde_json::from_str::<search::Api>(&response.text().await?)
            .context("Failed to deserialize search api response")?;

        let Some(canvas) = api.result.challenge_title_list else {
            return Err(SearchError::Unexpected(anyhow!(
                "Canvas search result didnt have `challengeTitleList` field in result"
            )));
        };

        for data in canvas.data {
            let id: u32 = data
                .content_id
                .parse()
                .context("Failed to parse webtoon id to u32")?;

            let webtoon = Item {
                client: self.clone(),
                id,
                r#type: Type::Canvas,
                title: data.name,
                thumbnail: format!("https://swebtoon-phinf.pstatic.net{}", data.thumbnail.path),
                creator: data.extra.writer.nickname,
            };

            webtoons.push(webtoon);
        }

        let mut next = canvas.pagination.next;
        while let Some(ref cursor) = next {
            let url = format!(
                "https://www.webtoons.com/p/api/community/v1/content/TITLE/GW/search?criteria=KEYWORD_SEARCH&contentSubType=CHALLENGE&nextSize=50&language={lang}&query={query}&cursor={cursor}"
            );

            let response = self.http.get(&url).retry().send().await?;

            let api = serde_json::from_str::<search::Api>(&response.text().await?)
                .context("Failed to deserialize search api response")?;

            let Some(canvas) = api.result.challenge_title_list else {
                return Err(SearchError::Unexpected(anyhow!(
                    "Canvas search result didnt have `challengeTitleList` field in result"
                )));
            };

            for data in canvas.data {
                let id: u32 = data
                    .content_id
                    .parse()
                    .context("Failed to parse webtoon id to u32")?;

                let webtoon = Item {
                    client: self.clone(),
                    id,
                    r#type: Type::Canvas,
                    title: data.name,
                    thumbnail: format!("https://swebtoon-phinf.pstatic.net{}", data.thumbnail.path),
                    creator: data.extra.writer.nickname,
                };

                webtoons.push(webtoon);
            }
            next = canvas.pagination.next;
        }

        Ok(webtoons)
    }

    /// Retrieves a list of all `original` webtoons for the specified [`Language`] from `webtoons.com`.
    ///
    /// This corresponds to all webtoons found at `https://www.webtoons.com/*/originals`.
    ///
    /// # Language Support
    ///
    /// The `originals` section of the Webtoons site is available in different languages, and
    /// the `language` parameter allows you to specify which language version of the site to
    /// scrape. This determines the set of webtoons returned in the list.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{ Client, Language, errors::Error};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let originals = client.originals(Language::En).await?;
    ///
    /// for webtoon in originals {
    ///     println!("Webtoon: {:?}", webtoon.title().await?);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn originals(&self, language: Language) -> Result<Vec<Webtoon>, OriginalsError> {
        originals::scrape(self, language).await
    }

    /// Retrieves a list of `canvas` webtoons for the specified [`Language`] from `webtoons.com`.
    ///
    /// This corresponds to all webtoons found at `https://www.webtoons.com/*/canvas`.
    ///
    /// # Language Support
    ///
    /// The `canvas` section is available in multiple languages, and the `language` parameter
    /// determines which language version of the site is scraped.
    ///
    /// # Pagination and Sorting
    ///
    /// You can specify which pages to scrape using the `pages` parameter, which accepts any
    /// valid range (e.g., `1..5` for pages 1 through 4). The `sort` parameter allows you to
    /// control how the results are ordered:
    ///
    /// - `Sort::Popularity`: Orders by read count.
    /// - `Sort::Likes`: Orders by the number of likes.
    /// - `Sort::Date`: Orders by the most recent updates.
    ///
    /// # Notes
    ///
    /// The list of Canvas webtoons can vary between languages, and the sorting order may impact
    /// the results significantly.
    ///
    /// Due to limitations of how `webtoons.com` responds to the request, there is no way to know if the page requested
    /// exists(No more pages). In the interest of sane defaults, an unbounded end is equal to `..100`. If not, this function would never return.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{ Client, Language, errors::Error, canvas::Sort};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let webtoons = client
    ///     .canvas(Language::En, 1..=3, Sort::Popularity)
    ///     .await?;
    ///
    /// for webtoon in webtoons {
    ///     println!("Webtoon: {}", webtoon.title().await?);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn canvas(
        &self,
        language: Language,
        pages: impl RangeBounds<u16> + Send,
        sort: Sort,
    ) -> Result<Vec<Webtoon>, CanvasError> {
        canvas::scrape(self, language, pages, sort).await
    }

    /// Constructs a [`Webtoon`] from the given `id` and [`Type`].
    ///
    /// Both sides, `canvas` and `original`, have separate sets of `id`'s. This means that an original and a canvas story
    /// could have the same numerical id. The `id`'s are unique across languages though, so this method supports any language.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{errors::Error, Type, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let Some(webtoon) = client.webtoon(95, Type::Original).await? else {
    ///     unreachable!("webtoon is known to exist");
    /// };
    ///
    /// assert_eq!("Tower of God", webtoon.title().await?);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn webtoon(&self, id: u32, r#type: Type) -> Result<Option<Webtoon>, WebtoonError> {
        let url = format!(
            "https://www.webtoons.com/*/{}/*/list?title_no={id}",
            match r#type {
                Type::Original => "*",
                Type::Canvas => "canvas",
            }
        );

        let response = self.http.get(&url).retry().send().await?;

        // Webtoon doesn't exist
        if response.status() == 404 {
            return Ok(None);
        }

        let mut segments = response
            .url()
            .path_segments()
            .ok_or(WebtoonError::InvalidUrl(
                "Webtoon url should have segments separated by `/`; this url did not.",
            ))?;

        let segment = segments
            .next()
            .ok_or(WebtoonError::InvalidUrl(
                "Webtoon URL was found to have segments, but for some reason failed to extract that first segment, which should be a language code: e.g `en`",
            ))?;

        let language = Language::from_str(segment)
            .context("Failed to parse return URL segment into `Language` enum")?;

        let segment = segments.next().ok_or(
                WebtoonError::InvalidUrl("Url was found to have segments, but didn't have a second segment, representing the scope of the webtoon.")
            )?;

        let scope = Scope::from_str(segment) //
            .context("Failed to parse URL scope path to a `Scope`")?;

        let slug = segments
            .next()
            .ok_or( WebtoonError::InvalidUrl( "Url was found to have segments, but didn't have a third segment, representing the slug name of the Webtoon."))?
            .to_string();

        let webtoon = Webtoon {
            client: self.clone(),
            id,
            language,
            scope,
            slug: Arc::from(slug),
            page: Arc::new(RwLock::new(None)),
        };

        Ok(Some(webtoon))
    }

    /// Constructs a [`Webtoon`] from a given `url`.
    ///
    /// # URL Structure
    ///
    /// The provided `url` must follow the typical structure used by `webtoons.com`:
    ///
    /// - `https://www.webtoons.com/{language}/{scope}/{slug}/list?title_no={id}`
    ///
    /// It is assumed that the webtoon will always exist given the URL. This simplifies usage and cleans up boilerplate.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let webtoon = client
    ///     .webtoon_from_url("https://www.webtoons.com/en/action/omniscient-reader/list?title_no=2154")?;
    ///
    /// assert_eq!("Omniscient Reader",  webtoon.title().await?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn webtoon_from_url(&self, url: &str) -> Result<Webtoon, WebtoonError> {
        let url = url::Url::parse(url)?;

        let mut segments = url.path_segments().ok_or(WebtoonError::InvalidUrl(
            "Webtoon url should have segments separated by `/`; this url did not.",
        ))?;

        let segment = segments
            .next()
            .ok_or(WebtoonError::InvalidUrl(
                "Webtoon URL was found to have segments, but for some reason failed to extract that first segment, which should be a language code: e.g `en`",
            ))?;

        let language = Language::from_str(segment)
            .context("Failed to parse URL language code into `Language` enum")?;

        let segment = segments.next().ok_or(
                WebtoonError::InvalidUrl("Url was found to have segments, but didn't have a second segment, representing the scope of the webtoon.")
            )?;

        let scope = Scope::from_str(segment) //
            .context("Failed to parse URL scope path to a `Scope`")?;

        let slug = segments
            .next()
            .ok_or( WebtoonError::InvalidUrl( "Url was found to have segments, but didn't have a third segment, representing the slug name of the Webtoon."))?
            .to_string();

        let id = url
            .query()
            .ok_or(WebtoonError::InvalidUrl(
                "Webtoon URL should have a `title_no` query: failed to find one in provided URL.",
            ))?
            .split('=')
            .nth(1)
            .context("`title_no` should always have a `=` separator")?
            .parse::<u32>()
            .context("`title_no` query parameter wasn't able to parse into a u32")?;

        let webtoon = Webtoon {
            client: self.clone(),
            language,
            scope,
            slug: Arc::from(slug),
            id,
            page: Arc::new(RwLock::new(None)),
        };

        Ok(webtoon)
    }

    /// Returns a [`UserInfo`] derived from a passed in session.
    ///
    /// This can be useful if you need to get the profile or username from the session alone.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// // When no session, or an invalid session, is passed in, `is_logged_in()` will be false.
    /// let user_info = client.user_info_for_session("session").await?;
    ///
    /// assert!(!user_info.is_logged_in());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn user_info_for_session(&self, session: &str) -> Result<UserInfo, ClientError> {
        let response = self
            .http
            .get("https://www.webtoons.com/en/member/userInfo")
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        let user_info: UserInfo = serde_json::from_str(&response.text().await?).map_err(|err| {
            ClientError::Unexpected(anyhow!("failed to deserialize `userInfo` endpoint: {err}"))
        })?;

        Ok(user_info)
    }

    /// Returns if the `Client` was provided a session.
    ///
    /// This does **NOT** mean session is valid.
    ///
    /// # Example
    ///
    /// ```
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    /// assert!(!client.has_session());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn has_session(&self) -> bool {
        self.session.is_some()
    }

    /// Tries to validate the current session.
    ///
    /// - `true` if the session is proven valid.
    /// - `false` if the session is proven invalid.
    ///
    /// <div class="warning">
    ///
    /// **This is mainly provided for a quick early return for when the circumstances allow. Any methods that use a
    /// session should not rely on the session always being valid after this check; The session could be invalidated
    /// after the check completes!**
    ///
    /// </div>
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::with_session("session");
    /// assert!(!client.has_valid_session().await?);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn has_valid_session(&self) -> Result<bool, ClientError> {
        let Some(session) = &self.session else {
            return Err(ClientError::NoSessionProvided);
        };

        let user_info = self.user_info_for_session(session).await?;

        Ok(user_info.is_logged_in)
    }
}

// Internal only impls
impl Client {
    pub(super) async fn get_originals_page(
        &self,
        lang: Language,
        day: &str,
    ) -> Result<Response, ClientError> {
        let url = format!("https://www.webtoons.com/{lang}/originals/{day}");
        let response = self.http.get(&url).retry().send().await?;

        Ok(response)
    }

    pub(super) async fn get_canvas_page(
        &self,
        lang: Language,
        page: u16,
        sort: Sort,
    ) -> Result<Response, ClientError> {
        let url = format!(
            "https://www.webtoons.com/{lang}/canvas/list?genreTab=ALL&sortOrder={sort}&page={page}"
        );

        let response = self.http.get(&url).retry().send().await?;

        Ok(response)
    }

    pub(super) async fn get_creator_page(
        &self,
        lang: Language,
        profile: &str,
    ) -> Result<Response, ClientError> {
        let url = format!("https://www.webtoons.com/p/community/{lang}/u/{profile}");

        let response = self.http.get(&url).retry().send().await?;

        Ok(response)
    }

    pub(super) async fn get_webtoon_page(
        &self,
        webtoon: &Webtoon,
        page: Option<u16>,
    ) -> Result<Response, ClientError> {
        let id = webtoon.id;
        let lang = webtoon.language;
        let scope = webtoon.scope.as_slug();
        let slug = &webtoon.slug;

        let url = if let Some(page) = page {
            format!("https://www.webtoons.com/{lang}/{scope}/{slug}/list?title_no={id}&page={page}")
        } else {
            format!("https://www.webtoons.com/{lang}/{scope}/{slug}/list?title_no={id}")
        };

        let response = self.http.get(&url).retry().send().await?;

        Ok(response)
    }

    pub(super) async fn post_subscribe_to_webtoon(
        &self,
        webtoon: &Webtoon,
    ) -> Result<(), ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let session = self.session.as_ref().unwrap();

        let mut form = HashMap::new();
        form.insert("titleNo", webtoon.id.to_string());
        form.insert("currentStatus", false.to_string());

        let url = match webtoon.scope {
            Scope::Original(_) => "https://www.webtoons.com/setFavorite",
            Scope::Canvas => "https://www.webtoons.com/challenge/setFavorite",
        };

        self.http
            .post(url)
            .header("Referer", "https://www.webtoons.com/")
            .header("Service-Ticket-Id", "epicom")
            .header("Cookie", format!("NEO_SES={session}"))
            .form(&form)
            .retry()
            .send()
            .await?;

        Ok(())
    }

    pub(super) async fn post_unsubscribe_to_webtoon(
        &self,
        webtoon: &Webtoon,
    ) -> Result<(), ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let session = self.session.as_ref().unwrap();

        let mut form = HashMap::new();
        form.insert("titleNo", webtoon.id.to_string());
        form.insert("currentStatus", true.to_string());

        let url = match webtoon.scope {
            Scope::Original(_) => "https://www.webtoons.com/setFavorite",
            Scope::Canvas => "https://www.webtoons.com/challenge/setFavorite",
        };

        self.http
            .post(url)
            .header("Referer", "https://www.webtoons.com/")
            .header("Service-Ticket-Id", "epicom")
            .header("Cookie", format!("NEO_SES={session}"))
            .form(&form)
            .retry()
            .send()
            .await?;

        Ok(())
    }

    pub(super) async fn get_episodes_dashboard(
        &self,
        webtoon: &Webtoon,
        page: u16,
    ) -> Result<Response, ClientError> {
        let Some(session) = &self.session else {
            return Err(ClientError::NoSessionProvided);
        };

        let id = webtoon.id;

        let url = format!(
            "https://www.webtoons.com/*/challenge/dashboardEpisode?titleNo={id}&page={page}"
        );

        let response = self
            .http
            .get(&url)
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        Ok(response)
    }

    pub(super) async fn get_stats_dashboard(
        &self,
        webtoon: &Webtoon,
    ) -> Result<Response, ClientError> {
        let Some(session) = &self.session else {
            return Err(ClientError::NoSessionProvided);
        };

        let lang = webtoon.language;
        let scope = match webtoon.scope {
            Scope::Canvas => "challenge",
            Scope::Original(_) => "*",
        };
        let id = webtoon.id;

        let url = format!(r"https://www.webtoons.com/{lang}/{scope}/titleStat?titleNo={id}");

        let response = self
            .http
            .get(&url)
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        Ok(response)
    }

    #[cfg(feature = "rss")]
    pub(super) async fn get_rss_for_webtoon(
        &self,
        webtoon: &Webtoon,
    ) -> Result<Response, ClientError> {
        let id = webtoon.id;
        let language = webtoon.language;
        let slug = &webtoon.slug;

        let scope = match webtoon.scope {
            Scope::Original(genre) => genre.as_slug(),
            Scope::Canvas => "challenge",
        };

        let url = format!("https://www.webtoons.com/{language}/{scope}/{slug}/rss?title_no={id}");

        let response = self.http.get(url).send().await?;

        Ok(response)
    }

    pub(super) async fn get_episode(
        &self,
        webtoon: &Webtoon,
        episode: u16,
    ) -> Result<Response, ClientError> {
        let id = webtoon.id;
        let scope = webtoon.scope.as_slug();

        // Language isn't needed
        let url = format!(
            "https://www.webtoons.com/*/{scope}/*/*/viewer?title_no={id}&episode_no={episode}"
        );

        let response = self.http.get(&url).retry().send().await?;

        Ok(response)
    }

    pub(super) async fn get_likes_for_episode(
        &self,
        episode: &Episode,
    ) -> Result<Response, ClientError> {
        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .unwrap_or_default();

        let scope = match episode.webtoon.scope {
            Scope::Original(_) => "w",
            Scope::Canvas => "c",
        };
        let webtoon = episode.webtoon.id;
        let episode = episode.number;

        let url = format!(
            "https://www.webtoons.com/api/v1/like/search/counts?serviceId=LINEWEBTOON&contentIds={scope}_{webtoon}_{episode}"
        );

        let response = self
            .http
            .get(&url)
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        Ok(response)
    }

    pub(super) async fn like_episode(&self, episode: &Episode) -> Result<(), ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let session = self
            .session
            .as_ref()
            .ok_or(ClientError::NoSessionProvided)?;

        let webtoon = episode.webtoon.id;
        let r#type = episode.webtoon.scope.as_single_letter();
        let number = episode.number;

        let response = self.get_react_token().await?;

        if response.success {
            let token = response
                .result
                .guest_token
                .context("`guestToken` should be some if `success` is true")?;
            let timestamp = response
                .result
                .timestamp
                .context("`timestamp` should be some if `success` is true")?;

            let language = episode.webtoon.language;

            let url = format!(
                "https://www.webtoons.com/api/v1/like/services/LINEWEBTOON/contents/{type}_{webtoon}_{number}?menuLanguageCode={language}&timestamp={timestamp}&guestToken={token}"
            );

            self.http
                .post(&url)
                .header("Cookie", format!("NEO_SES={session}"))
                .retry()
                .send()
                .await?;
        }

        Ok(())
    }

    pub(super) async fn unlike_episode(&self, episode: &Episode) -> Result<(), ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let session = self
            .session
            .as_ref()
            .ok_or(ClientError::NoSessionProvided)?;

        let webtoon = episode.webtoon.id;
        let r#type = episode.webtoon.scope.as_single_letter();
        let number = episode.number;

        let response = self.get_react_token().await?;

        if response.success {
            let token = response
                .result
                .guest_token
                .context("`guestToken` should be some if `success` is true")?;

            let timestamp = response
                .result
                .timestamp
                .context("`timestamp` should be some if `success` is true")?;

            let language = episode.webtoon.language;

            let url = format!(
                "https://www.webtoons.com/api/v1/like/services/LINEWEBTOON/contents/{type}_{webtoon}_{number}?menuLanguageCode={language}&timestamp={timestamp}&guestToken={token}"
            );

            self.http
                .delete(&url)
                .header("Cookie", format!("NEO_SES={session}"))
                .retry()
                .send()
                .await?;
        }

        Ok(())
    }

    pub(super) async fn get_posts_for_episode(
        &self,
        episode: &Episode,
        cursor: Option<Id>,
        stride: u8,
    ) -> Result<Response, ClientError> {
        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .unwrap_or_default();

        let scope = match episode.webtoon.scope {
            Scope::Original(_) => "w",
            Scope::Canvas => "c",
        };

        let webtoon = episode.webtoon.id;

        let episode = episode.number;

        let cursor = cursor.map_or_else(String::new, |id| id.to_string());

        let url = format!(
            "https://www.webtoons.com/p/api/community/v2/posts?pageId={scope}_{webtoon}_{episode}&pinRepresentation=none&prevSize=0&nextSize={stride}&cursor={cursor}&withCursor=true"
        );

        let response = self
            .http
            .get(&url)
            .header("Service-Ticket-Id", "epicom")
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        Ok(response)
    }

    pub(super) async fn get_upvotes_and_downvotes_for_post(
        &self,
        post: &Post,
    ) -> Result<Response, ClientError> {
        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .unwrap_or_default();

        let page_id = format!(
            "{}_{}_{}",
            match post.episode.webtoon.scope {
                Scope::Original(_) => "w",
                Scope::Canvas => "c",
            },
            post.episode.webtoon.id,
            post.episode.number
        );

        let url = format!(
            "https://www.webtoons.com/p/api/community/v2/reaction/post_like/channel/{page_id}/content/{}/emotion/count",
            post.id
        );

        let response = self
            .http
            .get(&url)
            .header("Service-Ticket-Id", "epicom")
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        Ok(response)
    }

    pub(super) async fn get_replies_for_post(
        &self,
        post: &Post,
        cursor: Option<Id>,
        stride: u8,
    ) -> Result<Response, ClientError> {
        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .unwrap_or_default();

        let post_id = post.id;

        let cursor = cursor.map_or_else(String::new, |id| id.to_string());

        let url = format!(
            "https://www.webtoons.com/p/api/community/v2/post/{post_id}/child-posts?sort=oldest&displayBlindCommentAsService=false&prevSize=0&nextSize={stride}&cursor={cursor}&withCursor=false"
        );

        let response = self
            .http
            .get(&url)
            .header("Service-Ticket-Id", "epicom")
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        Ok(response)
    }

    pub(super) async fn post_reply(
        &self,
        post: &Post,
        body: &str,
        is_spoiler: bool,
    ) -> Result<(), ClientError> {
        let page_id = format!(
            "{}_{}_{}",
            match post.episode.webtoon.scope {
                Scope::Original(_) => "w",
                Scope::Canvas => "c",
            },
            post.episode.webtoon.id,
            post.episode.number
        );

        let parent_id = post.id.to_string();

        let spoiler_filter = if is_spoiler { "ON" } else { "OFF" };
        let body = json![
            {
                "pageId": page_id,
                "parentId": parent_id,
                "settings": { "reply": "OFF", "reaction": "ON", "spoilerFilter": spoiler_filter },
                "title":"",
                "body": body
            }
        ];

        let token = self.get_api_token().await?;

        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .ok_or(ClientError::NoSessionProvided)?;

        self.http
            .post("https://www.webtoons.com/p/api/community/v2/post")
            .json(&body)
            .header("Api-Token", token.clone())
            .header("Cookie", format!("NEO_SES={session}"))
            .header("Service-Ticket-Id", "epicom")
            .retry()
            .send()
            .await?;

        Ok(())
    }

    pub(super) async fn delete_post(&self, post: &Post) -> Result<(), PostError> {
        let token = self.get_api_token().await?;

        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .ok_or(ClientError::NoSessionProvided)?;

        self.http
            .delete(format!(
                "https://www.webtoons.com/p/api/community/v2/post/{}",
                post.id
            ))
            .header("Api-Token", token.clone())
            .header("Cookie", format!("NEO_SES={session}"))
            .header("Service-Ticket-Id", "epicom")
            .retry()
            .send()
            .await?;

        Ok(())
    }

    pub(super) async fn put_react_to_post(
        &self,
        post: &Post,
        reaction: Reaction,
    ) -> Result<(), PostError> {
        let page_id = format!(
            "{}_{}_{}",
            match post.episode.webtoon.scope {
                Scope::Original(_) => "w",
                Scope::Canvas => "c",
            },
            post.episode.webtoon.id,
            post.episode.number
        );

        let url = match reaction {
            Reaction::Upvote => format!(
                "https://www.webtoons.com/p/api/community/v2/reaction/post_like/channel/{page_id}/content/{}/emotion/like",
                post.id
            ),
            Reaction::Downvote => format!(
                "https://www.webtoons.com/p/api/community/v2/reaction/post_like/channel/{page_id}/content/{}/emotion/dislike",
                post.id
            ),
            Reaction::None => unreachable!("Should never be used with `Reaction::None`"),
        };

        let token = self.get_api_token().await?;

        let session = self
            .session
            .as_ref()
            .map(|session| session.as_ref())
            .ok_or(ClientError::NoSessionProvided)?;

        self.http
            .put(&url)
            .header("Service-Ticket-Id", "epicom")
            .header("Referer", "https://www.webtoons.com/")
            .header("Cookie", format!("NEO_SES={session}"))
            .header("Api-Token", token.clone())
            .retry()
            .send()
            .await?;

        Ok(())
    }

    pub(super) async fn get_user_info_for_webtoon(
        &self,
        webtoon: &Webtoon,
    ) -> Result<WebtoonUserInfo, ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let Some(session) = &self.session else {
            return Err(ClientError::NoSessionProvided);
        };

        let url = match webtoon.scope {
            Scope::Original(_) => format!(
                "https://www.webtoons.com/getTitleUserInfo?titleNo={}",
                webtoon.id
            ),
            Scope::Canvas => {
                format!(
                    "https://www.webtoons.com/canvas/getTitleUserInfo?titleNo={}",
                    webtoon.id
                )
            }
        };

        let response = self
            .http
            .get(&url)
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        let text = response.text().await?;

        let title_user_info = serde_json::from_str(&text).context(text)?;

        Ok(title_user_info)
    }

    async fn get_react_token(&self) -> Result<ReactToken, ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let Some(session) = &self.session else {
            return Err(ClientError::NoSessionProvided);
        };

        let response = self
            .http
            .get("https://www.webtoons.com/api/v1/like/react-token")
            .header("Cookie", format!("NEO_SES={session}"))
            .header("Referer", "https://www.webtoons.com")
            .retry()
            .send()
            .await?;

        let text = response.text().await?;

        let api_token = serde_json::from_str::<ReactToken>(&text).context(text)?;

        Ok(api_token)
    }

    pub(super) async fn get_api_token(&self) -> Result<String, ClientError> {
        if !self.has_valid_session().await? {
            return Err(ClientError::InvalidSession);
        };

        let Some(session) = &self.session else {
            return Err(ClientError::NoSessionProvided);
        };

        let response = self
            .http
            .get("https://www.webtoons.com/p/api/community/v1/api-token")
            .header("Cookie", format!("NEO_SES={session}"))
            .retry()
            .send()
            .await?;

        let text = response.text().await?;

        let api_token = serde_json::from_str::<ApiToken>(&text).context(text)?;

        Ok(api_token.result.token)
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

/// Represents data from the `webtoons.com/*/member/userInfo` endpoint.
///
/// This can be used to get the username and profile, as well as check if user is logged in. This type is not constructed
/// directly, but gotten through [`Client::user_info_for_session()`].
///
/// # Example
///
/// ```no_run
/// # use webtoon::platform::webtoons::{errors::Error, Client};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Error> {
/// let client = Client::new();
///
/// let user_info = client.user_info_for_session("session").await?;
///
/// assert!(!user_info.is_logged_in());
/// assert_eq!(Some("username"), user_info.username());
/// assert_eq!(Some("profile"), user_info.profile());
/// # Ok(())
/// # }
/// ```
#[derive(Deserialize, Debug)]
pub struct UserInfo {
    #[serde(rename = "loginUser")]
    is_logged_in: bool,

    #[serde(rename = "nickname")]
    username: Option<String>,

    #[serde(rename = "profileUrl")]
    profile: Option<String>,
}

impl UserInfo {
    /// Returns if current user session is logged in.
    ///
    /// Functionally, this tells whether a session is valid or not.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let user_info = client.user_info_for_session("session").await?;
    ///
    /// assert!(!user_info.is_logged_in());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn is_logged_in(&self) -> bool {
        self.is_logged_in
    }

    /// Returns the users' username.
    ///
    /// If the session provided is invalid, then `username` will be `None`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let user_info = client.user_info_for_session("session").await?;
    ///
    /// assert_eq!(Some("username"), user_info.username());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn username(&self) -> Option<&str> {
        self.username.as_deref()
    }

    /// Returns the profile segment for `webtoons.com/*/creator/{profile}`.
    ///
    /// If the session provided is invalid, then `profile` will be `None`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webtoon::platform::webtoons::{errors::Error, Client};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let client = Client::new();
    ///
    /// let user_info = client.user_info_for_session("session").await?;
    ///
    /// assert_eq!(Some("profile"), user_info.profile());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn profile(&self) -> Option<&str> {
        self.profile.as_deref()
    }
}

#[allow(unused)]
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct WebtoonUserInfo {
    author: bool,
    pub(super) favorite: bool,
}

impl WebtoonUserInfo {
    pub fn is_webtoon_creator(&self) -> bool {
        self.author
    }

    #[allow(unused)]
    pub fn did_rate(&self) -> bool {
        self.favorite
    }
}

#[allow(unused)]
#[derive(Deserialize, Debug)]
pub(super) struct ApiToken {
    status: String,
    result: Token,
}

#[derive(Deserialize, Debug)]
pub(super) struct Token {
    token: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct ReactToken {
    result: ReactResult,
    success: bool,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReactResult {
    guest_token: Option<String>,
    timestamp: Option<i64>,
    status_code: Option<u16>,
}

#[derive(Debug, Serialize, Deserialize)]
struct NewLikesResponse {
    result: NewLikesResult,
    success: bool,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct NewLikesResult {
    count: u32,
}