View paste

User name: Thomas Baumann

Description: OTR Downloader 1.0

Date/Time: 21.05.2016 12:17:04

Highlight: Vb

''' <summary>Module where the application starts</summary>
Friend Module App

	' Constants for OTR free download time (for security added 10 minutes)
	Private ReadOnly StartTime As New TimeSpan(0, 10, 0)	' 0:10
	Private ReadOnly EndTime As New TimeSpan(7, 50, 0)		' 7:50

	' Buffer size for downloading (32KB)
	Private Const BufferSize As Integer = 32 * 1024 - 1

	' Number format for bytes received / total
	Private Const NumberFormat As String = "###,###,###,##0"



	''' <summary>Entry point for the application</summary>
	''' <param name="Args">The commandline arguments (if set)</param>
	''' <returns>Usually 0 (on success) or something else if something really went wrong</returns>
	Friend Function Main(ByVal Args As String()) As Integer

		' Show header
		Console.CursorVisible = False
		Console.ForegroundColor = ConsoleColor.White
		Console.WriteLine("OTR downloader 1.0 - http://tightDev.net")
		Console.ResetColor()
		Console.WriteLine()

		' Get input file
		Dim InFile As String
		If Args.Length = 1 Then
			InFile = Args(0)
		Else
			InFile = ".\Queue.txt"
		End If

		' Check if it exists
		If Not File.Exists(InFile) Then
			Console.WriteLine("Datei "".\Queue.txt"" nicht gefunden und es wurde keine andere Datei angegeben! Abbruch...")
			Return -1
		End If

		' Open input data and parse it
		Dim FileData As String() = File.ReadAllLines(InFile)
		Dim Queue As New List(Of Uri)
		For Each Line As String In FileData
			Try
				If String.IsNullOrEmpty(Line.Trim) Then Continue For
				If Line.StartsWith("#"c) Then Continue For
				If Line.Contains("#") Then Line = Line.Substring(0, Line.IndexOf("#"))
				Line = Line.Trim
				Queue.Add(New Uri(Line))
			Catch
				Console.ForegroundColor = ConsoleColor.Red
				Console.WriteLine("Fehler in URL: " & Line)
				Console.ResetColor()
				Queue.RemoveAt(0)
				Continue For
			End Try
		Next

		' Display found links
		Console.WriteLine(Queue.Count.ToString & " Links gefunden")
		Console.WriteLine()

		' Now loop through each link
		Do While Queue.Count > 0

			' Cache current time
			Dim Now As TimeSpan = DateTime.Now.TimeOfDay

			' Check free download time
			If Now < StartTime OrElse Now > EndTime Then

				' Not within the free time, display warning and wait
				Console.Write("Aktuelle Zeit außerhalb der Gratis Zeit (" & StartTime.ToString & " - " & EndTime.ToString & "). Warte...")
				Console.CursorLeft = 0
				Threading.Thread.Sleep(30000)

			Else

				' Download time is ok, start it. If successful remove it from queue
				If DownloadFile(Queue(0)) Then

					' Download successful
					Queue.RemoveAt(0)

					' Display message
					Console.WriteLine("Fertig. Warte 60 Sekunden vor dem nächsten Download...")
					Threading.Thread.Sleep(60000)

				Else

					' Download failed, wait 60 seconds and try again
					Console.WriteLine("Nächster Versuch in 60 Sekunden...")
					Threading.Thread.Sleep(60000)

				End If

			End If

		Loop

		' Display finished message
		Console.WriteLine()
		Console.ForegroundColor = ConsoleColor.Green
		Console.WriteLine("Alle downloads fertig!")
		Console.ResetColor()
		Console.WriteLine()
		Console.WriteLine("Beliebige Taste zum Beenden...")
		Console.ReadKey()

		Return 0

	End Function



	''' <summary>Downloads a file using the http protocol</summary>
	''' <param name="Url">The Url to the file to download</param>
	''' <returns>Returns True if the file was downloaded successfully, False otherwise.</returns>
	Private Function DownloadFile(ByVal Url As Uri) As Boolean

		' Get the file name and prepare result
		Dim File As String = Url.Segments(Url.Segments.Length - 1)
		Dim Result As Boolean

		' Show the file name which will be downloaded
		Console.WriteLine(File)

		Try

			' Create Request and get response
			Dim Request As HttpWebRequest = DirectCast(HttpWebRequest.CreateDefault(Url), HttpWebRequest)
			Dim Response As HttpWebResponse = DirectCast(Request.GetResponse, HttpWebResponse)

			' Check for correct status code
			If Response.StatusCode <> 200 Then
				Console.ForegroundColor = ConsoleColor.Red
				Console.WriteLine("Fehler: " & Response.StatusDescription)
				Console.ResetColor()
				Return False
			End If

			' Create the file and response stream
			Using OutStream As New FileStream(File, FileMode.Create, FileAccess.Write, FileShare.Read, BufferSize)
				Using InStream As Stream = Response.GetResponseStream

					' Download the file
					Result = StreamCopy(InStream, OutStream, Response.ContentLength)

				End Using
			End Using

		Catch ex As Exception

			' Display error mesage
			Console.WriteLine()
			Console.ForegroundColor = ConsoleColor.Red
			Console.WriteLine("Fehler: " & ex.Message)
			Console.ResetColor()
			Result = False

		End Try

		' If not successful delete the incomplete file
		If Result = False AndAlso IO.File.Exists(File) Then IO.File.Delete(File)

		' Add a blank line and return result
		Console.WriteLine()
		Return Result

	End Function

	''' <summary>Copies data from one stream to another. Also statistics will be displayed on the console.</summary>
	''' <param name="InStream">The stream to read from</param>
	''' <param name="OutStream">The stream to write to</param>
	''' <param name="TotalLength">The total file length in bytes</param>
	''' <returns>True if the stream was copied, False if an error occoured</returns>
	Private Function StreamCopy(ByVal InStream As Stream, ByVal OutStream As Stream, ByVal TotalLength As Long) As Boolean

		' Prepare buffer and other variables
		Dim Buffer(BufferSize) As Byte
		Dim Length As Integer
		Dim Percent As Integer
		Dim Kbs As Integer
		Dim StartDate As DateTime = DateTime.UtcNow
		Dim Result As Boolean = True

		Do

			' Copy data
			Length = InStream.Read(Buffer, 0, Buffer.Length)
			If Length < 1 Then Exit Do
			OutStream.Write(Buffer, 0, Length)

			' Calculate statistic
			Percent = CInt(OutStream.Length / TotalLength * 100)
			Try
				Kbs = CInt((OutStream.Length / (DateTime.UtcNow - StartDate).TotalSeconds) / 1024)
			Catch : End Try

			' Display status
			Console.CursorLeft = 0
			Console.Write( _
			  OutStream.Length.ToString(NumberFormat) & " / " & _
			  TotalLength.ToString(NumberFormat) & "  " & _
			  "(" & Percent.ToString("##0") & "%, " & Kbs.ToString(NumberFormat) & "KB/s)   " _
			)

			' Check for time range, cancel if exceeded
			If DateTime.Now.TimeOfDay > EndTime Then
				Result = False
				Exit Do
			End If

		Loop

		Return Result

	End Function

End Module

Create new paste