@@ -13,6 +13,9 @@ import java.util.logging.Level
1313import java.util.logging.Logger.getLogger
1414import java.io.File
1515import java.io.FileOutputStream
16+ import java.io.IOException
17+ import java.io.InputStream
18+ import java.io.OutputStream
1619
1720
1821class HttpSmsApiService (private val apiKey : String , private val baseURL : URI ) {
@@ -158,6 +161,28 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
158161 return true
159162 }
160163
164+ fun InputStream.copyToWithLimit (
165+ out : OutputStream ,
166+ limit : Long ,
167+ bufferSize : Int = DEFAULT_BUFFER_SIZE
168+ ): Long {
169+ var bytesCopied: Long = 0
170+ val buffer = ByteArray (bufferSize)
171+ var bytes = read(buffer)
172+
173+ while (bytes >= 0 ) {
174+ bytesCopied + = bytes
175+
176+ if (bytesCopied > limit) {
177+ throw IOException (" Download aborted: File exceeded maximum allowed size of $limit bytes." )
178+ }
179+
180+ out .write(buffer, 0 , bytes)
181+ bytes = read(buffer)
182+ }
183+ return bytesCopied
184+ }
185+
161186 // Downloads the attachment URL content locally
162187 fun downloadAttachment (context : Context , urlString : String , messageId : String , attachmentIndex : Int ): File ? {
163188 val request = Request .Builder ().url(urlString).build()
@@ -186,18 +211,13 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
186211 val tempFile = File (mmsDir, " mms_${messageId} _$attachmentIndex " )
187212 val inputStream = response.body?.byteStream()
188213 val outputStream = FileOutputStream (tempFile)
189- inputStream?.copyTo(outputStream)
214+
215+ inputStream?.copyToWithLimit(outputStream, maxSizeBytes.toLong())
190216
191217 outputStream.close()
192218 inputStream?.close()
193219 response.close()
194220
195- if (tempFile.length() > maxSizeBytes) {
196- tempFile.delete()
197- Timber .e(" Downloaded file exceeded 1.5MB limit." )
198- return null
199- }
200-
201221 return tempFile
202222 } catch (e: Exception ) {
203223 Timber .e(e, " Exception while downloading attachment" )
0 commit comments