steam-user 0.1.0

Steam User web client for Rust - HTTP-based Steam Community interactions
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
//! Friend Activity Feed services.
//!
//! This module provides functionality for fetching and interacting with
//! the Steam friend activity feed, including game purchases, achievements,
//! wishlist additions, and more.

use std::sync::OnceLock;

use scraper::{Html, Selector};
use steamid::SteamID;

static SEL_BLOTTER_DAY: OnceLock<Selector> = OnceLock::new();
fn sel_blotter_day() -> &'static Selector {
    SEL_BLOTTER_DAY.get_or_init(|| Selector::parse(".blotter_day").expect("valid CSS selector"))
}

static SEL_BLOTTER_BLOCK: OnceLock<Selector> = OnceLock::new();
fn sel_blotter_block() -> &'static Selector {
    SEL_BLOTTER_BLOCK.get_or_init(|| Selector::parse(".blotter_block").expect("valid CSS selector"))
}

static SEL_BLOTTER_DAY_HEADER: OnceLock<Selector> = OnceLock::new();
fn sel_blotter_day_header() -> &'static Selector {
    SEL_BLOTTER_DAY_HEADER.get_or_init(|| Selector::parse(".blotter_day_header_date").expect("valid CSS selector"))
}

static SEL_BLOTTER_DAILY_ROLLUP_LINE: OnceLock<Selector> = OnceLock::new();
fn sel_blotter_daily_rollup_line() -> &'static Selector {
    SEL_BLOTTER_DAILY_ROLLUP_LINE.get_or_init(|| Selector::parse(".blotter_daily_rollup_line").expect("valid CSS selector"))
}

static SEL_AUTHOR_AVATAR: OnceLock<Selector> = OnceLock::new();
fn sel_author_avatar() -> &'static Selector {
    SEL_AUTHOR_AVATAR.get_or_init(|| Selector::parse(".blotter_author_block .playerAvatar img").expect("valid CSS selector"))
}

static SEL_AUTHOR_LINK: OnceLock<Selector> = OnceLock::new();
fn sel_author_link() -> &'static Selector {
    SEL_AUTHOR_LINK.get_or_init(|| Selector::parse("a[data-miniprofile]").expect("valid CSS selector"))
}

static SEL_APP_LINKS: OnceLock<Selector> = OnceLock::new();
fn sel_app_links() -> &'static Selector {
    SEL_APP_LINKS.get_or_init(|| Selector::parse("a[href*=\"store.steampowered.com/app/\"], a[href*=\"steamcommunity.com/app/\"]").expect("valid CSS selector"))
}

static SEL_IMG_TITLE: OnceLock<Selector> = OnceLock::new();
fn sel_img_title() -> &'static Selector {
    SEL_IMG_TITLE.get_or_init(|| Selector::parse("img[title]").expect("valid CSS selector"))
}

static SEL_GROUP_LINKS: OnceLock<Selector> = OnceLock::new();
fn sel_group_links() -> &'static Selector {
    SEL_GROUP_LINKS.get_or_init(|| Selector::parse("a[href*=\"steamcommunity.com/groups/\"]").expect("valid CSS selector"))
}

static SEL_COMMENT_THREAD: OnceLock<Selector> = OnceLock::new();
fn sel_comment_thread() -> &'static Selector {
    SEL_COMMENT_THREAD.get_or_init(|| Selector::parse(".commentthread_comment").expect("valid CSS selector"))
}

static SEL_COMMENT_AVATAR: OnceLock<Selector> = OnceLock::new();
fn sel_comment_avatar() -> &'static Selector {
    SEL_COMMENT_AVATAR.get_or_init(|| Selector::parse(".commentthread_comment_avatar img").expect("valid CSS selector"))
}

static SEL_COMMENT_TIMESTAMP: OnceLock<Selector> = OnceLock::new();
fn sel_comment_timestamp() -> &'static Selector {
    SEL_COMMENT_TIMESTAMP.get_or_init(|| Selector::parse(".commentthread_comment_timestamp").expect("valid CSS selector"))
}

