aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZoneManager.cs
blob: b3dc4c34e8c13f340e4b07810f61b8738b19e1a3 (plain) (blame)
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
using LibHac.Fs.NcaUtils;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.FileSystem;
using System;
using System.Collections.ObjectModel;
using LibHac.Fs;
using System.IO;
using System.Collections.Generic;
using TimeZoneConverter.Posix;
using TimeZoneConverter;

using static Ryujinx.HLE.HOS.Services.Time.TimeZoneRule;
using static Ryujinx.HLE.HOS.ErrorCode;

namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
{
    public sealed class TimeZoneManager
    {
        private const long TimeZoneBinaryTitleId = 0x010000000000080E;

        private static TimeZoneManager instance;

        private static object instanceLock = new object();

        private Switch       _device;
        private TimeZoneRule _myRules;
        private string       _deviceLocationName;
        private string[]     _locationNameCache;

        public static TimeZoneManager Instance
        {
            get
            {
                lock (instanceLock)
                {
                    if (instance == null)
                    {
                        instance = new TimeZoneManager();
                    }

                    return instance;
                }
            }
        }

        TimeZoneManager()
        {
            // Empty rules (UTC)
            _myRules = new TimeZoneRule
            {
                Ats   = new long[TzMaxTimes],
                Types = new byte[TzMaxTimes],
                Ttis  = new TimeTypeInfo[TzMaxTypes],
                Chars = new char[TzCharsArraySize]
            };

            _deviceLocationName = "UTC";
        }

        internal void Initialize(Switch device)
        {
            _device = device;

            InitializeLocationNameCache();
        }

        private void InitializeLocationNameCache()
        {
            if (HasTimeZoneBinaryTitle())
            {
                using (IStorage ncaFileStream = new LocalStorage(_device.FileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open))
                {
                    Nca         nca              = new Nca(_device.System.KeySet, ncaFileStream);
                    IFileSystem romfs            = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
                    Stream      binaryListStream = romfs.OpenFile("binaryList.txt", OpenMode.Read).AsStream();

                    StreamReader reader = new StreamReader(binaryListStream);

                    List<string> locationNameList = new List<string>();

                    string locationName;
                    while ((locationName = reader.ReadLine()) != null)
                    {
                        locationNameList.Add(locationName);
                    }

                    _locationNameCache = locationNameList.ToArray();
                }
            }
            else
            {
                ReadOnlyCollection<TimeZoneInfo> timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();
                _locationNameCache = new string[timeZoneInfos.Count];

                int i = 0;

                foreach (TimeZoneInfo timeZoneInfo in timeZoneInfos)
                {
                    bool needConversion = TZConvert.TryWindowsToIana(timeZoneInfo.Id, out string convertedName);
                    if (needConversion)
                    {
                        _locationNameCache[i] = convertedName;
                    }
                    else
                    {
                        _locationNameCache[i] = timeZoneInfo.Id;
                    }
                    i++;
                }

                // As we aren't using the system archive, "UTC" might not exist on the host system.
                // Load from C# TimeZone APIs UTC id.
                string utcId             = TimeZoneInfo.Utc.Id;
                bool   utcNeedConversion = TZConvert.TryWindowsToIana(utcId, out string utcConvertedName);
                if (utcNeedConversion)
                {
                    utcId = utcConvertedName;
                }

                _deviceLocationName = utcId;
            }
        }

        private bool IsLocationNameValid(string locationName)
        {
            foreach (string cachedLocationName in _locationNameCache)
            {
                if (cachedLocationName.Equals(locationName))
                {
                    return true;
                }
            }
            return false;
        }

        public string GetDeviceLocationName()
        {
            return _deviceLocationName;
        }

        public uint SetDeviceLocationName(string locationName)
        {
            uint resultCode = LoadTimeZoneRules(out TimeZoneRule rules, locationName);

            if (resultCode == 0)
            {
                _myRules            = rules;
                _deviceLocationName = locationName;
            }

            return resultCode;
        }

        public uint LoadLocationNameList(uint index, out string[] outLocationNameArray, uint maxLength)
        {
            List<string> locationNameList = new List<string>();

            for (int i = 0; i < _locationNameCache.Length && i < maxLength; i++)
            {
                if (i < index)
                {
                    continue;
                }

                string locationName = _locationNameCache[i];

                // If the location name is too long, error out.
                if (locationName.Length > 0x24)
                {
                    outLocationNameArray = new string[0];

                    return MakeError(ErrorModule.Time, TimeError.LocationNameTooLong);
                }

                locationNameList.Add(locationName);
            }

            outLocationNameArray = locationNameList.ToArray();

            return 0;
        }

        public uint GetTotalLocationNameCount()
        {
            return (uint)_locationNameCache.Length;
        }

        public string GetTimeZoneBinaryTitleContentPath()
        {
            return _device.System.ContentManager.GetInstalledContentPath(TimeZoneBinaryTitleId, StorageId.NandSystem, ContentType.Data);
        }

        public bool HasTimeZoneBinaryTitle()
        {
            return !string.IsNullOrEmpty(GetTimeZoneBinaryTitleContentPath());
        }

        internal uint LoadTimeZoneRules(out TimeZoneRule outRules, string locationName)
        {
            outRules = new TimeZoneRule
            {
                Ats   = new long[TzMaxTimes],
                Types = new byte[TzMaxTimes],
                Ttis  = new TimeTypeInfo[TzMaxTypes],
                Chars = new char[TzCharsArraySize]
            };

            if (!IsLocationNameValid(locationName))
            {
                return MakeError(ErrorModule.Time, TimeError.TimeZoneNotFound);
            }

            if (!HasTimeZoneBinaryTitle())
            {
                // If the user doesn't have the system archives, we generate a POSIX rule string and parse it to generate a incomplete TimeZoneRule
                // TODO: As for now not having system archives is fine, we should enforce the usage of system archives later.
                Logger.PrintWarning(LogClass.ServiceTime, "TimeZoneBinary system archive not found! Time conversions will not be accurate!");
                try
                {
                    TimeZoneInfo info      = TZConvert.GetTimeZoneInfo(locationName);
                    string       posixRule = PosixTimeZone.FromTimeZoneInfo(info);

                    if (!TimeZone.ParsePosixName(posixRule, out outRules))
                    {
                        return MakeError(ErrorModule.Time, TimeError.TimeZoneConversionFailed);
                    }

                    return 0;
                }
                catch (TimeZoneNotFoundException)
                {
                    Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {locationName})");

                    return MakeError(ErrorModule.Time, TimeError.TimeZoneNotFound);
                }
            }
            else
            {
                using (IStorage ncaFileStream = new LocalStorage(_device.FileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open))
                {
                    Nca         nca        = new Nca(_device.System.KeySet, ncaFileStream);
                    IFileSystem romfs      = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
                    Stream      tzIfStream = romfs.OpenFile($"zoneinfo/{locationName}", OpenMode.Read).AsStream();

                    if (!TimeZone.LoadTimeZoneRules(out outRules, tzIfStream))
                    {
                        return MakeError(ErrorModule.Time, TimeError.TimeZoneConversionFailed);
                    }
                }

                return 0;
            }
        }

        internal uint ToCalendarTimeWithMyRules(long time, out CalendarInfo calendar)
        {
            return ToCalendarTime(_myRules, time, out calendar);
        }

        internal static uint ToCalendarTime(TimeZoneRule rules, long time, out CalendarInfo calendar)
        {
            int error = TimeZone.ToCalendarTime(rules, time, out calendar);

            if (error != 0)
            {
                return MakeError(ErrorModule.Time, error);
            }

            return 0;
        }

        internal uint ToPosixTimeWithMyRules(CalendarTime calendarTime, out long posixTime)
        {
            return ToPosixTime(_myRules, calendarTime, out posixTime);
        }

        internal static uint ToPosixTime(TimeZoneRule rules, CalendarTime calendarTime, out long posixTime)
        {
            int error = TimeZone.ToPosixTime(rules, calendarTime, out posixTime);

            if (error != 0)
            {
                return MakeError(ErrorModule.Time, error);
            }

            return 0;
        }
    }
}