forked from ankidroid/Anki-Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedia.kt
More file actions
175 lines (154 loc) · 6.6 KB
/
Media.kt
File metadata and controls
175 lines (154 loc) · 6.6 KB
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
/****************************************************************************************
* Copyright (c) 2011 Kostas Spyropoulos <inigo.aldana@gmail.com> *
* Copyright (c) 2014 Houssam Salem <houssam.salem.au@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki
import androidx.annotation.WorkerThread
import anki.media.CheckMediaResponse
import com.google.protobuf.kotlin.toByteString
import com.ichi2.libanki.Media.Companion.htmlMediaRegexps
import com.ichi2.libanki.TemplateManager.TemplateRenderContext.TemplateRenderOutput
import com.ichi2.libanki.exception.EmptyMediaException
import com.ichi2.libanki.utils.LibAnkiAlias
import com.ichi2.libanki.utils.NotInLibAnki
import timber.log.Timber
import java.io.File
/**
* Media manager - handles the addition and removal of media files from the media directory (collection.media) and
* maintains the media database, which is used to determine the state of files for syncing.
*/
@WorkerThread
open class Media(
private val col: Collection,
) {
val dir = col.collectionFiles.mediaFolder
init {
Timber.v("dir %s", dir)
val file = dir
if (!file.exists()) {
file.mkdirs()
}
}
/*
Adding media
***********************************************************
*/
fun addFile(oFile: File?): String {
if (oFile == null || oFile.length() == 0L) {
throw EmptyMediaException()
}
Timber.v("dir now %s", dir)
return col.backend.addMediaFile(oFile.name, oFile.readBytes().toByteString())
}
/*
* String manipulation
* ***********************************************************
*/
/**
* Extract media filenames from an HTML string.
*
* @param currentCard The card to scan for media filenames ([sound:...] or <img...>).
* @return A distinct, unordered list containing all the sound and image filenames found in the card.
*/
@LibAnkiAlias("files_in_str")
fun filesInStr(
renderOutput: TemplateRenderOutput,
includeRemote: Boolean = false,
): List<String> {
val files = mutableListOf<String>()
val processedText = LaTeX.mungeQA(renderOutput.questionText + renderOutput.answerText, col, true)
for (pattern in htmlMediaRegexps) {
val matches = pattern.findAll(processedText)
for (match in matches) {
val fname = pattern.extractFilename(match) ?: continue
val isLocal = !Regex("(?i)https?|ftp://").containsMatchIn(fname)
if (isLocal || includeRemote) {
files.add(fname)
}
}
}
// not in libAnki: the rendered output no longer contains [sound:] tags
files.addAll(
(renderOutput.questionAvTags + renderOutput.answerAvTags)
.filterIsInstance<SoundOrVideoTag>()
.map { it.filename },
)
return files.distinct()
}
fun findUnusedMediaFiles(): List<File> = check().unusedList.map { File(dir, it) }
/**
* [IRI](https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier) encodes media
*
* `foo bar` -> `foo%20bar`
*/
fun escapeMediaFilenames(
string: String,
unescape: Boolean = false,
): String =
if (unescape) {
col.backend.decodeIriPaths(string)
} else {
col.backend.encodeIriPaths(string)
}
/*
Rebuilding DB
***********************************************************
*/
fun check(): CheckMediaResponse = col.backend.checkMedia()
@LibAnkiAlias("empty_trash")
fun emptyTrash() = col.backend.emptyTrash()
/**
* Copying on import
* ***********************************************************
*/
open fun have(fname: String): Boolean = File(dir, fname).exists()
open fun forceResync() {
col.backend.removeMediaDb(colPath = col.colDb.absolutePath)
}
// FIXME: this currently removes files immediately, as the UI does not expose a way
/** Move provided files to the trash. */
@LibAnkiAlias("trash_files")
fun trashFiles(fnames: Iterable<String>) {
col.backend.trashMediaFiles(fnames = fnames)
}
@LibAnkiAlias("restore_trash")
fun restoreTrash() = col.backend.restoreTrash()
companion object {
/**
* Given a [media regex][htmlMediaRegexps] and a match, return the captured media filename
*/
@NotInLibAnki
private fun Regex.extractFilename(match: MatchResult): String? {
val index =
when (htmlMediaRegexps.indexOf(this)) {
0, 2 -> 3
1, 3 -> 2
else -> throw IllegalStateException(pattern)
}
return match.groups[index]?.value
}
val htmlMediaRegexps =
listOf(
// src element quoted case (img/audio)
Regex("(?i)(<(?:img|audio)\\b[^>]* src=(['\"])([^>]+?)\\2[^>]*>)"), // Group 3 = fname
// unquoted src (img/audio)
Regex("(?i)(<(?:img|audio)\\b[^>]* src=(?!['\"])([^ >]+)[^>]*?>)"), // Group 2 = fname
// quoted data attribute (object)
Regex("(?i)(<object\\b[^>]* data=(['\"])([^>]+?)\\2[^>]*>)"), // Group 3 = fname
// unquoted data attribute (object)
Regex("(?i)(<object\\b[^>]* data=(?!['\"])([^ >]+)[^>]*?>)"), // Group 2 = fname
)
}
}