-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
198 lines (178 loc) · 7.68 KB
/
app.js
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
window.addEventListener('DOMContentLoaded', function() {
'use strict';
var translate = navigator.mozL10n.get;
console.log(stripHTMLTags("<b>The left angle bracket, also known as <, is often used as a less than sign. On the other hand, the right angle bracket, known as >, is often used as a greater than sign.</b>"));
});
var bookCache = {};
var appUIState = new UIState({'bookCache': bookCache});
function stripHTMLTags(str) {
return str.replace(/<(?:.|\n)*?>/gm, '');
}
function Book(args) {
this.chapters = args.chapters
var json = args.json;
this.description = stripHTMLTags(json.description);
this.title = stripHTMLTags(json.title);
this.id = json.id;
this.fullBookURL = json.url_zip_file;
}
function Chapter(args) {
title_regex = /^<!\[CDATA\[(.*)\]\]>$/;
title_match = title_regex.exec(args.title);
this.title = stripHTMLTags(title_match[1] ? title_match[1] : args.title); // if regex doesn't match, fall back to raw string
this.index = args.index; // TODO: Add whenever this method is called, return current chapter or get it if not available
this.url = args.url;
this.position = 0;
}
function UIState(args) {
this.currentBook = args.currentBook;
this.currentChapter = args.currentChapter;
this.bookCache = args.bookCache; // to increase reausability of object - did not hard-code the coupling with our global bookCache
this.setCurrentBookById = function(id) {
this.currentBook = this.bookCache[id];
}
this.setCurrentChapterByIndex = function(index) {
this.currentChapter = this.currentBook.chapters[index];
}
}
$( document ).on( "pagecreate", "#chaptersListPage", function( event ) {
var selectedBook = appUIState.currentBook;
if (!selectedBook) { // selectedBook is undefined if you refresh the app from WebIDE on a chapter list page
console.warn("Chapters List: selectedBook was undefined, which freezes the app. Did you refresh from WebIDE?");
return false;
}
var generate_chapter_list_item = function (chapter) { // is this good coding practice? local method defined inside method
var chapterListItem = $('<li chapter-index=' + chapter.index + '><a href="book.html"><h2>' + chapter.title + '</h2></a></li>');
chapterListItem.click(function () {
appUIState.setCurrentChapterByIndex($(this).attr("chapter-index"));
});
$("#chaptersList").append(chapterListItem);
}
if (selectedBook.chapters != null) {
$.each(selectedBook.chapters, function(index, chapter) {
generate_chapter_list_item(chapter);
$("#chaptersList").listview('refresh');
});
} else {
getXML("https://librivox.org/rss/" + encodeURIComponent(selectedBook.id), function(xhr) {
var xml = $(xhr.response),
$items = xml.find("item"),
chapters = [];
$items.each(function(index, element) {
var $title = $(element).find("title")
var $enclosure = $(element).find("enclosure");
var chapter = new Chapter({'index': chapters.length, 'title': $title.text(), 'url': $enclosure.attr('url')})
chapters.push(chapter);
generate_chapter_list_item(chapter);
});
selectedBook.chapters = chapters;
$("#chaptersList").listview('refresh');
});
}
});
$( document ).on( "pagecreate", "#homeBook", function( event ){
$(".ui-slider-input").hide();
$(".ui-slider-handle").hide(); // Issue here - the page isn't refreshing onLoad. As a result? Slider isn't keeping CSS values
$("#downloadProgress").val(0).slider("refresh"); // This and the two lines before can be removed once fixed
var id = appUIState.currentBook.id;
$("#downloadFullBook").click(function(){
var url = appUIState.currentBook.fullBookURL;
downloadBook(url, id);
});
$("#downloadPart").click(function(){
var url = appUIState.currentChapter.url;
downloadBook(url, id);
});
var url = appUIState.currentChapter.url;
$("#audioSource").prop('type', "audio/mpeg");
$("#audioSource").prop("src", url);
$("#audioSource").trigger('load'); // Probably a better way to do this... loadAudio(src) method?
$("#audioSource").on("timeupdate", function () {
appUIState.currentChapter.position = this.currentTime;
});
});
$( document ).on( "pagecreate", "#homeFileManager", function(){ // TODO work only in LibriFox directory
var sdcard = navigator.getDeviceStorage('sdcard');
var request = sdcard.enumerate();
request.onsuccess = function(){
if(this.result){
fileListItem = $('<li><a data-icon="delete">' + this.result.name + '</a></li>');
fileListItem.click(function(){
});
$("#downloadedFiles").append(fileListItem);
this.continue();
};
$("#downloadedFiles").listview('refresh');
};
request.onerror = function(){
console.log("No data found on SDCard!");
$("#noAvailableDownloads").show();
}
});
function downloadBook(URL, id) {
var sdcard = navigator.getDeviceStorage("sdcard");
var progress_callback = function (event) {
if(event.lengthComputable){
var percentage = (event.loaded / event.total) * 100;
$("#downloadProgress").val(percentage).slider('refresh');
}
}
getBlob(URL, function(xhr) {
var filename = URL.substring(URL.lastIndexOf('/')+1);
sdcard.addNamed(xhr.response, filename); // TODO folder with id name ie /librifox/id/
}, {'progress_callback': progress_callback});
}
$("#newSearch").submit(function(event){
$("#booksList").empty();
var input = $("#bookSearch").val();
console.log(encodeURIComponent(input));
getJSON("https://librivox.org/api/feed/audiobooks/title/^" + encodeURIComponent(input) + "?&format=json",function(xhr) {
if (!xhr.response.books) {
$("#noAvailableBooks").show();
}
else {
xhr.response.books.forEach(function(entry) {
var book = new Book({'json': entry});
bookCache[book.id] = book; // this ends up storing id 3 times (as key, in book object, and in book object json)
bookListItem = $('<li book-id="' + book.id + '"><a href="chapters.html"><h2>' + book.title + '</h2><p>' + book.description + '</p></a></li>');
bookListItem.click(function(){
appUIState.setCurrentBookById($(this).attr("book-id"));
});
$("#booksList").append(bookListItem);
});
}
$("#booksList").listview('refresh');
});
return false;
});
function getDataFromUrl(url, type, load_callback, other_args) // NEEDS MORE MAGIC STRINGS
{
other_args = other_args || {};
var xhr = new XMLHttpRequest({ mozSystem: true });
if (xhr.overrideMimeType && type == 'json') {
xhr.overrideMimeType('application/json');
}
other_args.error_callback = other_args.error_callback || function(e) {
console.log("error loading json from url " + url);
console.log(e);
}
other_args.timeout_callback = other_args.timeout_callback || function(e) {
console.log("timeout loading json from url " + url);
console.log(e);
}
xhr.addEventListener('load', function(e) {
load_callback(xhr,e);
});
xhr.addEventListener('error', other_args.error_callback);
xhr.addEventListener('timeout', other_args.timeout_callback);
xhr.addEventListener('progress', other_args.progress_callback);
// xhr.upload.addEventListener("load", transferComplete, false);
// xhr.upload.addEventListener("error", transferFailed, false);
// xhr.upload.addEventListener("abort", transferCanceled, false);
xhr.open('GET', url);
if (type != 'default') { xhr.responseType = type; }
xhr.send();
}
function getJSON(url, load_callback, other_args) { getDataFromUrl(url, 'json', load_callback, other_args); }
function getXML(url, load_callback, other_args) { getDataFromUrl(url, 'default', load_callback, other_args); }
function getBlob(url, load_callback, other_args) { getDataFromUrl(url, 'blob', load_callback, other_args); }