use crate::{
    client::SteamUser,
    endpoint::steam_endpoint,
    error::SteamUserError,
    types::{ActivityAchievement, ActivityApp, ActivityAuthor, ActivityComment, ActivityCommentResponse, ActivityGroup, ActivityPlayer, ActivityType, FriendActivity, FriendActivityResponse},
    utils::avatar::{extract_custom_url, get_avatar_hash_from_url},
};

impl SteamUser {
    /// Retrieves the friend activity feed.
    ///
    /// Fetches activity items from the authenticated user's activity feed,
    /// including game purchases, achievements, wishlist additions, and more.
    ///
    /// # Arguments
    ///
    /// * `start` - Optional Unix timestamp to start fetching from (for
    ///   pagination).
    ///
    /// # Returns
    ///
    /// Returns a [`FriendActivityResponse`] containing activities and
    /// pagination info.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(mut user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let response = user.get_friend_activity(None).await?;
    /// for activity in response.activities {
    ///     println!("Activity: {:?}", activity.activity_type);
    /// }
    /// // Fetch next page if available
    /// if let Some(next_start) = response.next_request_timestart {
    ///     let next_page = user.get_friend_activity(Some(next_start)).await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(GET, host = Community, path = "/profiles/{steam_id}/ajaxgetusernews/", kind = Read)]
    pub async fn get_friend_activity(&self, start: Option<u64>) -> Result<FriendActivityResponse, SteamUserError> {
        let steam_id = self.session.steam_id.ok_or(SteamUserError::NotLoggedIn)?;
        let start_ts = start.unwrap_or_else(|| std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0));

        let response: serde_json::Value = self.get_path(format!("/profiles/{}/ajaxgetusernews/?start={}", steam_id.steam_id64(), start_ts)).send().await?.json().await?;

        let success = response.get("success").and_then(|v| v.as_bool()).unwrap_or(false);

        if !success {
            return Ok(FriendActivityResponse::default());
        }

        let next_request = response.get("next_request").and_then(|v| v.as_str()).map(|s| s.to_string());

        let next_request_timestart = next_request.as_ref().and_then(|url| url.split("?start=").last().and_then(|s| s.parse::<u64>().ok()));

        let blotter_html = response.get("blotter_html").and_then(|v| v.as_str()).unwrap_or("").to_string();

        // Activity feeds re-parse a fresh HTML fragment per blotter block; for
        // accounts with many days of activity this is the heaviest CPU path
        // in this service, so run it on the blocking pool.
        let activities = tokio::task::spawn_blocking(move || parse_activity_feed(&blotter_html)).await.map_err(|e| crate::error::SteamUserError::Other(format!("activity-feed parse task failed: {e}")))?;

