-
Notifications
You must be signed in to change notification settings - Fork 0
/
Subscribers.cs
114 lines (98 loc) · 3.19 KB
/
Subscribers.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace Telegram.Bot
{
/// <summary>
/// Verantwortlich für das Speichern der Abonnenten
/// </summary>
static class Subscribers
{
/// <summary>
/// Fügt einen neuen Subscriber hinzu
/// </summary>
/// <param name="chatId">Chat ID des hinzuzufügenden chats</param>
public static async Task AddSubscriber(Types.ChatId chatId)
{
ChatIDs.Add(chatId);
await WriteSubscribersToFile();
}
/// <summary>
/// Entfernt einen Subscriber von der Liste
/// </summary>
/// <param name="chatId">Chat ID des zu entfernenden Chats</param>
public static async Task RemoveSubscriber(Types.ChatId chatId)
{
ChatIDs.Remove(chatId);
await WriteSubscribersToFile();
}
/// <summary>
/// Gibt alle aktuellen Abonnenten auf der Konsole aus
/// </summary>
public static void PrintSubscribers()
{
foreach (var chatId in ChatIDs)
{
Console.WriteLine(chatId);
}
}
/// <summary>
/// Schreibt alle aktuellen Abonnenten in eine Datei
/// </summary>
private static async Task WriteSubscribersToFile()
{
StreamWriter sw = new StreamWriter("subscribers.txt");
foreach (var chatId in ChatIDs)
{
await sw.WriteLineAsync(chatId);
}
sw.Close();
}
/// <summary>
/// Liest alle aktuellen Abonnenten aus einer Datei
/// </summary>
public static void ReadSubscribersFromFile()
{
StreamReader sr;
try
{
sr = new StreamReader("subscribers.txt");
}
catch (FileNotFoundException)
{
Console.WriteLine("Created new Subscriber File");
StreamWriter sw = new StreamWriter("subscribers.txt");
sw.Close();
sr = new StreamReader("subscribers.txt");
}
string line;
while ((line = sr.ReadLine()) != null)
{
ChatIDs.Add(long.Parse(line));
}
sr.Close();
}
public static async Task RemoveAll()
{
ChatIDs.Clear();
await WriteSubscribersToFile();
}
/// <summary>
/// Enthält die ChatID jedes Abonennten ein Mal
/// </summary>
public static SortedSet<Types.ChatId> ChatIDs { get; } = new SortedSet<Types.ChatId>(new ChatIdComparer());
}
/// <summary>
/// Vergleich zweier ChatIDs
/// </summary>
class ChatIdComparer : IComparer<Types.ChatId>
{
public int Compare(Types.ChatId x, Types.ChatId y)
{
Debug.Assert(x.Identifier.HasValue && y.Identifier.HasValue);
return x.Identifier.Value.CompareTo(y.Identifier.Value);
}
}
}