PageRenderTime 36ms CodeModel.GetById 9ms app.highlight 22ms RepoModel.GetById 1ms app.codeStats 0ms

/Utilites/DownloadCache.vb

#
Visual Basic | 261 lines | 209 code | 43 blank | 9 comment | 0 complexity | 52103aa8dd1d309beb0a93a829d9b05a MD5 | raw file
  1Imports System.Security.Cryptography
  2Imports System.Net
  3Imports System.IO
  4Imports System.IO.Compression
  5Imports System.Text
  6Imports System
  7Imports System.Drawing
  8
  9Public Class DownloadCache
 10
 11    Public Shared Property CacheFolder As String
 12
 13    Public Shared Function GetCacheFileName(ByVal URL As String) As String
 14        Dim Buffer As Byte() = Utilities.ComputeHashValueToByte(URL)
 15
 16        Dim Extention As String = URL.Split("?")(0)
 17        Extention = IO.Path.GetExtension(Extention)
 18
 19        Dim Result As String = ""
 20        For Each Item As Byte In Buffer
 21            Result &= Conversion.Hex(Item)
 22        Next
 23
 24        Return Result & Extention
 25    End Function
 26
 27    Public Shared Function SaveImageToCacheAndPath(ByVal URL As String, Path As String, Optional ByVal ForceDownload As Boolean = False, _
 28                                           Optional ByVal resizeWidth As Integer = 0, Optional ByVal resizeHeight As Integer = 0, _
 29                                           Optional ByVal Overwrite As Boolean = True) As Boolean
 30        Dim CacheFileName As String = ""
 31        If Not SaveImageToCache(URL, Path, ForceDownload, CacheFileName) Then Return False
 32
 33        Dim CachePath = IO.Path.Combine(CacheFolder, CacheFileName)
 34
 35        If IfNotValidImage_Delete(CachePath) Then
 36
 37            'Resize cache image only if need to
 38            If Not (resizeWidth = 0 And resizeHeight = 0) Then CopyAndDownSizeImage(CachePath, CachePath, resizeWidth, resizeHeight)
 39
 40            Utilities.EnsureFolderExists(Path)
 41            File.Copy(CachePath, Path, Overwrite)
 42        Else
 43            Return False
 44        End If
 45        Return True
 46    End Function
 47
 48
 49    Public Shared Function SaveImageToCacheAndPaths(ByVal URL As String, Paths As List(Of String), Optional ByVal ForceDownload As Boolean = False, _
 50                                           Optional ByVal resizeWidth As Integer = 0, Optional ByVal resizeHeight As Integer = 0, _
 51                                           Optional ByVal Overwrite As Boolean = True) As Boolean
 52        Dim verifiedPaths As New List(Of String)
 53        For each path in Paths
 54            If Not File.exists(path) OrElse Overwrite Then verifiedPaths.add(path)
 55        Next
 56        If verifiedPaths.Count = 0 Then Return True
 57        Dim CacheFileName = ""
 58        If Not SaveImageToCache(URL, verifiedPaths(0), ForceDownload, CacheFileName) Then Return False
 59
 60        Dim CachePath = IO.Path.Combine(CacheFolder, CacheFileName)
 61
 62        If IfNotValidImage_Delete(CachePath) Then
 63
 64            'Resize cache image only if need to
 65            If Not (resizeWidth = 0 And resizeHeight = 0) Then CopyAndDownSizeImage(CachePath, CachePath, resizeWidth, resizeHeight)
 66
 67            For Each path In verifiedPaths
 68                Utilities.EnsureFolderExists(path)
 69                If Overwrite OrElse Not File.Exists(path) Then File.Copy(CachePath, path, Overwrite)
 70            Next
 71        Else
 72            Return False
 73        End If
 74
 75        Return True
 76    End Function
 77
 78    Public Shared Function IfNotValidImage_Delete(filename As String) As Boolean
 79        Dim ok As Boolean = True
 80        Try
 81            Dim testImage = new Drawing.Bitmap(filename)
 82            testImage.Dispose()
 83        Catch ex As Exception
 84            Try
 85                File.Delete(filename)
 86                ok = False
 87            Catch 
 88                ok = False
 89            End Try
 90            Throw 
 91        End Try
 92        Return ok
 93    End Function
 94
 95    Public Shared Sub CopyAndDownSizeImage(ByVal src As String, ByVal dest As String, Optional ByVal resizeWidth As Integer = 0, Optional ByVal resizeHeight As Integer = 0)
 96        Try
 97            Dim img = Utilities.GetImage(src)
 98            Dim resized = False
 99