        Ok(FriendActivityResponse { activities, next_request_timestart, next_request_url: next_request })
    }

    /// Retrieves the complete friend activity feed by fetching all pages.
    ///
    /// This method will continue fetching pages until no more activities are
    /// available. Use with caution as this may make many HTTP requests.
    ///
    /// # Returns
    ///
    /// Returns a `Vec<FriendActivity>` containing all activities from the feed.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # async fn example(mut user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let all_activities = user.get_friend_activity_full().await?;
    /// println!("Found {} total activities", all_activities.len());
    /// # Ok(())
    /// # }
    /// ```
    // delegates to `get_friend_activity` (paginated) — no #[steam_endpoint]
    #[tracing::instrument(skip(self))]
    pub async fn get_friend_activity_full(&self) -> Result<Vec<FriendActivity>, SteamUserError> {
        let mut all_activities = Vec::new();
        let mut next_start: Option<u64> = None;

        loop {
            let response = self.get_friend_activity(next_start).await?;
            all_activities.extend(response.activities);

            match response.next_request_timestart {
                Some(ts) => next_start = Some(ts),
                None => break,
            }
        }

        Ok(all_activities)
    }

    /// Comments on a friend's game purchase activity.
    ///
    /// # Arguments
    ///
    /// * `steam_id` - The SteamID of the user who received the game.
    /// * `thread_id` - The thread ID of the activity (from
    ///   [`FriendActivity::thread_id`]).
    /// * `comment` - The comment text to post.
    ///
    /// # Returns
    ///
    /// Returns an [`ActivityCommentResponse`] with the result of the operation.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # use steamid::SteamID;
    /// # async fn example(mut user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let friend_id = SteamID::from(76561198012345678u64);
    /// let result = user
    ///     .comment_user_received_new_game(friend_id, 1234567890, "Nice game!")
    ///     .await?;
    /// println!("Comment posted: {}", result.success);
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/comment/UserReceivedNewGame/post/{steam_id}/{thread_id}/", kind = Write)]
    pub async fn comment_user_received_new_game(&self, steam_id: SteamID, thread_id: u64, comment: &str) -> Result<ActivityCommentResponse, SteamUserError> {
        let form = [("comment", comment), ("count", "3"), ("feature2", "-1"), ("newestfirstpagination", "true")];

        let response: serde_json::Value = self.post_path(format!("/comment/UserReceivedNewGame/post/{}/{}/", steam_id.steam_id64(), thread_id)).form(&form).send().await?.json().await?;

        Ok(parse_comment_response(&response))
    }

    /// Upvotes (likes) a friend's game purchase activity.
    ///
    /// # Arguments
    ///
    /// * `steam_id` - The SteamID of the user who received the game.
    /// * `thread_id` - The thread ID of the activity (from
    ///   [`FriendActivity::thread_id`]).
    ///
    /// # Returns
    ///
    /// Returns an [`ActivityCommentResponse`] with the result of the operation.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # use steamid::SteamID;
    /// # async fn example(mut user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let friend_id = SteamID::from(76561198012345678u64);
    /// let result = user
    ///     .rate_up_user_received_new_game(friend_id, 1234567890)
    ///     .await?;
    /// println!(
    ///     "Upvoted: {}, total upvotes: {}",
    ///     result.has_upvoted, result.upvotes
    /// );
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/comment/UserReceivedNewGame/voteup/{steam_id}/{thread_id}/", kind = Write)]
    pub async fn rate_up_user_received_new_game(&self, steam_id: SteamID, thread_id: u64) -> Result<ActivityCommentResponse, SteamUserError> {
        let form = [("vote", "1"), ("count", "3"), ("feature2", "-1"), ("newestfirstpagination", "true")];

        let response: serde_json::Value = self.post_path(format!("/comment/UserReceivedNewGame/voteup/{}/{}/", steam_id.steam_id64(), thread_id)).form(&form).send().await?.json().await?;

        Ok(parse_comment_response(&response))
    }

    /// Deletes a comment from a friend's game purchase activity.
    ///
    /// # Arguments
    ///
    /// * `steam_id` - The SteamID of the user who received the game.
    /// * `thread_id` - The thread ID of the activity (from
    ///   [`FriendActivity::thread_id`]).
    /// * `comment_id` - The ID of the comment to delete.
    ///
    /// # Returns
    ///
    /// Returns an [`ActivityCommentResponse`] with the result of the operation.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use steam_user::client::SteamUser;
    /// # use steamid::SteamID;
    /// # async fn example(mut user: SteamUser) -> Result<(), Box<dyn std::error::Error>> {
    /// let friend_id = SteamID::from(76561198012345678u64);
    /// let result = user
    ///     .delete_comment_user_received_new_game(friend_id, 1234567890, "6407003171827779878")
    ///     .await?;
    /// println!("Deleted: {}", result.success);
    /// # Ok(())
    /// # }
    /// ```
    #[steam_endpoint(POST, host = Community, path = "/comment/UserReceivedNewGame/delete/{steam_id}/{thread_id}/", kind = Write)]
    pub async fn delete_comment_user_received_new_game(&self, steam_id: SteamID, thread_id: u64, comment_id: &str) -> Result<ActivityCommentResponse, SteamUserError> {
        let form = [("gidcomment", comment_id), ("start", "0"), ("count", "3"), ("feature2", "-1"), ("newestfirstpagination", "true")];

        let response: serde_json::Value = self.post_path(format!("/comment/UserReceivedNewGame/delete/{}/{}/", steam_id.steam_id64(), thread_id)).form(&form).send().await?.json().await?;

        Ok(parse_comment_response(&response))
    }
}

