@@ -188,37 +188,40 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
188188 val request = Request .Builder ().url(urlString).build()
189189
190190 try {
191- val response = client.newCall(request).execute()
192- if (! response.isSuccessful) {
193- Timber .e(" Failed to download attachment: ${response.code} " )
194- response.close()
195- return null
196- }
191+ client.newCall(request).execute().use { response ->
192+ if (! response.isSuccessful) {
193+ Timber .e(" Failed to download attachment: ${response.code} " )
194+ return null
195+ }
197196
198- val maxSizeBytes = 1.5 * 1024 * 1024 // most (modern?) carriers have a 2MB limit, so targetting 1.5MB should be safe
199- val contentLength = response.body?.contentLength() ? : - 1L
200- if (contentLength > maxSizeBytes) {
201- Timber .e(" Attachment is too large ($contentLength bytes)." )
202- response.close()
203- return null
204- }
197+ val body = response.body
198+ if (body == null ) {
199+ Timber .e(" Failed to download attachment: response body is null" )
200+ return null
201+ }
205202
206- val mmsDir = File (context.cacheDir, " mms_attachments" )
207- if (! mmsDir.exists()) {
208- mmsDir.mkdirs()
209- }
203+ val maxSizeBytes = 1.5 * 1024 * 1024 // most (modern?) carriers have a 2MB limit, so targetting 1.5MB should be safe
204+ val contentLength = body.contentLength()
205+ if (contentLength > maxSizeBytes) {
206+ Timber .e(" Attachment is too large ($contentLength bytes)." )
207+ return null
208+ }
210209
211- val tempFile = File (mmsDir, " mms_${messageId} _$attachmentIndex " )
212- val inputStream = response.body?.byteStream()
213- val outputStream = FileOutputStream (tempFile)
214-
215- inputStream?.copyToWithLimit(outputStream, maxSizeBytes.toLong())
216-
217- outputStream.close()
218- inputStream?.close()
219- response.close()
210+ val mmsDir = File (context.cacheDir, " mms_attachments" )
211+ if (! mmsDir.exists()) {
212+ mmsDir.mkdirs()
213+ }
214+
215+ val tempFile = File (mmsDir, " mms_${messageId} _$attachmentIndex " )
216+ val inputStream = body.byteStream()
217+ FileOutputStream (tempFile).use { outputStream ->
218+ inputStream.use { input ->
219+ input.copyToWithLimit(outputStream, maxSizeBytes.toLong())
220+ }
221+ }
220222
221- return tempFile
223+ return tempFile
224+ }
222225 } catch (e: Exception ) {
223226 Timber .e(e, " Exception while downloading attachment" )
224227 return null
0 commit comments