100            'Down-size only
101            If (resizeWidth <> 0 And img.Width > resizeWidth) Or img.Height > resizeHeight And Not (resizeWidth = 0 And resizeHeight = 0) Then
102
103                'Calc scaled height - width is passed in as zero for people pictures and posters.
104                If resizeWidth = 0 Then
105                    resizeWidth = img.Width * resizeHeight / img.Height
106                End If
107
108                img = Utilities.ResizeImage(img, resizeWidth, resizeHeight)
109                resized = True
110            End If
111
112            If resized Or src <> dest Then
113                Utilities.SaveImage(img, dest)
114            End If
115        Catch
116        End Try
117    End Sub
118
119    Public Shared Function DownloadFileAndCache(ByVal URL As String, Optional ByVal Path As String = "", _
120                                          Optional ByVal ForceDownload As Boolean = False, _
121                                          Optional ByVal resizeFanart As Integer = 0, _
122                                          Optional ByVal retcachename As Boolean = False, _
123                                          Optional ByRef strValue As String = "") As Boolean
124
125        Dim CacheFileName As String = ""
126        Dim returnCode As Boolean = SaveImageToCache(URL, Path, ForceDownload, CacheFileName)
127        If returnCode Then
128            Dim CachePath As String = IO.Path.Combine(CacheFolder, CacheFileName)
129            If String.IsNullOrEmpty(Path) Then
130                strValue = IO.File.ReadAllText(CachePath)
131            Else
132                If Not retcachename Then
133                    Utilities.copyImage(CachePath, Path, resizeFanart)
134                Else
135                    strValue = CachePath 
136                End If
137            End If
138        End If
139        DownloadFileAndCache = returnCode
140        Return returncode
141    End Function
142
143    Public Shared Function SaveImageToCache(ByVal URL As String, ByVal Path As String, ByVal ForceDownload As Boolean, ByRef CacheFileName As String) As Boolean
144        Dim returnCode As Boolean = True
145        Dim CachePath As String = ""
146        Try
147            Utilities.EnsureFolderExists(CacheFolder)
148
149            If URL = "" Then Return False
150            CacheFileName = GetCacheFileName(URL)
151            CachePath = IO.Path.Combine(CacheFolder, CacheFileName)
152
153            If Not File.Exists(CachePath) OrElse ForceDownload Then
154
155                'Check to see if URL is actually a local file
156                If Not URL.Contains("://") AndAlso File.Exists(URL) Then
157                    If CachePath <> URL Then
158                        If Utilities.SafeDeleteFile(CachePath) Then
159                            File.Copy(URL, CachePath)
160                        End If
161                    End If
162                    Return True
163                End If
164
165                If ForceDownload AndAlso File.Exists(CachePath) Then File.Delete(CachePath)
166
167                Try
168                    Dim webReq As HttpWebRequest = DirectCast(WebRequest.Create(URL), HttpWebRequest)
169                    webReq.Proxy = Utilities.MyProxy
170                    webReq.AllowAutoRedirect = True
171                    webReq.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
172
173                    Using webResp As HttpWebResponse = webReq.GetResponse()
174                        Using responseStreamData As Stream = webResp.GetResponseStream()
175                            'got a response - should probably put a Try...Catch in here for filesystem stuff, but I'll wing it for now.
176                            If String.IsNullOrEmpty(Path) Then
177                                IO.File.WriteAllText(CachePath, New StreamReader(responseStreamData, Encoding.UTF8).ReadToEnd)
178                            Else
179                                Utilities.SafeDeleteFile(CachePath)
180
181                                Using fileStream As New FileStream(CachePath, FileMode.OpenOrCreate, FileAccess.Write)
182                                    Dim buffer(webResp.ContentLength) As Byte
183                                    Dim bytesRead = responseStreamData.Read(buffer, 0, buffer.Length)
184                                    While bytesRead > 0
185                                        fileStream.Write(buffer, 0, bytesRead)
186                                        bytesRead = responseStreamData.Read(buffer, 0, buffer.Length)
187                                    End While
188                                End Using
189                            End If
190                        End Using
191                    End Using
192                    If (New IO.FileInfo(CachePath)).Length = 0 Then
193                        File.Delete(CachePath)
194                        returnCode = False
195                    End If
196                Catch ex As WebException
197                    If ex.Message.Contains("could not be resolved") Then Return False : Exit Try
198                    Using errorResp As HttpWebResponse = DirectCast(ex.Response, HttpWebResponse)
199                        Using errorRespStream As Stream = errorResp.GetResponseStream()
200                            Dim errorText As String = New StreamReader(errorRespStream).ReadToEnd()
201
202                            'Writing to TvLog! -> Poo -> To do anyone -> Raise event?
203                            returnCode = False
204                            'Utilities.tvScraperLog &= String.Format("**** Scraper Error: Code {0} ****{3}     {2}{3}", errorResp.StatusCode, vbCrLf)
205                        End Using
206                    End Using
207                    returnCode = False
208                End Try
209            End If
210        Catch ex As Exception
211            'MsgBox(ex.Message.ToString & vbCrLf & "URL string =" & URL & vbCrLf & "cachefolder = " & CacheFolder & vbCrLf & "path = " & Path)
212            returnCode = False
213        End Try
214        Return returnCode
215    End Function
216
217    Public Shared Function Savexmltopath(ByVal URL As String, ByVal Path As String, ByVal filename As String, ByVal ForceDownload As Boolean) As Boolean
218        Dim returnCode As Boolean = True
219        Dim Fullpath As String = Path & filename
220        Try
221            Utilities.EnsureFolderExists(Path)
222            If URL = "" Then Return False
223            If Not File.Exists(Fullpath) OrElse ForceDownload Then
224                If ForceDownload AndAlso File.Exists(Fullpath) Then
225                    File.Delete(Fullpath)
226                End If
227                Try
228                    Dim webReq As HttpWebRequest = DirectCast(WebRequest.Create(URL), HttpWebRequest)
229                    webReq.Proxy = Utilities.MyProxy
230                    webReq.AllowAutoRedirect = True
231                    webReq.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
232                    Using webResp As HttpWebResponse = webReq.GetResponse()
233                        Using responseStreamData As Stream = webResp.GetResponseStream()
234                            IO.File.WriteAllText(Fullpath, New StreamReader(responseStreamData, Encoding.UTF8).ReadToEnd)
235                        End Using
236                    End Using
237                Catch ex As WebException
238                    If ex.Message.Contains("could not be resolved") Then Return False : Exit Try
239                    Using errorResp As HttpWebResponse = DirectCast(ex.Response, HttpWebResponse)
240                        Using errorRespStream As Stream = errorResp.GetResponseStream()
241                            Dim errorText As String = New StreamReader(errorRespStream).ReadToEnd()
242                            returnCode = False
243                        End Using
244                    End Using
245                    returnCode = False
246                End Try
247            End If
248        Catch ex As Exception
249            MsgBox(ex.Message.ToString & vbCrLf & "URL string =" & URL & vbCrLf & "Filename = " & filename & vbCrLf & "path = " & Path)
250            returnCode = False
251        End Try
252        Return returnCode
253    End Function
254
255End Class
256
257
258
259
260
261