/// Parses the activity feed HTML into structured activity items.
fn parse_activity_feed(html: &str) -> Vec<FriendActivity> {
    let cleaned_html = html.replace(['\t', '\n', '\r'], "");
    let document = Html::parse_document(&format!("<div>{}</div>", cleaned_html));
    let mut activities = Vec::new();

    for day_element in document.select(sel_blotter_day()) {
        let timestamp = day_element.value().attr("id").and_then(|id| id.strip_prefix("blotter_day_")).and_then(|ts| ts.parse::<u64>().ok()).unwrap_or(0);

        let header_date = day_element.select(sel_blotter_day_header()).next().map(|el| el.text().collect::<String>().trim().to_string()).unwrap_or_default();

        for block_element in day_element.select(sel_blotter_block()) {
            let block_html = block_element.html();
            let block_doc = Html::parse_fragment(&block_html);

            // Determine activity type from classes
            let activity_type = determine_activity_type(&block_doc);

            let mut activity = match activity_type {
                ActivityType::DailyRollup => parse_blotter_daily_rollup(&block_doc),
                ActivityType::GamePurchase => parse_blotter_game_purchase(&block_doc),
                _ => FriendActivity { activity_type: activity_type.clone(), ..Default::default() },
            };

            activity.timestamp = timestamp;
            activity.header_date = header_date.clone();
            activities.push(activity);
        }
    }

    activities
}

/// Determines the activity type from the blotter block.
fn determine_activity_type(doc: &Html) -> ActivityType {
    let html = doc.html();

    if html.contains("blotter_daily_rollup") {
        ActivityType::DailyRollup
    } else if html.contains("blotter_gamepurchase") {
        ActivityType::GamePurchase
    } else if html.contains("blotter_workshopitempublished") {
        ActivityType::WorkshopItemPublished
    } else if html.contains("blotter_recommendation") {
        ActivityType::Recommendation
    } else if html.contains("blotter_userstatus") {
        ActivityType::UserStatus
    } else if html.contains("blotter_screenshot") {
        ActivityType::Screenshot
    } else if html.contains("blotter_videopublished") {
        ActivityType::VideoPublished
    } else {
        ActivityType::Unknown("unknown".to_string())
    }
}

/// Parses a daily rollup blotter block.
fn parse_blotter_daily_rollup(doc: &Html) -> FriendActivity {
    let mut activity = FriendActivity { activity_type: ActivityType::DailyRollup, ..Default::default() };

    for line_element in doc.select(sel_blotter_daily_rollup_line()) {
        let line_html = line_element.html();
        let line_doc = Html::parse_fragment(&line_html);

        // Get content text to determine sub-type
        let content_text = line_element.text().collect::<String>();

        // Parse players
        let players = parse_player_list_from_blotter(&line_doc);

        // Parse apps
        let apps = parse_app_list_from_blotter(&line_doc);

        // Parse achieved
        let achieved = parse_achieved_from_blotter(&line_doc);

        // Parse groups
        let groups = parse_group_list_from_blotter(&line_doc);

        // Merge into activity
        activity.players.extend(players);
        activity.apps.extend(apps);
        activity.achieved.extend(achieved);
        activity.groups.extend(groups);

        // Try to determine more specific type
        if content_text.contains("are now friends") || content_text.contains("is now friends with") {
            activity.activity_type = ActivityType::NewFriend;
        } else if content_text.contains("played") && content_text.contains("for the first time") {
            activity.activity_type = ActivityType::PlayedFirstTime;
        } else if content_text.contains("achieved") {
            activity.activity_type = ActivityType::Achieved;
        } else if content_text.contains("has added") && content_text.contains("to their wishlist") {
            activity.activity_type = ActivityType::AddedToWishlist;
        } else if content_text.contains("is now following") {
            activity.activity_type = ActivityType::Following;
        } else if content_text.contains("has joined") {
            activity.activity_type = ActivityType::Joined;
        }
    }

    activity
}

