File: Cache.cs

package info (click to toggle)
libflickrnet 25277-6
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 628 kB
  • ctags: 1,355
  • sloc: cs: 7,136; makefile: 24; sh: 13; ansic: 6
file content (387 lines) | stat: -rw-r--r-- 9,776 bytes parent folder | download | duplicates (3)
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
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace FlickrNet
{
	/// <summary>
	/// Internal Cache class
	/// </summary>
	internal sealed class Cache
	{
		private class CacheException : Exception
		{
			public CacheException(string message) : base(message)
			{}

		}

		private static PersistentCache _downloads;


		/// <summary>
		/// A static object containing the list of cached downloaded files.
		/// </summary>
		public static PersistentCache Downloads
		{
			get 
			{
				lock(lockObject)
				{
					if( _downloads == null )
						_downloads = new PersistentCache(Path.Combine(CacheLocation, "downloadCache.dat"), new PictureCacheItemPersister(), CacheSizeLimit);
					return _downloads;
				}
			}
		}

		private static PersistentCache _responses;

		/// <summary>
		/// A static object containing the list of cached responses from Flickr.
		/// </summary>
		public static PersistentCache Responses
		{
			get 
			{
				lock(lockObject)
				{
					if( _responses == null )
						_responses = new PersistentCache(Path.Combine(CacheLocation, "responseCache.dat"), new ResponseCacheItemPersister(), CacheSizeLimit);
					return _responses;
				}
			}
		}


		private Cache()
		{
		}

		private static object lockObject = new object();

		private enum Tristate
		{
			Null, True, False
		}
		private static Tristate _cacheDisabled;

		internal static bool CacheDisabled
		{
			get
			{
#if !WindowsCE
				if( _cacheDisabled == Tristate.Null && FlickrConfigurationManager.Settings != null )
					_cacheDisabled = (FlickrConfigurationManager.Settings.CacheDisabled?Tristate.True:Tristate.False);
#endif
				
				if( _cacheDisabled == Tristate.Null ) _cacheDisabled = Tristate.False;

				return (_cacheDisabled==Tristate.True);
			}
			set
			{
				_cacheDisabled = value?Tristate.True:Tristate.False;
			}
		}

		private static string _cacheLocation;

		internal static string CacheLocation
		{
			get 
			{ 
#if !WindowsCE
				if( _cacheLocation == null && FlickrConfigurationManager.Settings != null )
					_cacheLocation = FlickrConfigurationManager.Settings.CacheLocation;
#endif
				if( _cacheLocation == null )
				{
					try
					{
#if !WindowsCE
						_cacheLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FlickrNet");
#else
                        _cacheLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "FlickrNetCache");
#endif
					}
					catch(System.Security.SecurityException)
					{
						// Permission to read application directory not provided.
						throw new CacheException("Unable to read default cache location. Please cacheLocation in configuration file or set manually in code");
					}
				}

				if( _cacheLocation == null )
					throw new CacheException("Unable to determine cache location. Please set cacheLocation in configuration file or set manually in code");

				return _cacheLocation;
			}
			set
			{
				_cacheLocation = value;
			}
		}

		// Default cache size is set to 50MB
        private static long _cacheSizeLimit = 52428800;
        private static long _cacheSize;

		internal static long CacheSizeLimit
		{
			get 
			{
                return _cacheSizeLimit;
			}
			set 
			{
                _cacheSizeLimit = value;
			}
		}

		internal static long CacheSize
		{
			get 
			{
                return _cacheSize;
			}
			set 
			{
                _cacheSize = value;
			}
		}


		// Default cache timeout is 1 hour
		private static TimeSpan _cachetimeout = new TimeSpan(0, 1, 0, 0, 0);

		/// <summary>
		/// The default timeout for cachable objects within the cache.
		/// </summary>
		public static TimeSpan CacheTimeout
		{
			get { return _cachetimeout; }
			set { _cachetimeout = value; }
		}
		
		internal static void FlushCache(string url)
		{
			Responses[url] = null;
			Downloads[url] = null;
		}

		internal static void FlushCache()
		{
			Responses.Flush();
			Downloads.Flush();
		}

	}

	/// <summary>
	/// A cache item containing details of a REST response from Flickr.
	/// </summary>
	[Serializable]
	public class ResponseCacheItem : ICacheItem
	{
		private string url;
		private string response;
		private DateTime creationTime;

		/// <summary>
		/// Gets or sets the original URL of the request.
		/// </summary>
		public string Url { get { return url; } set { url = value; } }

		/// <summary>
		/// Gets or sets the XML response.
		/// </summary>
		public string Response { get { return response; } set { response = value; } }

		/// <summary>
		/// Gets or sets the time the cache item was created.
		/// </summary>
		public DateTime CreationTime { get { return creationTime; } set { creationTime = value; } }

		/// <summary>
		/// Gets the filesize of the request.
		/// </summary>
		public long FileSize { get { return (response==null?0:response.Length); } }

		void ICacheItem.OnItemFlushed()
		{
		}

	}

	internal class ResponseCacheItemPersister : CacheItemPersister
	{
		public override ICacheItem Read(Stream inputStream)
		{
			string s = Utils.ReadString(inputStream);
			string response = Utils.ReadString(inputStream);

			string[] chunks = s.Split('\n');

			// Corrupted cache record, so throw IOException which is then handled and returns partial cache.
			if( chunks.Length != 2 )
				throw new IOException("Unexpected number of chunks found");

			string url = chunks[0];
			DateTime creationTime = new DateTime(long.Parse(chunks[1]));
			ResponseCacheItem item = new ResponseCacheItem();
			item.Url = url;
			item.CreationTime = creationTime;
			item.Response = response;
			return item;
		}

		public override void Write(Stream outputStream, ICacheItem cacheItem)
		{
			ResponseCacheItem item = (ResponseCacheItem) cacheItem;
			StringBuilder result = new StringBuilder();
			result.Append(item.Url + "\n");
			result.Append(item.CreationTime.Ticks.ToString("0"));
			Utils.WriteString(outputStream, result.ToString());
			Utils.WriteString(outputStream, item.Response);
		}
	}

	/// <summary>
	/// An item that can be stored in a cache.
	/// </summary>
	public interface ICacheItem
	{
		/// <summary>
		/// The time this cache item was created.
		/// </summary>
		DateTime CreationTime { get; }

		/// <summary>
		/// Gets called back when the item gets flushed
		/// from the cache.
		/// </summary>
		void OnItemFlushed();

		/// <summary>
		/// The size of this item, in bytes. Return 0
		/// if size management is not important.
		/// </summary>
		long FileSize { get; }
	}

	/// <summary>
	/// An interface that knows how to read/write subclasses
	/// of ICacheItem.  Obviously there will be a tight
	/// coupling between concrete implementations of ICacheItem
	/// and concrete implementations of ICacheItemPersister.
	/// </summary>
	public abstract class CacheItemPersister
	{
		/// <summary>
		/// Read a single cache item from the input stream.
		/// </summary>
		public abstract ICacheItem Read(Stream inputStream);

		/// <summary>
		/// Write a single cache item to the output stream.
		/// </summary>
		public abstract void Write(Stream outputStream, ICacheItem cacheItem);
	}

	/// <summary>
	/// Contains details of image held with the Flickr.Net cache.
	/// </summary>
	[Serializable]
	public class PictureCacheItem : ICacheItem
	{
		#region [ Internal Variables ]
		internal string url;
		internal DateTime creationTime;
		internal string filename;
		internal long fileSize;
		#endregion

		#region [ Public Properties ]
		/// <summary>
		/// The URL of the original image on Flickr.
		/// </summary>
		public string Url { get { return url; } }
		/// <summary>
		/// The <see cref="DateTime"/> that the cache item was created.
		/// </summary>
		public DateTime CreationTime { get { return creationTime; } }

		/// <summary>
		/// The filesize in bytes of the image.
		/// </summary>
		public long FileSize { get { return fileSize; } }
		/// <summary>
		/// The Flickr photo id of the image.
		/// </summary>
		public string PhotoId
		{
			get 
			{
				if( url == null ) 
					return null;
				else
				{
					int begin = url.LastIndexOf("/");
					int end = url.IndexOf("_");

					return url.Substring(begin + 1, (end - begin) - 1);
				}
			}
		}
		#endregion

		#region [ Public Methods ]

		void ICacheItem.OnItemFlushed()
		{
			File.Delete(filename);
		}

		#endregion
	}

	/// <summary>
	/// Persists PictureCacheItem objects.
	/// </summary>
	internal class PictureCacheItemPersister : CacheItemPersister
	{
		public override ICacheItem Read(Stream inputStream)
		{
			string s = Utils.ReadString(inputStream);

			string[] chunks = s.Split('\n');
			string url = chunks[0];
			DateTime creationTime = new DateTime(long.Parse(chunks[1]));
			string filename = chunks[2];
			long fileSize = long.Parse(chunks[3]);

			PictureCacheItem pci = new PictureCacheItem();
			pci.url = url;
			pci.creationTime = creationTime;
			pci.filename = filename;
			pci.fileSize = fileSize;
			return pci;
		}

		public override void Write(Stream outputStream, ICacheItem cacheItem)
		{
			PictureCacheItem pci = (PictureCacheItem) cacheItem;
			StringBuilder output = new StringBuilder();

			output.Append(pci.url + "\n");
			output.Append(pci.creationTime.Ticks + "\n");
			output.Append(pci.filename + "\n");
			output.Append(pci.fileSize + "\n");

			Utils.WriteString(outputStream, output.ToString());
		}
	}
}