/// Parses a game purchase blotter block.
fn parse_blotter_game_purchase(doc: &Html) -> FriendActivity {
    let mut activity = FriendActivity { activity_type: ActivityType::GamePurchase, ..Default::default() };

    // Parse author
    if let Some(avatar_el) = doc.select(sel_author_avatar()).next() {
        let avatar_src = avatar_el.value().attr("src").unwrap_or("");
        let avatar_hash = get_avatar_hash_from_url(avatar_src).unwrap_or_default();

        if let Some(author_el) = doc.select(sel_author_link()).next() {
            let miniprofile = author_el.value().attr("data-miniprofile").and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);

            let profile_url = author_el.value().attr("href").unwrap_or("").to_string();
            let custom_url = extract_custom_url(&profile_url);

            // Get name (skip nickname elements)
            let name = author_el.text().collect::<String>().trim().to_string();

            activity.author = Some(ActivityAuthor {
                name,
                nickname: None,
                avatar_hash,
                miniprofile,
                steam_id: SteamID::from_individual_account_id(u32::try_from(miniprofile).unwrap_or(0)),
                profile_url,
                custom_url,
            });
        }
    }

    // Parse apps from content and details
    activity.apps = parse_app_list_from_blotter(doc);

    // Parse thread ID for commenting
    activity.thread_id = parse_thread_id(doc);

    // Parse comments
    activity.comments = parse_activity_comments(doc);

    activity
}

/// Parses player list from blotter content.
fn parse_player_list_from_blotter(doc: &Html) -> Vec<ActivityPlayer> {
    let mut players = Vec::new();

    for element in doc.select(sel_author_link()) {
        let miniprofile = element.value().attr("data-miniprofile").and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);

        if miniprofile == 0 {
            continue;
        }

        let name = element.text().collect::<String>().trim().to_string();

        players.push(ActivityPlayer { name, nickname: None, miniprofile, steam_id: SteamID::from_individual_account_id(u32::try_from(miniprofile).unwrap_or(0)) });
    }

    players
}

/// Parses app list from blotter content.
fn parse_app_list_from_blotter(doc: &Html) -> Vec<ActivityApp> {
    let mut apps = Vec::new();

    for element in doc.select(sel_app_links()) {
        let link = element.value().attr("href").unwrap_or("").to_string();
        let name = element.text().collect::<String>().trim().to_string();
        let id = parse_app_id_from_link(&link);

        if id > 0 {
            apps.push(ActivityApp { id, name, link });
        }
    }

    // Deduplicate by ID
    apps.sort_by_key(|a| a.id);
    apps.dedup_by_key(|a| a.id);

    apps
}

/// Parses achievements from blotter content.
fn parse_achieved_from_blotter(doc: &Html) -> Vec<ActivityAchievement> {
    let mut achieved = Vec::new();

    for element in doc.select(sel_img_title()) {
        let title = element.value().attr("title").unwrap_or("").to_string();
        let img = element.value().attr("src").unwrap_or("").to_string();

        if !title.is_empty() && img.contains("achievement") {
            achieved.push(ActivityAchievement { title, img });
        }
    }

    achieved
}

/// Parses group list from blotter content.
fn parse_group_list_from_blotter(doc: &Html) -> Vec<ActivityGroup> {
    let mut groups = Vec::new();

    for element in doc.select(sel_group_links()) {
        let link = element.value().attr("href").unwrap_or("").to_string();
        let name = element.text().collect::<String>().trim().to_string();
        let url = link.split("steamcommunity.com/groups/").nth(1).unwrap_or("").trim_end_matches('/').to_string();

        if !url.is_empty() {
            groups.push(ActivityGroup { name, link, url });
        }
    }

    groups
}

/// Parses thread ID for commenting from blotter block.
fn parse_thread_id(doc: &Html) -> Option<u64> {
    let html = doc.html();

    // Try to find in onclick attribute
    if let Some(start) = html.find("UserReceivedNewGame_") {
        let rest = &html[start..];
        if let Some(end) = rest.find('\'') {
            let id_part = &rest[..end];
            // Extract the thread ID (last number after underscore)
            if let Some(last_underscore) = id_part.rfind('_') {
                if let Ok(id) = id_part[last_underscore + 1..].parse::<u64>() {
                    return Some(id);
                }
            }
        }
    }

    // Try to find in form/paging element IDs
    if let Some(start) = html.find("commentthread_UserReceivedNewGame_") {
        let rest = &html[start..];
        // Find the thread ID between underscores
        let parts: Vec<&str> = rest.split('_').collect();
        if parts.len() >= 3 {
            if let Ok(id) = parts[2].parse::<u64>() {
                return Some(id);
            }
        }
    }

    None
}

/// Parses comments from an activity block.
fn parse_activity_comments(doc: &Html) -> Vec<ActivityComment> {
    let mut comments = Vec::new();

    for element in doc.select(sel_comment_thread()) {
        let id = element.value().attr("id").unwrap_or("").replace("comment_", "");

        if id.is_empty() {
            continue;
        }

        let author_avatar_hash = element.select(sel_comment_avatar()).next().and_then(|el| el.value().attr("src")).and_then(get_avatar_hash_from_url).unwrap_or_default();

        let author_miniprofile = element.select(sel_author_link()).next().and_then(|el| el.value().attr("data-miniprofile")).and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);

        let timestamp = element.select(sel_comment_timestamp()).next().and_then(|el| el.value().attr("data-timestamp")).and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);

        comments.push(ActivityComment {
            id,
            author_steam_id: SteamID::from_individual_account_id(u32::try_from(author_miniprofile).unwrap_or(0)),
            author_miniprofile,
            author_avatar_hash,
            timestamp,
        });
    }

    comments
}

/// Parses an app ID from a Steam store/community URL.
fn parse_app_id_from_link(link: &str) -> u32 {
    let prefixes = ["steamcommunity.com/app/", "store.steampowered.com/app/", "store.steampowered.com/sub/"];

    for prefix in prefixes {
        if let Some(start) = link.find(prefix) {
            let rest = &link[start + prefix.len()..];
            let id_str = rest.split('/').next().unwrap_or("");
            if let Ok(id) = id_str.parse::<u32>() {
                return id;
            }
        }
    }

    0
}

/// Parses the comment response JSON.
fn parse_comment_response(response: &serde_json::Value) -> ActivityCommentResponse {
    let success = response.get("success").and_then(|v| v.as_bool()).or_else(|| response.get("success").and_then(|v| v.as_i64()).map(|n| n == 1)).unwrap_or(false);

    let total_count = response.get("total_count").and_then(|v| v.as_u64()).map(|n| u32::try_from(n).unwrap_or(u32::MAX)).unwrap_or(0);

    let upvotes = response.get("upvotes").and_then(|v| v.as_u64()).map(|n| u32::try_from(n).unwrap_or(u32::MAX)).unwrap_or(0);

    let has_upvoted = response.get("has_upvoted").and_then(|v| v.as_i64()).map(|n| n == 1).unwrap_or(false);

    ActivityCommentResponse { success, total_count, upvotes, has_upvoted }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_app_id_from_link() {
        assert_eq!(parse_app_id_from_link("https://store.steampowered.com/app/730/Counter-Strike_2/"), 730);
        assert_eq!(parse_app_id_from_link("https://steamcommunity.com/app/570"), 570);
        assert_eq!(parse_app_id_from_link("https://store.steampowered.com/sub/469"), 469);
        assert_eq!(parse_app_id_from_link("https://example.com"), 0);
    }

    #[test]
    fn test_determine_activity_type() {
        let doc = Html::parse_fragment("<div class=\"blotter_gamepurchase\">test</div>");
        assert_eq!(determine_activity_type(&doc), ActivityType::GamePurchase);

        let doc = Html::parse_fragment("<div class=\"blotter_daily_rollup\">test</div>");
        assert_eq!(determine_activity_type(&doc), ActivityType::DailyRollup);
    }
}