code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('clearhtml', function(K) { var self = this, name = 'clearhtml'; self.clickToolbar(name, function() { self.focus(); var html = self.html(); html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, ''); html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, ''); html = K.formatHtml(html, { a : ['href', 'target'], embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'], img : ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'], table : ['border'], 'td,th' : ['rowspan', 'colspan'], 'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [] }); self.html(html); self.cmd.selection(true); self.addBookmark(); }); });
zzblog
web/js/kindeditor/plugins/clearhtml/clearhtml.js
JavaScript
asf20
1,185
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('image', function(K) { var self = this, name = 'image', allowImageUpload = K.undef(self.allowImageUpload, true), allowFileManager = K.undef(self.allowFileManager, false), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'), imgPath = self.basePath + 'plugins/image/images/', lang = self.lang(name + '.'); self.plugin.imageDialog = function(options) { var imageUrl = K.undef(options.imageUrl, 'http://'), imageWidth = K.undef(options.imageWidth, ''), imageHeight = K.undef(options.imageHeight, ''), imageTitle = K.undef(options.imageTitle, ''), imageAlign = K.undef(options.imageAlign, ''), clickFn = options.clickFn; var html = [ '<div style="padding:10px 20px;">', //tabs '<div class="tabs"></div>', //url or file '<div class="ke-dialog-row">', '<div class="tab1" style="display:none;">', '<label for="keUrl" style="width:60px;">' + lang.remoteUrl + '</label>', '<input type="text" id="keUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> &nbsp;', '<span class="ke-button-common ke-button-outer">', '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />', '</span>', '</div>', '<div class="tab2" style="display:none;">', '<label style="width:60px;">' + lang.localUrl + '</label>', '<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> &nbsp;', '<input type="button" class="ke-upload-button" value="' + lang.viewServer + '" />', '</div>', '</div>', //size '<div class="ke-dialog-row">', '<label for="keWidth" style="width:60px;">' + lang.size + '</label>', lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ', lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ', '<img class="ke-refresh-btn" src="' + imgPath + 'refresh.gif" width="16" height="16" alt="" style="cursor:pointer;" />', '</div>', //align '<div class="ke-dialog-row">', '<label style="width:60px;">' + lang.align + '</label>', '<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />', ' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />', ' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />', '</div>', //title '<div class="ke-dialog-row">', '<label for="keTitle" style="width:60px;">' + lang.imgTitle + '</label>', '<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:200px;" /></div>', '</div>', '</div>' ].join(''); var dialogWidth = allowImageUpload ? 450 : 400; dialogHeight = allowImageUpload ? 300 : 250; var dialog = self.createDialog({ name : name, width : dialogWidth, height : dialogHeight, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { // insert local image if (tabs && tabs.selectedIndex === 1) { dialog.showLoading(self.lang('uploadLoading')); uploadbutton.submit(); localUrlBox.val(''); return; } // insert remote image var url = K.trim(urlBox.val()), width = widthBox.val(), height = heightBox.val(), title = titleBox.val(), align = ''; alignBox.each(function() { if (this.checked) { align = this.value; return false; } }); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } clickFn.call(self, url, title, width, height, 0, align); } }, beforeRemove : function() { viewServerBtn.remove(); widthBox.remove(); heightBox.remove(); refreshBtn.remove(); uploadbutton.remove(); } }), div = dialog.div; var tabs; if (allowImageUpload) { tabs = K.tabs({ src : K('.tabs', div), afterSelect : function(i) { } }); tabs.add({ title : lang.remoteImage, panel : K('.tab1', div) }); tabs.add({ title : lang.localImage, panel : K('.tab2', div) }); tabs.select(0); } else { K('.tab1', div).show(); } var urlBox = K('[name="url"]', div), localUrlBox = K('[name="localUrl"]', div), viewServerBtn = K('[name="viewServer"]', div), widthBox = K('[name="width"]', div), heightBox = K('[name="height"]', div), refreshBtn = K('.ke-refresh-btn', div), titleBox = K('[name="title"]', div), alignBox = K('[name="align"]'); var uploadbutton = K.uploadbutton({ button : K('.ke-upload-button', div)[0], fieldName : 'imgFile', url : K.addParam(uploadJson, 'dir=image'), afterUpload : function(data) { dialog.hideLoading(); if (data.error === 0) { var width = widthBox.val(), height = heightBox.val(), title = titleBox.val(), align = ''; alignBox.each(function() { if (this.checked) { align = this.value; return false; } }); var url = K.formatUrl(data.url, 'absolute'); clickFn.call(self, url, title, width, height, 0, align); if (self.afterUpload) { self.afterUpload.call(self, url); } } else { alert(data.message); } }, afterError : function(html) { dialog.hideLoading(); self.errorDialog(html); } }); uploadbutton.fileBox.change(function(e) { localUrlBox.val(uploadbutton.fileBox.val()); }); if (allowFileManager) { viewServerBtn.click(function(e) { self.loadPlugin('filemanager', function() { self.plugin.filemanagerDialog({ viewType : 'VIEW', dirName : 'image', clickFn : function(url, title) { if (self.dialogs.length > 1) { K('[name="url"]', div).val(url); self.hideDialog(); } } }); }); }); } else { viewServerBtn.hide(); } var originalWidth = 0, originalHeight = 0; function setSize(width, height) { widthBox.val(width); heightBox.val(height); originalWidth = width; originalHeight = height; } refreshBtn.click(function(e) { var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({ position : 'absolute', visibility : 'hidden', top : 0, left : '-1000px' }); K(document.body).append(tempImg); setSize(tempImg.width(), tempImg.height()); tempImg.remove(); }); widthBox.change(function(e) { if (originalWidth > 0) { heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10))); } }); heightBox.change(function(e) { if (originalHeight > 0) { widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10))); } }); urlBox.val(options.imageUrl); setSize(options.imageWidth, options.imageHeight); titleBox.val(options.imageTitle); alignBox.each(function() { if (this.value === options.imageAlign) { this.checked = true; return false; } }); urlBox[0].focus(); urlBox[0].select(); return dialog; }; self.plugin.image = { edit : function() { var img = self.plugin.getSelectedImage(); self.plugin.imageDialog({ imageUrl : img ? img.attr('data-ke-src') : 'http://', imageWidth : img ? img.width() : '', imageHeight : img ? img.height() : '', imageTitle : img ? img.attr('title') : '', imageAlign : img ? img.attr('align') : '', clickFn : function(url, title, width, height, border, align) { self.exec('insertimage', url, title, width, height, border, align); // Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog setTimeout(function() { self.hideDialog().focus(); }, 0); } }); }, 'delete' : function() { self.plugin.getSelectedImage().remove(); } }; self.clickToolbar(name, self.plugin.image.edit); });
zzblog
web/js/kindeditor/plugins/image/image.js
JavaScript
asf20
9,119
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('wordpaste', function(K) { var self = this, name = 'wordpaste'; self.clickToolbar(name, function() { var lang = self.lang(name + '.'), html = '<div style="padding:10px 20px;">' + '<div style="margin-bottom:10px;">' + lang.comment + '</div>' + '<iframe class="ke-textarea" frameborder="0" style="width:408px;height:260px;"></iframe>' + '</div>', dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var str = doc.body.innerHTML; str = K.clearMsWord(str, self.filterMode ? self.htmlTags : K.options.htmlTags); self.insertHtml(str).hideDialog().focus(); } } }), div = dialog.div, iframe = K('iframe', div), doc = K.iframeDoc(iframe); if (!K.IE) { doc.designMode = 'on'; } doc.open(); doc.write('<!doctype html><html><head><title>WordPaste</title></head>'); doc.write('<body style="background-color:#FFF;font-size:12px;margin:2px;">'); if (!K.IE) { doc.write('<br />'); } doc.write('</body></html>'); doc.close(); if (K.IE) { doc.body.contentEditable = 'true'; } iframe[0].contentWindow.focus(); }); });
zzblog
web/js/kindeditor/plugins/wordpaste/wordpaste.js
JavaScript
asf20
1,663
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('flash', function(K) { var self = this, name = 'flash', lang = self.lang(name + '.'), allowFlashUpload = K.undef(self.allowFlashUpload, true), allowFileManager = K.undef(self.allowFileManager, false), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'); self.plugin.flash = { edit : function() { var html = [ '<div style="padding:10px 20px;">', //url '<div class="ke-dialog-row">', '<label for="keUrl" style="width:60px;">' + lang.url + '</label>', '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> &nbsp;', '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;', '<span class="ke-button-common ke-button-outer">', '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />', '</span>', '</div>', //width '<div class="ke-dialog-row">', '<label for="keWidth" style="width:60px;">' + lang.width + '</label>', '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" /> ', '</div>', //height '<div class="ke-dialog-row">', '<label for="keHeight" style="width:60px;">' + lang.height + '</label>', '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" /> ', '</div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 450, height : 200, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var url = K.trim(urlBox.val()), width = widthBox.val(), height = heightBox.val(); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } var html = K.mediaImg(self.themesPath + 'common/blank.gif', { src : url, type : K.mediaType('.swf'), width : width, height : height, quality : 'high' }); self.insertHtml(html).hideDialog().focus(); } } }), div = dialog.div, urlBox = K('[name="url"]', div), viewServerBtn = K('[name="viewServer"]', div), widthBox = K('[name="width"]', div), heightBox = K('[name="height"]', div); urlBox.val('http://'); if (allowFlashUpload) { var uploadbutton = K.uploadbutton({ button : K('.ke-upload-button', div)[0], fieldName : 'imgFile', url : K.addParam(uploadJson, 'dir=flash'), afterUpload : function(data) { dialog.hideLoading(); if (data.error === 0) { var url = K.formatUrl(data.url, 'absolute'); urlBox.val(url); if (self.afterUpload) { self.afterUpload.call(self, url); } alert(self.lang('uploadSuccess')); } else { alert(data.message); } }, afterError : function(html) { dialog.hideLoading(); self.errorDialog(html); } }); uploadbutton.fileBox.change(function(e) { dialog.showLoading(self.lang('uploadLoading')); uploadbutton.submit(); }); } else { K('.ke-upload-button', div).hide(); urlBox.width(250); } if (allowFileManager) { viewServerBtn.click(function(e) { self.loadPlugin('filemanager', function() { self.plugin.filemanagerDialog({ viewType : 'LIST', dirName : 'flash', clickFn : function(url, title) { if (self.dialogs.length > 1) { K('[name="url"]', div).val(url); self.hideDialog(); } } }); }); }); } else { viewServerBtn.hide(); } var img = self.plugin.getSelectedFlash(); if (img) { var attrs = K.mediaAttrs(img.attr('data-ke-tag')); urlBox.val(attrs.src); widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0); heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0); } urlBox[0].focus(); urlBox[0].select(); }, 'delete' : function() { self.plugin.getSelectedFlash().remove(); } }; self.clickToolbar(name, self.plugin.flash.edit); });
zzblog
web/js/kindeditor/plugins/flash/flash.js
JavaScript
asf20
4,964
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('table', function(K) { var self = this, name = 'table', lang = self.lang(name + '.'), zeroborder = 'ke-zeroborder'; // 取得下一行cell的index function _getCellIndex(table, row, cell) { var rowSpanCount = 0; for (var i = 0, len = row.cells.length; i < len; i++) { if (row.cells[i] == cell) { break; } rowSpanCount += row.cells[i].rowSpan - 1; } return cell.cellIndex - rowSpanCount; } self.plugin.table = { //insert or modify table prop : function(isInsert) { var html = [ '<div style="padding:10px 20px;">', //rows, cols '<div class="ke-dialog-row">', '<label for="keRows" style="width:90px;">' + lang.cells + '</label>', lang.rows + ' <input type="text" id="keRows" class="ke-input-text ke-input-number" name="rows" value="" maxlength="4" /> &nbsp; ', lang.cols + ' <input type="text" class="ke-input-text ke-input-number" name="cols" value="" maxlength="4" />', '</div>', //width, height '<div class="ke-dialog-row">', '<label for="keWidth" style="width:90px;">' + lang.size + '</label>', lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> &nbsp; ', '<select name="widthType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select> &nbsp; ', lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> &nbsp; ', '<select name="heightType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select>', '</div>', //space, padding '<div class="ke-dialog-row">', '<label for="kePadding" style="width:90px;">' + lang.space + '</label>', lang.padding + ' <input type="text" id="kePadding" class="ke-input-text ke-input-number" name="padding" value="" maxlength="4" /> &nbsp; ', lang.spacing + ' <input type="text" class="ke-input-text ke-input-number" name="spacing" value="" maxlength="4" />', '</div>', //align '<div class="ke-dialog-row">', '<label for="keAlign" style="width:90px;">' + lang.align + '</label>', '<select id="keAlign" name="align">', '<option value="">' + lang.alignDefault + '</option>', '<option value="left">' + lang.alignLeft + '</option>', '<option value="center">' + lang.alignCenter + '</option>', '<option value="right">' + lang.alignRight + '</option>', '</select>', '</div>', //border '<div class="ke-dialog-row">', '<label for="keBorder" style="width:90px;">' + lang.border + '</label>', lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> &nbsp; ', lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>', '</div>', //background color '<div class="ke-dialog-row">', '<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>', '<span class="ke-inline-block ke-input-color"></span>', '</div>', '</div>' ].join(''); var picker, currentElement; function removePicker() { if (picker) { picker.remove(); picker = null; currentElement = null; } } var dialog = self.createDialog({ name : name, width : 500, height : 300, title : self.lang(name), body : html, beforeDrag : removePicker, beforeRemove : function() { removePicker(); colorBox.unbind(); }, yesBtn : { name : self.lang('yes'), click : function(e) { var rows = rowsBox.val(), cols = colsBox.val(), width = widthBox.val(), height = heightBox.val(), widthType = widthTypeBox.val(), heightType = heightTypeBox.val(), padding = paddingBox.val(), spacing = spacingBox.val(), align = alignBox.val(), border = borderBox.val(), borderColor = K(colorBox[0]).html() || '', bgColor = K(colorBox[1]).html() || ''; if (rows == 0 || !/^\d+$/.test(rows)) { alert(self.lang('invalidRows')); rowsBox[0].focus(); return; } if (cols == 0 || !/^\d+$/.test(cols)) { alert(self.lang('invalidRows')); colsBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } if (!/^\d*$/.test(padding)) { alert(self.lang('invalidPadding')); paddingBox[0].focus(); return; } if (!/^\d*$/.test(spacing)) { alert(self.lang('invalidSpacing')); spacingBox[0].focus(); return; } if (!/^\d*$/.test(border)) { alert(self.lang('invalidBorder')); borderBox[0].focus(); return; } //modify table if (table) { if (width !== '') { table.width(width + widthType); } else { table.css('width', ''); } if (table[0].width !== undefined) { table.removeAttr('width'); } if (height !== '') { table.height(height + heightType); } else { table.css('height', ''); } if (table[0].height !== undefined) { table.removeAttr('height'); } table.css('background-color', bgColor); if (table[0].bgColor !== undefined) { table.removeAttr('bgColor'); } if (padding !== '') { table[0].cellPadding = padding; } else { table.removeAttr('cellPadding'); } if (spacing !== '') { table[0].cellSpacing = spacing; } else { table.removeAttr('cellSpacing'); } if (align !== '') { table[0].align = align; } else { table.removeAttr('align'); } if (border !== '') { table.attr('border', border); } else { table.removeAttr('border'); } if (border === '' || border === '0') { table.addClass(zeroborder); } else { table.removeClass(zeroborder); } if (borderColor !== '') { table.attr('borderColor', borderColor); } else { table.removeAttr('borderColor'); } self.hideDialog().focus(); return; } //insert new table var style = ''; if (width !== '') { style += 'width:' + width + widthType + ';'; } if (height !== '') { style += 'height:' + height + heightType + ';'; } if (bgColor !== '') { style += 'background-color:' + bgColor + ';'; } var html = '<table'; if (style !== '') { html += ' style="' + style + '"'; } if (padding !== '') { html += ' cellpadding="' + padding + '"'; } if (spacing !== '') { html += ' cellspacing="' + spacing + '"'; } if (align !== '') { html += ' align="' + align + '"'; } if (border !== '') { html += ' border="' + border + '"'; } if (border === '' || border === '0') { html += ' class="' + zeroborder + '"'; } if (borderColor !== '') { html += ' bordercolor="' + borderColor + '"'; } html += '>'; for (var i = 0; i < rows; i++) { html += '<tr>'; for (var j = 0; j < cols; j++) { html += '<td>' + (K.IE ? '&nbsp;' : '<br />') + '</td>'; } html += '</tr>'; } html += '</table>'; if (!K.IE) { html += '<br />'; } self.insertHtml(html); self.select().hideDialog().focus(); self.addBookmark(); } } }), div = dialog.div, rowsBox = K('[name="rows"]', div).val(3), colsBox = K('[name="cols"]', div).val(2), widthBox = K('[name="width"]', div).val(100), heightBox = K('[name="height"]', div), widthTypeBox = K('[name="widthType"]', div), heightTypeBox = K('[name="heightType"]', div), paddingBox = K('[name="padding"]', div).val(2), spacingBox = K('[name="spacing"]', div).val(0), alignBox = K('[name="align"]', div), borderBox = K('[name="border"]', div).val(1), colorBox = K('.ke-input-color', div); function setColor(box, color) { color = color.toUpperCase(); box.css('background-color', color); box.css('color', color === '#000000' ? '#FFFFFF' : '#000000'); box.html(color); } setColor(K(colorBox[0]), '#000000'); setColor(K(colorBox[1]), ''); function clickHandler(e) { removePicker(); if (!picker || this !== currentElement) { var box = K(this), pos = box.pos(); picker = K.colorpicker({ x : pos.x, y : pos.y + box.height(), z : 811214, selectedColor : K(this).html(), colors : self.colorTable, noColor : self.lang('noColor'), shadowMode : self.shadowMode, click : function(color) { setColor(box, color); removePicker(); } }); currentElement = this; } } colorBox.click(clickHandler); // foucs and select rowsBox[0].focus(); rowsBox[0].select(); var table; if (isInsert) { return; } //get selected table node table = self.plugin.getSelectedTable(); if (table) { rowsBox.val(table[0].rows.length); colsBox.val(table[0].rows.length > 0 ? table[0].rows[0].cells.length : 0); rowsBox.attr('disabled', true); colsBox.attr('disabled', true); var match, tableWidth = table[0].style.width || table[0].width, tableHeight = table[0].style.height || table[0].height; if (tableWidth !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableWidth))) { widthBox.val(match[1]); widthTypeBox.val(match[2]); } else { widthBox.val(''); } if (tableHeight !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableHeight))) { heightBox.val(match[1]); heightTypeBox.val(match[2]); } paddingBox.val(table[0].cellPadding || ''); spacingBox.val(table[0].cellSpacing || ''); alignBox.val(table[0].align || ''); borderBox.val(table[0].border === undefined ? '' : table[0].border); setColor(K(colorBox[0]), K.toHex(table.attr('borderColor') || '')); setColor(K(colorBox[1]), K.toHex(table[0].style.backgroundColor || table[0].bgColor || '')); widthBox[0].focus(); widthBox[0].select(); } }, //modify cell cellprop : function() { var html = [ '<div style="padding:10px 20px;">', //width, height '<div class="ke-dialog-row">', '<label for="keWidth" style="width:90px;">' + lang.size + '</label>', lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> &nbsp; ', '<select name="widthType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select> &nbsp; ', lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> &nbsp; ', '<select name="heightType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select>', '</div>', //align '<div class="ke-dialog-row">', '<label for="keAlign" style="width:90px;">' + lang.align + '</label>', lang.textAlign + ' <select id="keAlign" name="textAlign">', '<option value="">' + lang.alignDefault + '</option>', '<option value="left">' + lang.alignLeft + '</option>', '<option value="center">' + lang.alignCenter + '</option>', '<option value="right">' + lang.alignRight + '</option>', '</select> ', lang.verticalAlign + ' <select name="verticalAlign">', '<option value="">' + lang.alignDefault + '</option>', '<option value="top">' + lang.alignTop + '</option>', '<option value="middle">' + lang.alignMiddle + '</option>', '<option value="bottom">' + lang.alignBottom + '</option>', '<option value="baseline">' + lang.alignBaseline + '</option>', '</select>', '</div>', //border '<div class="ke-dialog-row">', '<label for="keBorder" style="width:90px;">' + lang.border + '</label>', lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> &nbsp; ', lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>', '</div>', //background color '<div class="ke-dialog-row">', '<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>', '<span class="ke-inline-block ke-input-color"></span>', '</div>', '</div>' ].join(''); var picker, currentElement; function removePicker() { if (picker) { picker.remove(); picker = null; currentElement = null; } } var dialog = self.createDialog({ name : name, width : 500, height : 220, title : self.lang('tablecell'), body : html, beforeDrag : removePicker, beforeRemove : function() { removePicker(); colorBox.unbind(); }, yesBtn : { name : self.lang('yes'), click : function(e) { var width = widthBox.val(), height = heightBox.val(), widthType = widthTypeBox.val(), heightType = heightTypeBox.val(), padding = paddingBox.val(), spacing = spacingBox.val(), textAlign = textAlignBox.val(), verticalAlign = verticalAlignBox.val(), border = borderBox.val(), borderColor = K(colorBox[0]).html() || '', bgColor = K(colorBox[1]).html() || ''; if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } if (!/^\d*$/.test(border)) { alert(self.lang('invalidBorder')); borderBox[0].focus(); return; } cell.css({ width : width !== '' ? (width + widthType) : '', height : height !== '' ? (height + heightType) : '', 'background-color' : bgColor, 'text-align' : textAlign, 'vertical-align' : verticalAlign, 'border-width' : border, 'border-style' : border !== '' ? 'solid' : '', 'border-color' : borderColor }); self.hideDialog().focus(); self.addBookmark(); } } }), div = dialog.div, widthBox = K('[name="width"]', div).val(100), heightBox = K('[name="height"]', div), widthTypeBox = K('[name="widthType"]', div), heightTypeBox = K('[name="heightType"]', div), paddingBox = K('[name="padding"]', div).val(2), spacingBox = K('[name="spacing"]', div).val(0), textAlignBox = K('[name="textAlign"]', div), verticalAlignBox = K('[name="verticalAlign"]', div), borderBox = K('[name="border"]', div).val(1), colorBox = K('.ke-input-color', div); function setColor(box, color) { color = color.toUpperCase(); box.css('background-color', color); box.css('color', color === '#000000' ? '#FFFFFF' : '#000000'); box.html(color); } setColor(K(colorBox[0]), '#000000'); setColor(K(colorBox[1]), ''); function clickHandler(e) { removePicker(); if (!picker || this !== currentElement) { var box = K(this), pos = box.pos(); picker = K.colorpicker({ x : pos.x, y : pos.y + box.height(), z : 811214, selectedColor : K(this).html(), colors : self.colorTable, noColor : self.lang('noColor'), shadowMode : self.shadowMode, click : function(color) { setColor(box, color); removePicker(); } }); currentElement = this; } } colorBox.click(clickHandler); // foucs and select widthBox[0].focus(); widthBox[0].select(); // get selected cell var cell = self.plugin.getSelectedCell(); var match, cellWidth = cell[0].style.width || cell[0].width || '', cellHeight = cell[0].style.height || cell[0].height || ''; if ((match = /^(\d+)((?:px|%)*)$/.exec(cellWidth))) { widthBox.val(match[1]); widthTypeBox.val(match[2]); } else { widthBox.val(''); } if ((match = /^(\d+)((?:px|%)*)$/.exec(cellHeight))) { heightBox.val(match[1]); heightTypeBox.val(match[2]); } textAlignBox.val(cell[0].style.textAlign || ''); verticalAlignBox.val(cell[0].style.verticalAlign || ''); var border = cell[0].style.borderWidth || ''; if (border) { border = parseInt(border); } borderBox.val(border); setColor(K(colorBox[0]), K.toHex(cell[0].style.borderColor || '')); setColor(K(colorBox[1]), K.toHex(cell[0].style.backgroundColor || '')); widthBox[0].focus(); widthBox[0].select(); }, insert : function() { this.prop(true); }, 'delete' : function() { var table = self.plugin.getSelectedTable(); self.cmd.range.setStartBefore(table[0]).collapse(true); self.cmd.select(); table.remove(); self.addBookmark(); }, colinsert : function(offset) { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], index = cell.cellIndex + offset; for (var i = 0, len = table.rows.length; i < len; i++) { var newRow = table.rows[i], newCell = newRow.insertCell(index); newCell.innerHTML = K.IE ? '' : '<br />'; // 调整下一行的单元格index index = _getCellIndex(table, newRow, newCell); } self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, colinsertleft : function() { this.colinsert(0); }, colinsertright : function() { this.colinsert(1); }, rowinsert : function(offset) { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], newRow; if (offset === 1) { newRow = table.insertRow(row.rowIndex + (cell.rowSpan - 1) + offset); } else { newRow = table.insertRow(row.rowIndex); } for (var i = 0, len = row.cells.length; i < len; i++) { var newCell = newRow.insertCell(i); // copy colspan if (offset === 1 && row.cells[i].colSpan > 1) { newCell.colSpan = row.cells[i].colSpan; } newCell.innerHTML = K.IE ? '' : '<br />'; } self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, rowinsertabove : function() { this.rowinsert(0); }, rowinsertbelow : function() { this.rowinsert(1); }, rowmerge : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex, // 当前行的index nextRowIndex = rowIndex + cell.rowSpan, // 下一行的index nextRow = table.rows[nextRowIndex]; // 下一行 // 最后一行不能合并 if (table.rows.length <= nextRowIndex) { return; } var cellIndex = _getCellIndex(table, row, cell); // 下一行单元格的index if (nextRow.cells.length <= cellIndex) { return; } var nextCell = nextRow.cells[cellIndex]; // 下一行单元格 // 上下行的colspan不一致时不能合并 if (cell.colSpan !== nextCell.colSpan) { return; } cell.rowSpan += nextCell.rowSpan; nextRow.deleteCell(cellIndex); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, colmerge : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex, // 当前行的index cellIndex = cell.cellIndex, nextCellIndex = cellIndex + 1; // 最后一列不能合并 if (row.cells.length <= nextCellIndex) { return; } var nextCell = row.cells[nextCellIndex]; // 左右列的rowspan不一致时不能合并 if (cell.rowSpan !== nextCell.rowSpan) { return; } cell.colSpan += nextCell.colSpan; row.deleteCell(nextCellIndex); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, rowsplit : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex; // 不是可分割单元格 if (cell.rowSpan === 1) { return; } var cellIndex = _getCellIndex(table, row, cell); for (var i = 1, len = cell.rowSpan; i < len; i++) { var newRow = table.rows[rowIndex + i], newCell = newRow.insertCell(cellIndex); if (cell.colSpan > 1) { newCell.colSpan = cell.colSpan; } newCell.innerHTML = K.IE ? '' : '<br />'; // 调整下一行的单元格index cellIndex = _getCellIndex(table, newRow, newCell); } K(cell).removeAttr('rowSpan'); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, colsplit : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], cellIndex = cell.cellIndex; // 不是可分割单元格 if (cell.colSpan === 1) { return; } for (var i = 1, len = cell.colSpan; i < len; i++) { var newCell = row.insertCell(cellIndex + i); if (cell.rowSpan > 1) { newCell.rowSpan = cell.rowSpan; } newCell.innerHTML = K.IE ? '' : '<br />'; } K(cell).removeAttr('colSpan'); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, coldelete : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], index = cell.cellIndex; for (var i = 0, len = table.rows.length; i < len; i++) { var newRow = table.rows[i], newCell = newRow.cells[index]; if (newCell.colSpan > 1) { newCell.colSpan -= 1; if (newCell.colSpan === 1) { K(newCell).removeAttr('colSpan'); } } else { newRow.deleteCell(index); } // 跳过不需要删除的行 if (newCell.rowSpan > 1) { i += newCell.rowSpan - 1; } } if (row.cells.length === 0) { self.cmd.range.setStartBefore(table).collapse(true); self.cmd.select(); K(table).remove(); } else { self.cmd.selection(true); } self.addBookmark(); }, rowdelete : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex; // 从下到上删除 for (var i = cell.rowSpan - 1; i >= 0; i--) { table.deleteRow(rowIndex + i); } if (table.rows.length === 0) { self.cmd.range.setStartBefore(table).collapse(true); self.cmd.select(); K(table).remove(); } else { self.cmd.selection(true); } self.addBookmark(); } }; self.clickToolbar(name, self.plugin.table.prop); });
zzblog
web/js/kindeditor/plugins/table/table.js
JavaScript
asf20
24,272
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php * Arabic Translation By daif alotaibi (http://daif.net/) *******************************************************************************/ KindEditor.lang({ source : 'عرض المصدر', preview : 'معاينة الصفحة', undo : 'تراجع(Ctrl+Z)', redo : 'إعادة التراجع(Ctrl+Y)', cut : 'قص(Ctrl+X)', copy : 'نسخ(Ctrl+C)', paste : 'لصق(Ctrl+V)', plainpaste : 'لصق كنص عادي', wordpaste : 'لصق من مايكروسفت ورد', selectall : 'تحديد الكل', justifyleft : 'محاذاه لليسار', justifycenter : 'محاذاه للوسط', justifyright : 'محاذاه لليمين', justifyfull : 'محاذاه تلقائية', insertorderedlist : 'قائمة مرقمه', insertunorderedlist : 'قائمة نقطية', indent : 'إزاحه النص', outdent : 'إلغاء الازاحة', subscript : 'أسفل النص', superscript : 'أعلى النص', formatblock : 'Paragraph format', fontname : 'نوع الخط', fontsize : 'حجم الخط', forecolor : 'لون النص', hilitecolor : 'لون خلفية النص', bold : 'عريض(Ctrl+B)', italic : 'مائل(Ctrl+I)', underline : 'خط تحت النص(Ctrl+U)', strikethrough : 'خط على النص', removeformat : 'إزالة التنسيق', image : 'إدراج صورة', flash : 'إدراج فلاش', media : 'إدراج وسائط متعددة', table : 'إدراج جدول', tablecell : 'خلية', hr : 'إدراج خط أفقي', emoticons : 'إدراج وجه ضاحك', link : 'رابط', unlink : 'إزالة الرابط', fullscreen : 'محرر ملئ الشاشة(Esc)', about : 'حول', print : 'طباعة', filemanager : 'مدير الملفات', code : 'إدراج نص برمجي', map : 'خرائط قووقل', lineheight : 'إرتفاع السطر', clearhtml : 'مسح كود HTML', pagebreak : 'إدراج فاصل صفحات', quickformat : 'تنسيق سريع', insertfile : 'إدراج ملف', template : 'إدراج قالب', anchor : 'رابط', yes : 'موافق', no : 'إلغاء', close : 'إغلاق', editImage : 'خصائص الصورة', deleteImage : 'حذفالصورة', editFlash : 'خصائص الفلاش', deleteFlash : 'حذف الفلاش', editMedia : 'خصائص الوسائط', deleteMedia : 'حذف الوسائط', editLink : 'خصائص الرابط', deleteLink : 'إزالة الرابط', tableprop : 'خصائص الجدول', tablecellprop : 'خصائص الخلية', tableinsert : 'إدراج جدول', tabledelete : 'حذف جدول', tablecolinsertleft : 'إدراج عمود لليسار', tablecolinsertright : 'إدراج عمود لليسار', tablerowinsertabove : 'إدراج صف للأعلى', tablerowinsertbelow : 'إدراج صف للأسفل', tablerowmerge : 'دمج للأسفل', tablecolmerge : 'دمج لليمين', tablerowsplit : 'تقسم الصف', tablecolsplit : 'تقسيم العمود', tablecoldelete : 'حذف العمود', tablerowdelete : 'حذف الصف', noColor : 'إفتراضي', invalidImg : "الرجاء إدخال رابط صحيح.\nالملفات المسموح بها: jpg,gif,bmp,png", invalidMedia : "الرجاء إدخال رابط صحيح.\nالملفات المسموح بها: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb", invalidWidth : "العرض يجب أن يكون رقم.", invalidHeight : "الإرتفاع يجب أن يكون رقم.", invalidBorder : "عرض الحد يجب أن يكون رقم.", invalidUrl : "الرجاء إدخال رابط حيح.", invalidRows : 'صفوف غير صحيح.', invalidCols : 'أعمدة غير صحيحة.', invalidPadding : 'The padding must be number.', invalidSpacing : 'The spacing must be number.', invalidJson : 'Invalid JSON string.', uploadSuccess : 'تم رفع الملف بنجاح.', cutError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+X).', copyError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+C).', pasteError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+V).', ajaxLoading : 'Loading ...', uploadLoading : 'Uploading ...', uploadError : 'Upload Error', 'plainpaste.comment' : 'إستخدم إختصار لوحة المفاتيح (Ctrl+V) للصق داخل النافذة.', 'wordpaste.comment' : 'إستخدم إختصار لوحة المفاتيح (Ctrl+V) للصق داخل النافذة.', 'link.url' : 'الرابط', 'link.linkType' : 'الهدف', 'link.newWindow' : 'نافذة جديدة', 'link.selfWindow' : 'نفس النافذة', 'flash.url' : 'الرابط', 'flash.width' : 'العرض', 'flash.height' : 'الإرتفاع', 'flash.upload' : 'رفع', 'flash.viewServer' : 'أستعراض', 'media.url' : 'الرابط', 'media.width' : 'العرض', 'media.height' : 'الإرتفاع', 'media.autostart' : 'تشغيل تلقائي', 'media.upload' : 'رفع', 'media.viewServer' : 'أستعراض', 'image.remoteImage' : 'إدراج الرابط', 'image.localImage' : 'رفع', 'image.remoteUrl' : 'الرابط', 'image.localUrl' : 'الملف', 'image.size' : 'الحجم', 'image.width' : 'العرض', 'image.height' : 'الإرتفاع', 'image.resetSize' : 'إستعادة الأبعاد', 'image.align' : 'محاذاة', 'image.defaultAlign' : 'الإفتراضي', 'image.leftAlign' : 'اليسار', 'image.rightAlign' : 'اليمين', 'image.imgTitle' : 'العنوان', 'image.viewServer' : 'أستعراض', 'filemanager.emptyFolder' : 'فارغ', 'filemanager.moveup' : 'المجلد الأب', 'filemanager.viewType' : 'العرض: ', 'filemanager.viewImage' : 'مصغرات', 'filemanager.listImage' : 'قائمة', 'filemanager.orderType' : 'الترتيب: ', 'filemanager.fileName' : 'بالإسم', 'filemanager.fileSize' : 'بالحجم', 'filemanager.fileType' : 'بالنوع', 'insertfile.url' : 'الرابط', 'insertfile.title' : 'العنوان', 'insertfile.upload' : 'رفع', 'insertfile.viewServer' : 'أستعراض', 'table.cells' : 'خلايا', 'table.rows' : 'صفوف', 'table.cols' : 'أعمدة', 'table.size' : 'الأبعاد', 'table.width' : 'العرض', 'table.height' : 'الإرتفاع', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : 'الخارج', 'table.padding' : 'الداخل', 'table.spacing' : 'الفراغات', 'table.align' : 'محاذاه', 'table.textAlign' : 'افقى', 'table.verticalAlign' : 'رأسي', 'table.alignDefault' : 'إفتراضي', 'table.alignLeft' : 'يسار', 'table.alignCenter' : 'وسط', 'table.alignRight' : 'يمين', 'table.alignTop' : 'أعلى', 'table.alignMiddle' : 'منتصف', 'table.alignBottom' : 'أسفل', 'table.alignBaseline' : 'Baseline', 'table.border' : 'الحدود', 'table.borderWidth' : 'العرض', 'table.borderColor' : 'اللون', 'table.backgroundColor' : 'الخلفية', 'map.address' : 'العنوان: ', 'map.search' : 'بحث', 'anchor.name' : 'إسم الرابط', 'formatblock.formatBlock' : { h1 : 'عنوان 1', h2 : 'عنوان 2', h3 : 'عنوان 3', h4 : 'عنوان 4', p : 'عادي' }, 'fontname.fontName' : { 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Comic Sans MS' : 'Comic Sans MS', 'Courier New' : 'Courier New', 'Garamond' : 'Garamond', 'Georgia' : 'Georgia', 'Tahoma' : 'Tahoma', 'Times New Roman' : 'Times New Roman', 'Trebuchet MS' : 'Trebuchet MS', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : 'إرتفاع السطر 1'}, {'1.5' : 'إرتفاع السطر 1.5'}, {'2' : 'إرتفاع السطر 2'}, {'2.5' : 'إرتفاع السطر 2.5'}, {'3' : 'إرتفاع السطر 3'} ], 'template.selectTemplate' : 'قالب', 'template.replaceContent' : 'إستبدال المحتوى الحالي', 'template.fileList' : { '1.html' : 'صورة ونص', '2.html' : 'جدول', '3.html' : 'قائمة' } }, 'ar');
zzblog
web/js/kindeditor/lang/ar.js
JavaScript
asf20
8,658
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.lang({ source : 'HTML代码', preview : '预览', undo : '后退(Ctrl+Z)', redo : '前进(Ctrl+Y)', cut : '剪切(Ctrl+X)', copy : '复制(Ctrl+C)', paste : '粘贴(Ctrl+V)', plainpaste : '粘贴为无格式文本', wordpaste : '从Word粘贴', selectall : '全选(Ctrl+A)', justifyleft : '左对齐', justifycenter : '居中', justifyright : '右对齐', justifyfull : '两端对齐', insertorderedlist : '编号', insertunorderedlist : '项目符号', indent : '增加缩进', outdent : '减少缩进', subscript : '下标', superscript : '上标', formatblock : '段落', fontname : '字体', fontsize : '文字大小', forecolor : '文字颜色', hilitecolor : '文字背景', bold : '粗体(Ctrl+B)', italic : '斜体(Ctrl+I)', underline : '下划线(Ctrl+U)', strikethrough : '删除线', removeformat : '删除格式', image : '图片', flash : 'Flash', media : '视音频', table : '表格', tablecell : '单元格', hr : '插入横线', emoticons : '插入表情', link : '超级链接', unlink : '取消超级链接', fullscreen : '全屏显示(Esc)', about : '关于', print : '打印(Ctrl+P)', filemanager : '浏览服务器', code : '插入程序代码', map : 'Google地图', lineheight : '行距', clearhtml : '清理HTML代码', pagebreak : '插入分页符', quickformat : '一键排版', insertfile : '插入文件', template : '插入模板', anchor : '锚点', yes : '确定', no : '取消', close : '关闭', editImage : '图片属性', deleteImage : '删除图片', editFlash : 'Flash属性', deleteFlash : '删除Flash', editMedia : '视音频属性', deleteMedia : '删除视音频', editLink : '超级链接属性', deleteLink : '取消超级链接', editAnchor : '锚点属性', deleteAnchor : '删除锚点', tableprop : '表格属性', tablecellprop : '单元格属性', tableinsert : '插入表格', tabledelete : '删除表格', tablecolinsertleft : '左侧插入列', tablecolinsertright : '右侧插入列', tablerowinsertabove : '上方插入行', tablerowinsertbelow : '下方插入行', tablerowmerge : '向下合并单元格', tablecolmerge : '向右合并单元格', tablerowsplit : '拆分行', tablecolsplit : '拆分列', tablecoldelete : '删除列', tablerowdelete : '删除行', noColor : '无颜色', invalidImg : "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。", invalidMedia : "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。", invalidWidth : "宽度必须为数字。", invalidHeight : "高度必须为数字。", invalidBorder : "边框必须为数字。", invalidUrl : "请输入有效的URL地址。", invalidRows : '行数为必选项,只允许输入大于0的数字。', invalidCols : '列数为必选项,只允许输入大于0的数字。', invalidPadding : '边距必须为数字。', invalidSpacing : '间距必须为数字。', invalidJson : '服务器发生故障。', uploadSuccess : '上传成功。', cutError : '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。', copyError : '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。', pasteError : '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。', ajaxLoading : '加载中,请稍候 ...', uploadLoading : '上传中,请稍候 ...', uploadError : '上传错误', 'plainpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。', 'wordpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。', 'link.url' : 'URL', 'link.linkType' : '打开类型', 'link.newWindow' : '新窗口', 'link.selfWindow' : '当前窗口', 'flash.url' : 'URL', 'flash.width' : '宽度', 'flash.height' : '高度', 'flash.upload' : '上传', 'flash.viewServer' : '浏览', 'media.url' : 'URL', 'media.width' : '宽度', 'media.height' : '高度', 'media.autostart' : '自动播放', 'media.upload' : '上传', 'media.viewServer' : '浏览', 'image.remoteImage' : '远程图片', 'image.localImage' : '本地上传', 'image.remoteUrl' : '图片地址', 'image.localUrl' : '图片地址', 'image.size' : '图片大小', 'image.width' : '宽', 'image.height' : '高', 'image.resetSize' : '重置大小', 'image.align' : '对齐方式', 'image.defaultAlign' : '默认方式', 'image.leftAlign' : '左对齐', 'image.rightAlign' : '右对齐', 'image.imgTitle' : '图片说明', 'image.viewServer' : '浏览...', 'filemanager.emptyFolder' : '空文件夹', 'filemanager.moveup' : '移到上一级文件夹', 'filemanager.viewType' : '显示方式:', 'filemanager.viewImage' : '缩略图', 'filemanager.listImage' : '详细信息', 'filemanager.orderType' : '排序方式:', 'filemanager.fileName' : '名称', 'filemanager.fileSize' : '大小', 'filemanager.fileType' : '类型', 'insertfile.url' : 'URL', 'insertfile.title' : '文件说明', 'insertfile.upload' : '上传', 'insertfile.viewServer' : '浏览', 'table.cells' : '单元格数', 'table.rows' : '行数', 'table.cols' : '列数', 'table.size' : '大小', 'table.width' : '宽度', 'table.height' : '高度', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : '边距间距', 'table.padding' : '边距', 'table.spacing' : '间距', 'table.align' : '对齐方式', 'table.textAlign' : '水平对齐', 'table.verticalAlign' : '垂直对齐', 'table.alignDefault' : '默认', 'table.alignLeft' : '左对齐', 'table.alignCenter' : '居中', 'table.alignRight' : '右对齐', 'table.alignTop' : '顶部', 'table.alignMiddle' : '中部', 'table.alignBottom' : '底部', 'table.alignBaseline' : '基线', 'table.border' : '边框', 'table.borderWidth' : '边框', 'table.borderColor' : '颜色', 'table.backgroundColor' : '背景颜色', 'map.address' : '地址: ', 'map.search' : '搜索', 'anchor.name' : '锚点名称', 'formatblock.formatBlock' : { h1 : '标题 1', h2 : '标题 2', h3 : '标题 3', h4 : '标题 4', p : '正 文' }, 'fontname.fontName' : { 'SimSun' : '宋体', 'NSimSun' : '新宋体', 'FangSong_GB2312' : '仿宋_GB2312', 'KaiTi_GB2312' : '楷体_GB2312', 'SimHei' : '黑体', 'Microsoft YaHei' : '微软雅黑', 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Times New Roman' : 'Times New Roman', 'Courier New' : 'Courier New', 'Tahoma' : 'Tahoma', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : '单倍行距'}, {'1.5' : '1.5倍行距'}, {'2' : '2倍行距'}, {'2.5' : '2.5倍行距'}, {'3' : '3倍行距'} ], 'template.selectTemplate' : '可选模板', 'template.replaceContent' : '替换当前内容', 'template.fileList' : { '1.html' : '图片和文字', '2.html' : '表格', '3.html' : '项目编号' } }, 'zh_CN');
zzblog
web/js/kindeditor/lang/zh_CN.js
JavaScript
asf20
7,502
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.lang({ source : '原始碼', preview : '預覽', undo : '復原(Ctrl+Z)', redo : '重複(Ctrl+Y)', cut : '剪下(Ctrl+X)', copy : '複製(Ctrl+C)', paste : '貼上(Ctrl+V)', plainpaste : '貼為純文字格式', wordpaste : '自Word貼上', selectall : '全選(Ctrl+A)', justifyleft : '靠左對齊', justifycenter : '置中', justifyright : '靠右對齊', justifyfull : '左右對齊', insertorderedlist : '編號清單', insertunorderedlist : '項目清單', indent : '增加縮排', outdent : '減少縮排', subscript : '下標', superscript : '上標', formatblock : '標題', fontname : '字體', fontsize : '文字大小', forecolor : '文字顏色', hilitecolor : '背景顏色', bold : '粗體(Ctrl+B)', italic : '斜體(Ctrl+I)', underline : '底線(Ctrl+U)', strikethrough : '刪除線', removeformat : '清除格式', image : '影像', flash : 'Flash', media : '多媒體', table : '表格', hr : '插入水平線', emoticons : '插入表情', link : '超連結', unlink : '移除超連結', fullscreen : '最大化', about : '關於', print : '列印(Ctrl+P)', fileManager : '瀏覽伺服器', code : '插入程式代碼', map : 'Google地圖', lineheight : '行距', clearhtml : '清理HTML代碼', pagebreak : '插入分頁符號', quickformat : '快速排版', insertfile : '插入文件', template : '插入樣板', anchor : '錨點', yes : '確定', no : '取消', close : '關閉', editImage : '影像屬性', deleteImage : '刪除影像', editFlash : 'Flash屬性', deleteFlash : '删除Flash', editMedia : '多媒體屬性', deleteMedia : '删除多媒體', editLink : '超連結屬性', deleteLink : '移除超連結', tableprop : '表格屬性', tablecellprop : '儲存格屬性', tableinsert : '插入表格', tabledelete : '刪除表格', tablecolinsertleft : '向左插入列', tablecolinsertright : '向右插入列', tablerowinsertabove : '向上插入欄', tablerowinsertbelow : '下方插入欄', tablerowmerge : '向下合併單元格', tablecolmerge : '向右合併單元格', tablerowsplit : '分割欄', tablecolsplit : '分割列', tablecoldelete : '删除列', tablerowdelete : '删除欄', noColor : '自動', invalidImg : "請輸入有效的URL。\n只允許jpg,gif,bmp,png格式。", invalidMedia : "請輸入有效的URL。\n只允許swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。", invalidWidth : "寬度必須是數字。", invalidHeight : "高度必須是數字。", invalidBorder : "邊框必須是數字。", invalidUrl : "請輸入有效的URL。", invalidRows : '欄數是必須輸入項目,只允許輸入大於0的數字。', invalidCols : '列數是必須輸入項目,只允許輸入大於0的數字。', invalidPadding : '內距必須是數字。', invalidSpacing : '間距必須是數字。', invalidBorder : '边框必须为数字。', pleaseInput : "請輸入內容。", invalidJson : '伺服器發生故障。', cutError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+X)完成。', copyError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+C)完成。', pasteError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+V)完成。', ajaxLoading : '加載中,請稍候 ...', uploadLoading : '上傳中,請稍候 ...', uploadError : '上傳錯誤', 'plainpaste.comment' : '請使用快捷鍵(Ctrl+V)把內容貼到下方區域裡。', 'wordpaste.comment' : '請使用快捷鍵(Ctrl+V)把內容貼到下方區域裡。', 'link.url' : 'URL', 'link.linkType' : '打開類型', 'link.newWindow' : '新窗口', 'link.selfWindow' : '本頁窗口', 'flash.url' : 'URL', 'flash.width' : '寬度', 'flash.height' : '高度', 'flash.upload' : '上傳', 'flash.viewServer' : '瀏覽', 'media.url' : 'URL', 'media.width' : '寬度', 'media.height' : '高度', 'media.autostart' : '自動播放', 'media.upload' : '上傳', 'media.viewServer' : '瀏覽', 'image.remoteImage' : '影像URL', 'image.localImage' : '上傳影像', 'image.remoteUrl' : '影像URL', 'image.localUrl' : '影像URL', 'image.size' : '影像大小', 'image.width' : '寬度', 'image.height' : '高度', 'image.resetSize' : '原始大小', 'image.align' : '對齊方式', 'image.defaultAlign' : '未設定', 'image.leftAlign' : '向左對齊', 'image.rightAlign' : '向右對齊', 'image.imgTitle' : '影像說明', 'image.viewServer' : '瀏覽...', 'filemanager.emptyFolder' : '空文件夾', 'filemanager.moveup' : '至上一級文件夾', 'filemanager.viewType' : '顯示方式:', 'filemanager.viewImage' : '縮略圖', 'filemanager.listImage' : '詳細信息', 'filemanager.orderType' : '排序方式:', 'filemanager.fileName' : '名稱', 'filemanager.fileSize' : '大小', 'filemanager.fileType' : '類型', 'insertfile.url' : 'URL', 'insertfile.title' : '文件說明', 'insertfile.upload' : '上傳', 'insertfile.viewServer' : '瀏覽', 'table.cells' : '儲存格數', 'table.rows' : '欄數', 'table.cols' : '列數', 'table.size' : '表格大小', 'table.width' : '寬度', 'table.height' : '高度', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : '內距間距', 'table.padding' : '內距', 'table.spacing' : '間距', 'table.align' : '對齊方式', 'table.textAlign' : '水平對齊', 'table.verticalAlign' : '垂直對齊', 'table.alignDefault' : '未設定', 'table.alignLeft' : '向左對齊', 'table.alignCenter' : '置中', 'table.alignRight' : '向右對齊', 'table.alignTop' : '靠上', 'table.alignMiddle' : '置中', 'table.alignBottom' : '靠下', 'table.alignBaseline' : '基線', 'table.border' : '表格邊框', 'table.borderWidth' : '邊框', 'table.borderColor' : '顏色', 'table.backgroundColor' : '背景顏色', 'map.address' : '住所: ', 'map.search' : '尋找', 'anchor.name' : '錨點名稱', 'formatblock.formatBlock' : { h1 : '標題 1', h2 : '標題 2', h3 : '標題 3', h4 : '標題 4', p : '一般' }, 'fontname.fontName' : { 'MingLiU' : '細明體', 'PMingLiU' : '新細明體', 'DFKai-SB' : '標楷體', 'SimSun' : '宋體', 'NSimSun' : '新宋體', 'FangSong' : '仿宋體', 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Times New Roman' : 'Times New Roman', 'Courier New' : 'Courier New', 'Tahoma' : 'Tahoma', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : '单倍行距'}, {'1.5' : '1.5倍行距'}, {'2' : '2倍行距'}, {'2.5' : '2.5倍行距'}, {'3' : '3倍行距'} ], 'template.selectTemplate' : '可選樣板', 'template.replaceContent' : '取代當前內容', 'template.fileList' : { '1.html' : '影像和文字', '2.html' : '表格', '3.html' : '项目清單' } }, 'zh_TW');
zzblog
web/js/kindeditor/lang/zh_TW.js
JavaScript
asf20
7,420
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.lang({ source : 'Source', preview : 'Preview', undo : 'Undo(Ctrl+Z)', redo : 'Redo(Ctrl+Y)', cut : 'Cut(Ctrl+X)', copy : 'Copy(Ctrl+C)', paste : 'Paste(Ctrl+V)', plainpaste : 'Paste as plain text', wordpaste : 'Paste from Word', selectall : 'Select all', justifyleft : 'Align left', justifycenter : 'Align center', justifyright : 'Align right', justifyfull : 'Align full', insertorderedlist : 'Ordered list', insertunorderedlist : 'Unordered list', indent : 'Increase indent', outdent : 'Decrease indent', subscript : 'Subscript', superscript : 'Superscript', formatblock : 'Paragraph format', fontname : 'Font family', fontsize : 'Font size', forecolor : 'Text color', hilitecolor : 'Highlight color', bold : 'Bold(Ctrl+B)', italic : 'Italic(Ctrl+I)', underline : 'Underline(Ctrl+U)', strikethrough : 'Strikethrough', removeformat : 'Remove format', image : 'Image', flash : 'Flash', media : 'Embeded media', table : 'Table', tablecell : 'Cell', hr : 'Insert horizontal line', emoticons : 'Insert emoticon', link : 'Link', unlink : 'Unlink', fullscreen : 'Toggle fullscreen mode(Esc)', about : 'About', print : 'Print', filemanager : 'File Manager', code : 'Insert code', map : 'Google Maps', lineheight : 'Line height', clearhtml : 'Clear HTML code', pagebreak : 'Insert Page Break', quickformat : 'Quick Format', insertfile : 'Insert file', template : 'Insert Template', anchor : 'Anchor', yes : 'OK', no : 'Cancel', close : 'Close', editImage : 'Image properties', deleteImage : 'Delete image', editFlash : 'Flash properties', deleteFlash : 'Delete flash', editMedia : 'Media properties', deleteMedia : 'Delete media', editLink : 'Link properties', deleteLink : 'Unlink', tableprop : 'Table properties', tablecellprop : 'Cell properties', tableinsert : 'Insert table', tabledelete : 'Delete table', tablecolinsertleft : 'Insert column left', tablecolinsertright : 'Insert column right', tablerowinsertabove : 'Insert row above', tablerowinsertbelow : 'Insert row below', tablerowmerge : 'Merge down', tablecolmerge : 'Merge right', tablerowsplit : 'Split row', tablecolsplit : 'Split column', tablecoldelete : 'Delete column', tablerowdelete : 'Delete row', noColor : 'Default', invalidImg : "Please type valid URL.\nAllowed file extension: jpg,gif,bmp,png", invalidMedia : "Please type valid URL.\nAllowed file extension: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb", invalidWidth : "The width must be number.", invalidHeight : "The height must be number.", invalidBorder : "The border must be number.", invalidUrl : "Please type valid URL.", invalidRows : 'Invalid rows.', invalidCols : 'Invalid columns.', invalidPadding : 'The padding must be number.', invalidSpacing : 'The spacing must be number.', invalidJson : 'Invalid JSON string.', uploadSuccess : 'Upload success.', cutError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+X) instead.', copyError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+C) instead.', pasteError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+V) instead.', ajaxLoading : 'Loading ...', uploadLoading : 'Uploading ...', uploadError : 'Upload Error', 'plainpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.', 'wordpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.', 'link.url' : 'URL', 'link.linkType' : 'Target', 'link.newWindow' : 'New window', 'link.selfWindow' : 'Same window', 'flash.url' : 'URL', 'flash.width' : 'Width', 'flash.height' : 'Height', 'flash.upload' : 'Upload', 'flash.viewServer' : 'Browse', 'media.url' : 'URL', 'media.width' : 'Width', 'media.height' : 'Height', 'media.autostart' : 'Auto start', 'media.upload' : 'Upload', 'media.viewServer' : 'Browse', 'image.remoteImage' : 'Insert URL', 'image.localImage' : 'Upload', 'image.remoteUrl' : 'URL', 'image.localUrl' : 'File', 'image.size' : 'Size', 'image.width' : 'Width', 'image.height' : 'Height', 'image.resetSize' : 'Reset dimensions', 'image.align' : 'Align', 'image.defaultAlign' : 'Default', 'image.leftAlign' : 'Left', 'image.rightAlign' : 'Right', 'image.imgTitle' : 'Title', 'image.viewServer' : 'Browse', 'filemanager.emptyFolder' : 'Blank', 'filemanager.moveup' : 'Parent folder', 'filemanager.viewType' : 'Display: ', 'filemanager.viewImage' : 'Thumbnails', 'filemanager.listImage' : 'List', 'filemanager.orderType' : 'Sorting: ', 'filemanager.fileName' : 'By name', 'filemanager.fileSize' : 'By size', 'filemanager.fileType' : 'By type', 'insertfile.url' : 'URL', 'insertfile.title' : 'Title', 'insertfile.upload' : 'Upload', 'insertfile.viewServer' : 'Browse', 'table.cells' : 'Cells', 'table.rows' : 'Rows', 'table.cols' : 'Columns', 'table.size' : 'Dimensions', 'table.width' : 'Width', 'table.height' : 'Height', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : 'Space', 'table.padding' : 'Padding', 'table.spacing' : 'Spacing', 'table.align' : 'Align', 'table.textAlign' : 'Horizontal', 'table.verticalAlign' : 'Vertical', 'table.alignDefault' : 'Default', 'table.alignLeft' : 'Left', 'table.alignCenter' : 'Center', 'table.alignRight' : 'Right', 'table.alignTop' : 'Top', 'table.alignMiddle' : 'Middle', 'table.alignBottom' : 'Bottom', 'table.alignBaseline' : 'Baseline', 'table.border' : 'Border', 'table.borderWidth' : 'Width', 'table.borderColor' : 'Color', 'table.backgroundColor' : 'Background', 'map.address' : 'Address: ', 'map.search' : 'Search', 'anchor.name' : 'Anchor name', 'formatblock.formatBlock' : { h1 : 'Heading 1', h2 : 'Heading 2', h3 : 'Heading 3', h4 : 'Heading 4', p : 'Normal' }, 'fontname.fontName' : { 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Comic Sans MS' : 'Comic Sans MS', 'Courier New' : 'Courier New', 'Garamond' : 'Garamond', 'Georgia' : 'Georgia', 'Tahoma' : 'Tahoma', 'Times New Roman' : 'Times New Roman', 'Trebuchet MS' : 'Trebuchet MS', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : 'Line height 1'}, {'1.5' : 'Line height 1.5'}, {'2' : 'Line height 2'}, {'2.5' : 'Line height 2.5'}, {'3' : 'Line height 3'} ], 'template.selectTemplate' : 'Template', 'template.replaceContent' : 'Replace current content', 'template.fileList' : { '1.html' : 'Image and Text', '2.html' : 'Table', '3.html' : 'List' } }, 'en');
zzblog
web/js/kindeditor/lang/en.js
JavaScript
asf20
7,072
/* common */ .ke-inline-block { display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .ke-clearfix { zoom: 1; } .ke-clearfix:after { content: "."; display: block; clear: both; font-size: 0; height: 0; line-height: 0; visibility: hidden; } .ke-shadow { box-shadow: 1px 1px 3px #A0A0A0; -moz-box-shadow: 1px 1px 3px #A0A0A0; -webkit-box-shadow: 1px 1px 3px #A0A0A0; filter: progid:DXImageTransform.Microsoft.Shadow(color='#A0A0A0', Direction=135, Strength=3); background-color: #F0F0EE; } .ke-menu a, .ke-menu a:hover, .ke-dialog a, .ke-dialog a:hover { color: #337FE5; text-decoration: none; } /* icons */ .ke-icon-source { background-position: 0px 0px; width: 16px; height: 16px; } .ke-icon-preview { background-position: 0px -16px; width: 16px; height: 16px; } .ke-icon-print { background-position: 0px -32px; width: 16px; height: 16px; } .ke-icon-undo { background-position: 0px -48px; width: 16px; height: 16px; } .ke-icon-redo { background-position: 0px -64px; width: 16px; height: 16px; } .ke-icon-cut { background-position: 0px -80px; width: 16px; height: 16px; } .ke-icon-copy { background-position: 0px -96px; width: 16px; height: 16px; } .ke-icon-paste { background-position: 0px -112px; width: 16px; height: 16px; } .ke-icon-selectall { background-position: 0px -128px; width: 16px; height: 16px; } .ke-icon-justifyleft { background-position: 0px -144px; width: 16px; height: 16px; } .ke-icon-justifycenter { background-position: 0px -160px; width: 16px; height: 16px; } .ke-icon-justifyright { background-position: 0px -176px; width: 16px; height: 16px; } .ke-icon-justifyfull { background-position: 0px -192px; width: 16px; height: 16px; } .ke-icon-insertorderedlist { background-position: 0px -208px; width: 16px; height: 16px; } .ke-icon-insertunorderedlist { background-position: 0px -224px; width: 16px; height: 16px; } .ke-icon-indent { background-position: 0px -240px; width: 16px; height: 16px; } .ke-icon-outdent { background-position: 0px -256px; width: 16px; height: 16px; } .ke-icon-subscript { background-position: 0px -272px; width: 16px; height: 16px; } .ke-icon-superscript { background-position: 0px -288px; width: 16px; height: 16px; } .ke-icon-date { background-position: 0px -304px; width: 25px; height: 16px; } .ke-icon-time { background-position: 0px -320px; width: 25px; height: 16px; } .ke-icon-formatblock { background-position: 0px -336px; width: 25px; height: 16px; } .ke-icon-fontname { background-position: 0px -352px; width: 21px; height: 16px; } .ke-icon-fontsize { background-position: 0px -368px; width: 23px; height: 16px; } .ke-icon-forecolor { background-position: 0px -384px; width: 20px; height: 16px; } .ke-icon-hilitecolor { background-position: 0px -400px; width: 23px; height: 16px; } .ke-icon-bold { background-position: 0px -416px; width: 16px; height: 16px; } .ke-icon-italic { background-position: 0px -432px; width: 16px; height: 16px; } .ke-icon-underline { background-position: 0px -448px; width: 16px; height: 16px; } .ke-icon-strikethrough { background-position: 0px -464px; width: 16px; height: 16px; } .ke-icon-removeformat { background-position: 0px -480px; width: 16px; height: 16px; } .ke-icon-image { background-position: 0px -496px; width: 16px; height: 16px; } .ke-icon-flash { background-position: 0px -512px; width: 16px; height: 16px; } .ke-icon-media { background-position: 0px -528px; width: 16px; height: 16px; } .ke-icon-div { background-position: 0px -544px; width: 16px; height: 16px; } .ke-icon-formula { background-position: 0px -576px; width: 16px; height: 16px; } .ke-icon-hr { background-position: 0px -592px; width: 16px; height: 16px; } .ke-icon-emoticons { background-position: 0px -608px; width: 16px; height: 16px; } .ke-icon-link { background-position: 0px -624px; width: 16px; height: 16px; } .ke-icon-unlink { background-position: 0px -640px; width: 16px; height: 16px; } .ke-icon-fullscreen { background-position: 0px -656px; width: 16px; height: 16px; } .ke-icon-about { background-position: 0px -672px; width: 16px; height: 16px; } .ke-icon-plainpaste { background-position: 0px -704px; width: 16px; height: 16px; } .ke-icon-wordpaste { background-position: 0px -720px; width: 16px; height: 16px; } .ke-icon-table { background-position: 0px -784px; width: 16px; height: 16px; } .ke-icon-tablemenu { background-position: 0px -768px; width: 16px; height: 16px; } .ke-icon-tableinsert { background-position: 0px -784px; width: 16px; height: 16px; } .ke-icon-tabledelete { background-position: 0px -800px; width: 16px; height: 16px; } .ke-icon-tablecolinsertleft { background-position: 0px -816px; width: 16px; height: 16px; } .ke-icon-tablecolinsertright { background-position: 0px -832px; width: 16px; height: 16px; } .ke-icon-tablerowinsertabove { background-position: 0px -848px; width: 16px; height: 16px; } .ke-icon-tablerowinsertbelow { background-position: 0px -864px; width: 16px; height: 16px; } .ke-icon-tablecoldelete { background-position: 0px -880px; width: 16px; height: 16px; } .ke-icon-tablerowdelete { background-position: 0px -896px; width: 16px; height: 16px; } .ke-icon-tablecellprop { background-position: 0px -912px; width: 16px; height: 16px; } .ke-icon-tableprop { background-position: 0px -928px; width: 16px; height: 16px; } .ke-icon-checked { background-position: 0px -944px; width: 16px; height: 16px; } .ke-icon-code { background-position: 0px -960px; width: 16px; height: 16px; } .ke-icon-map { background-position: 0px -976px; width: 16px; height: 16px; } .ke-icon-lineheight { background-position: 0px -992px; width: 16px; height: 16px; } .ke-icon-clearhtml { background-position: 0px -1008px; width: 16px; height: 16px; } .ke-icon-pagebreak { background-position: 0px -1024px; width: 16px; height: 16px; } .ke-icon-insertfile { background-position: 0px -1040px; width: 16px; height: 16px; } .ke-icon-quickformat { background-position: 0px -1056px; width: 16px; height: 16px; } .ke-icon-template { background-position: 0px -1072px; width: 16px; height: 16px; } .ke-icon-tablecellsplit { background-position: 0px -1088px; width: 16px; height: 16px; } .ke-icon-tablerowmerge { background-position: 0px -1104px; width: 16px; height: 16px; } .ke-icon-tablerowsplit { background-position: 0px -1120px; width: 16px; height: 16px; } .ke-icon-tablecolmerge { background-position: 0px -1136px; width: 16px; height: 16px; } .ke-icon-tablecolsplit { background-position: 0px -1152px; width: 16px; height: 16px; } .ke-icon-anchor { background-position: 0px -1168px; width: 16px; height: 16px; } .ke-icon-search { background-position: 0px -1184px; width: 16px; height: 16px; } .ke-icon-new { background-position: 0px -1200px; width: 16px; height: 16px; } .ke-icon-specialchar { background-position: 0px -1216px; width: 16px; height: 16px; } /* container */ .ke-container { display: block; border: 1px solid #CCCCCC; background-color: #FFF; overflow: hidden; margin: 0; padding: 0; } /* toolbar */ .ke-toolbar { border-bottom: 1px solid #CCC; background-color: #F0F0EE; padding: 2px 5px; text-align: left; overflow: hidden; zoom: 1; } .ke-toolbar-icon { background-repeat: no-repeat; font-size: 0; line-height: 0; overflow: hidden; display: block; } .ke-toolbar-icon-url { background-image: url(default.png); } .ke-toolbar .ke-outline { border: 1px solid #F0F0EE; margin: 1px; padding: 1px 2px; font-size: 0; line-height: 0; overflow: hidden; cursor: pointer; display: block; float: left; } .ke-toolbar .ke-on { border: 1px solid #5690D2; } .ke-toolbar .ke-selected { border: 1px solid #5690D2; background-color: #E9EFF6; } .ke-toolbar .ke-disabled { cursor: default; } .ke-toolbar .ke-separator { height: 16px; margin: 2px 3px; border-left: 1px solid #A0A0A0; border-right: 1px solid #FFFFFF; border-top:0; border-bottom:0; width: 0; font-size: 0; line-height: 0; overflow: hidden; display: block; float: left; } .ke-toolbar .ke-hr { overflow: hidden; height: 1px; clear: both; } /* edit */ .ke-edit { padding: 0; } .ke-edit-iframe, .ke-edit-textarea { border: 0; margin: 0; padding: 0; overflow: auto; } .ke-edit-textarea { font: 12px/1.5 "Consolas", "Monaco", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace; color: #000; overflow: auto; resize: none; } .ke-edit-textarea:focus { outline: none; } /* statusbar */ .ke-statusbar { position: relative; background-color: #F0F0EE; border-top: 1px solid #CCCCCC; font-size: 0; line-height: 0; *height: 12px; overflow: hidden; text-align: center; cursor: s-resize; } .ke-statusbar-center-icon { background-position: -0px -754px; width: 15px; height: 11px; background-image: url(default.png); } .ke-statusbar-right-icon { position: absolute; right: 0; bottom: 0; cursor: se-resize; background-position: -5px -741px; width: 11px; height: 11px; background-image: url(default.png); } /* menu */ .ke-menu { border: 1px solid #A0A0A0; background-color: #F1F1F1; color: #222222; padding: 2px; font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; text-align: left; overflow: hidden; } .ke-menu-item { border: 1px solid #F1F1F1; background-color: #F1F1F1; color: #222222; height: 24px; overflow: hidden; cursor: pointer; } .ke-menu-item-on { border: 1px solid #5690D2; background-color: #E9EFF6; } .ke-menu-item-left { width: 27px; text-align: center; overflow: hidden; } .ke-menu-item-center { width: 0; height: 24px; border-left: 1px solid #E3E3E3; border-right: 1px solid #FFFFFF; border-top: 0; border-bottom: 0; } .ke-menu-item-center-on { border-left: 1px solid #E9EFF6; border-right: 1px solid #E9EFF6; } .ke-menu-item-right { border: 0; padding: 0 0 0 5px; line-height: 24px; text-align: left; overflow: hidden; } .ke-menu-separator { margin: 2px 0; height: 0; overflow: hidden; border-top: 1px solid #CCCCCC; border-bottom: 1px solid #FFFFFF; border-left: 0; border-right: 0; } /* colorpicker */ .ke-colorpicker { border: 1px solid #A0A0A0; background-color: #F1F1F1; color: #222222; padding: 2px; } .ke-colorpicker-table { border:0; margin:0; padding:0; border-collapse: separate; } .ke-colorpicker-cell { font-size: 0; line-height: 0; border: 1px solid #F0F0EE; cursor: pointer; margin:3px; padding:0; } .ke-colorpicker-cell-top { font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; line-height: 24px; border: 1px solid #F0F0EE; cursor: pointer; margin:0; padding:0; text-align: center; } .ke-colorpicker-cell-on { border: 1px solid #5690D2; } .ke-colorpicker-cell-selected { border: 1px solid #2446AB; } .ke-colorpicker-cell-color { width: 14px; height: 14px; margin: 3px; padding: 0; border: 0; } /* dialog */ .ke-dialog { position: absolute; margin: 0; padding: 0; } .ke-dialog-content { background-color: #F0F0EE; width: 100%; height: 100%; color: #333; border: 1px solid #A0A0A0; } .ke-dialog-shadow { position: absolute; z-index: -1; top: 0; left: 0; width: 100%; height: 100%; box-shadow: 3px 3px 7px #A0A0A0; -moz-box-shadow: 3px 3px 7px #A0A0A0; -webkit-box-shadow: 3px 3px 7px #A0A0A0; filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius='3', MakeShadow='true', ShadowOpacity='0.3'); background-color: #F0F0EE; } .ke-dialog-header { border:0; margin:0; background-color: #F0F0EE; padding: 10px; text-align: left; font: 14px/1 "sans serif",tahoma,verdana,helvetica; font-weight: bold; color: #222222; cursor: move; } .ke-dialog-icon-close { display: block; background-position: 0px -688px; width: 16px; height: 16px; position: absolute; right: 15px; top: 15px; cursor: pointer; background-image: url(default.png); overflow: hidden; right: 10px; top: 10px; } .ke-dialog-body { font: 12px/1.5 "sans serif",tahoma,verdana,helvetica; text-align: left; overflow: hidden; background-color: #F0F0EE; } .ke-dialog-body textarea { display: block; overflow: auto; padding: 0; resize: none; } .ke-dialog-body textarea:focus, .ke-dialog-body input:focus, .ke-dialog-body select:focus { outline: none; } .ke-dialog-body label { margin-right: 10px; cursor: pointer; display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .ke-dialog-body img { display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .ke-dialog-body select { display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; width: auto; } .ke-dialog-body .ke-textarea { display: block; width: 408px; height: 260px; font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; border-color: #848484 #E0E0E0 #E0E0E0 #848484; border-style: solid; border-width: 1px; } .ke-dialog-body .ke-form { margin: 0; padding: 0; } .ke-dialog-loading { position: absolute; top: 0; left: 0; z-index: 1; text-align: center; } .ke-dialog-loading-content { background: url("../common/loading.gif") no-repeat; color: #666; font-size: 14px; font-weight: bold; height: 31px; line-height: 31px; padding-left: 36px; } .ke-dialog-row { margin-bottom: 10px; } .ke-dialog-footer { font: 12px/1 "sans serif",tahoma,verdana,helvetica; text-align: right; padding:0 0 5px 0; background-color: #F0F0EE; } .ke-dialog-preview, .ke-dialog-yes { margin: 5px; } .ke-dialog-no { margin: 5px 10px 5px 5px; } .ke-dialog-mask { background-color:#FFF; filter:alpha(opacity=50); opacity:0.5; } .ke-button-common { background: url(bg.gif) no-repeat scroll 0 0 transparent; cursor: pointer; height: 25px; line-height: 25px; overflow: visible; display: inline-block; vertical-align: top; } .ke-button-outer { background-position: 0 0; padding: 0; position: relative; display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .ke-button { background-position: right 0; padding: 0 12px; margin: 0; font-family: "sans serif",tahoma,verdana,helvetica; border: 0 none; color: #333; font-size: 12px; font-weight: bold; left: 2px; text-decoration: none; } /* inputbox */ .ke-input-text { background-color:#FFFFFF; font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; line-height: 17px; height: 17px; padding: 2px 4px; border-color: #848484 #E0E0E0 #E0E0E0 #848484; border-style: solid; border-width: 1px; display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .ke-input-number { width: 50px; } .ke-input-color { border: 1px solid #A0A0A0; background-color: #FFFFFF; font-size: 12px; width: 60px; height: 20px; line-height: 20px; padding-left: 5px; overflow: hidden; cursor: pointer; display: -moz-inline-stack; display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .ke-upload-area { position: relative; overflow: hidden; margin: 0; padding: 0; } .ke-upload-area .ke-upload-file { position: absolute; top: 0; right: 0; height: 25px; padding: 0; margin: 0; z-index: 811212; border: 0 none; opacity: 0; filter: alpha(opacity=0); } /* tabs */ .ke-tabs { font: 12px/1 "sans serif",tahoma,verdana,helvetica; border-bottom:1px solid #A0A0A0; padding-left:5px; margin-bottom:10px; } .ke-tabs-ul { list-style-image:none; list-style-position:outside; list-style-type:none; margin:0; padding:0; } .ke-tabs-li { position: relative; border: 1px solid #A0A0A0; background-color: #E0E0E0; margin: 0 2px -1px 0; padding: 0 20px; float: left; line-height: 25px; text-align: center; color: #555555; cursor: pointer; } .ke-tabs-li-selected { background-color: #F0F0EE; border-bottom: 1px solid #F0F0EE; color: #000; cursor: default; } .ke-tabs-li-on { background-color: #F0F0EE; color: #000; } /* emoticons */ .ke-plugin-emoticons { position: relative; } .ke-plugin-emoticons .ke-preview { position: absolute; text-align: center; margin: 2px; padding: 10px; top: 0; border: 1px solid #A0A0A0; background-color: #FFFFFF; display: none; } .ke-plugin-emoticons .ke-preview-img { border:0; margin:0; padding:0; } .ke-plugin-emoticons .ke-table { border:0; margin:0; padding:0; border-collapse:separate; } .ke-plugin-emoticons .ke-cell { margin:0; padding:1px; border:1px solid #F0F0EE; cursor:pointer; } .ke-plugin-emoticons .ke-on { border: 1px solid #5690D2; background-color: #E9EFF6; } .ke-plugin-emoticons .ke-img { display:block; background-repeat:no-repeat; overflow:hidden; margin:2px; width:24px; height:24px; margin: 0; padding: 0; border: 0; } .ke-plugin-emoticons .ke-page { text-align: right; margin: 5px; padding: 0; border: 0; font: 12px/1 "sans serif",tahoma,verdana,helvetica; color: #333; text-decoration: none; } .ke-plugin-plainpaste-textarea, .ke-plugin-wordpaste-iframe { display: block; width: 408px; height: 260px; font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; border-color: #848484 #E0E0E0 #E0E0E0 #848484; border-style: solid; border-width: 1px; } /* filemanager */ .ke-plugin-filemanager-header { width: 100%; margin-bottom: 10px; } .ke-plugin-filemanager-header .ke-left { float: left; } .ke-plugin-filemanager-header .ke-right { float: right; } .ke-plugin-filemanager-body { overflow: scroll; background-color:#FFFFFF; border-color: #848484 #E0E0E0 #E0E0E0 #848484; border-style: solid; border-width: 1px; width: 470px; height: 370px; padding: 5px; } .ke-plugin-filemanager-body .ke-item { width: 100px; margin: 5px; } .ke-plugin-filemanager-body .ke-photo { border: 1px solid #DDDDDD; background-color:#FFFFFF; padding: 10px; } .ke-plugin-filemanager-body .ke-name { width: 100px; text-align: center; overflow: hidden; height:16px; } .ke-plugin-filemanager-body .ke-on { border: 1px solid #5690D2; background-color: #E9EFF6; } .ke-plugin-filemanager-body .ke-table { width: 95%; border: 0; margin: 0; padding: 0; border-collapse: separate; } .ke-plugin-filemanager-body .ke-table .ke-cell { margin: 0; padding: 0; border: 0; } .ke-plugin-filemanager-body .ke-table .ke-name { width: 55%; text-align: left; } .ke-plugin-filemanager-body .ke-table .ke-size { width: 15%; text-align: left; } .ke-plugin-filemanager-body .ke-table .ke-datetime { width: 30%; text-align: center; } /* template */ .ke-plugin-template .ke-header { width: 100%; margin-bottom: 10px; } .ke-plugin-template label { margin-right: 0; cursor: pointer; font-weight: normal; display: inline; vertical-align: top; } .ke-plugin-template .ke-left { float: left; } .ke-plugin-template .ke-right { float: right; }
zzblog
web/js/kindeditor/themes/default/default.css
CSS
asf20
19,872
/* container */ .ke-container-simple { display: block; border: 1px solid #CCC; background-color: #FFF; overflow: hidden; } /* toolbar */ .ke-container-simple .ke-toolbar { border-bottom: 1px solid #CCC; background-color: #FFF; padding: 2px 5px; overflow: hidden; } .ke-container-simple .ke-toolbar .ke-outline { border: 1px solid #FFF; background-color: transparent; margin: 1px; padding: 1px 2px; font-size: 0; line-height: 0; overflow: hidden; cursor: pointer; } .ke-container-simple .ke-toolbar .ke-on { border: 1px solid #5690D2; } .ke-container-simple .ke-toolbar .ke-selected { border: 1px solid #5690D2; background-color: #E9EFF6; } .ke-container-simple .ke-toolbar .ke-disabled { cursor: default; } /* statusbar */ .ke-container-simple .ke-statusbar { position: relative; background-color: #FFF; border-top: 1px solid #CCCCCC; font-size: 0; line-height: 0; *height: 12px; overflow: hidden; text-align: center; cursor: s-resize; } /* menu */ .ke-menu-simple { border: 1px solid #A0A0A0; background-color: #FFF; color: #222222; padding: 2px; font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; text-align: left; overflow: hidden; } .ke-menu-simple .ke-menu-item { border: 1px solid #FFF; background-color: #FFF; color: #222222; height: 24px; overflow: hidden; cursor: pointer; } .ke-menu-simple .ke-menu-item-on { border: 1px solid #5690D2; background-color: #FFF; } /* colorpicker */ .ke-colorpicker-simple { border: 1px solid #A0A0A0; background-color: #FEFEFE; color: #222222; padding: 2px; } .ke-colorpicker-simple .ke-colorpicker-cell { font-size: 0; line-height: 0; border: 1px solid #FEFEFE; cursor: pointer; margin:3px; padding:0; } .ke-colorpicker-simple .ke-colorpicker-cell-top { font-family: "sans serif",tahoma,verdana,helvetica; font-size: 12px; line-height: 24px; border: 1px solid #FEFEFE; cursor: pointer; margin:0; padding:0; text-align: center; } .ke-colorpicker-simple .ke-colorpicker-cell-on { border: 1px solid #5690D2; } .ke-colorpicker-simple .ke-colorpicker-cell-selected { border: 1px solid #2446AB; } /* dialog */ .ke-dialog-simple { position: absolute; margin: 0; padding: 0; } .ke-dialog-simple .ke-dialog-content { color: #333; background-color: #FFF; } .ke-dialog-simple .ke-dialog-shadow { background-color: #FFF; } .ke-dialog-simple .ke-dialog-header { border:0; margin:0; background-color: #FFF; padding: 10px; text-align: left; font: 14px/1 "sans serif",tahoma,verdana,helvetica; font-weight: bold; color: #222222; background-color: #FFF; cursor: move; } .ke-dialog-simple .ke-dialog-body { background-color: #FFF; } .ke-dialog-simple .ke-dialog-footer { background-color: #FFF; } /* tabs */ .ke-dialog-simple .ke-tabs { font: 12px/1 "sans serif",tahoma,verdana,helvetica; border-bottom:1px solid #A0A0A0; padding-left:5px; margin-bottom:10px; } .ke-dialog-simple .ke-tabs-li { position: relative; border: 1px solid #A0A0A0; background-color: #F0F0EE; margin: 0 2px -1px 0; padding: 0 20px; float: left; line-height: 25px; text-align: center; color: #555; cursor: pointer; } .ke-dialog-simple .ke-tabs-li-selected { background-color: #FFF; border-bottom: 1px solid #FFF; color: #000; cursor: default; } .ke-dialog-simple .ke-tabs-li-on { background-color: #FFF; color: #000; }
zzblog
web/js/kindeditor/themes/simple/simple.css
CSS
asf20
3,338
/* * Table */ table.dataTable { margin: 0 auto; clear: both; width: 100%; } table.dataTable thead th { padding: 3px 18px 3px 10px; border-bottom: 1px solid black; font-weight: bold; cursor: pointer; *cursor: hand; } table.dataTable tfoot th { padding: 3px 18px 3px 10px; border-top: 1px solid black; font-weight: bold; } table.dataTable td { padding: 3px 10px; } table.dataTable td.center, table.dataTable td.dataTables_empty { text-align: center; } table.dataTable tr.odd { background-color: #E2E4FF; } table.dataTable tr.even { background-color: white; } table.dataTable tr.odd td.sorting_1 { background-color: #D3D6FF; } table.dataTable tr.odd td.sorting_2 { background-color: #DADCFF; } table.dataTable tr.odd td.sorting_3 { background-color: #E0E2FF; } table.dataTable tr.even td.sorting_1 { background-color: #EAEBFF; } table.dataTable tr.even td.sorting_2 { background-color: #F2F3FF; } table.dataTable tr.even td.sorting_3 { background-color: #F9F9FF; } /* * Table wrapper */ .dataTables_wrapper { position: relative; clear: both; *zoom: 1; } /* * Page length menu */ .dataTables_length { float: left; } /* * Filter */ .dataTables_filter { float: right; text-align: right; } /* * Table information */ .dataTables_info { clear: both; float: left; } /* * Pagination */ .dataTables_paginate { float: right; text-align: right; } /* Two button pagination - previous / next */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; float: left; cursor: pointer; *cursor: hand; color: #111 !important; } .paginate_disabled_previous:hover, .paginate_enabled_previous:hover, .paginate_disabled_next:hover, .paginate_enabled_next:hover { text-decoration: none !important; } .paginate_disabled_previous:active, .paginate_enabled_previous:active, .paginate_disabled_next:active, .paginate_enabled_next:active { outline: none; } .paginate_disabled_previous, .paginate_disabled_next { color: #666 !important; } .paginate_disabled_previous, .paginate_enabled_previous { padding-left: 23px; } .paginate_disabled_next, .paginate_enabled_next { padding-right: 23px; margin-left: 10px; } .paginate_enabled_previous { background: url('../images/back_enabled.png') no-repeat top left; } .paginate_enabled_previous:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; } .paginate_disabled_previous { background: url('../images/back_disabled.png') no-repeat top left; } .paginate_enabled_next { background: url('../images/forward_enabled.png') no-repeat top right; } .paginate_enabled_next:hover { background: url('../images/forward_enabled_hover.png') no-repeat top right; } .paginate_disabled_next { background: url('../images/forward_disabled.png') no-repeat top right; } /* Full number pagination */ .paging_full_numbers { height: 22px; line-height: 22px; } .paging_full_numbers a:active { outline: none } .paging_full_numbers a:hover { text-decoration: none; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; color: #333 !important; } .paging_full_numbers a.paginate_button { background-color: #ddd; } .paging_full_numbers a.paginate_button:hover { background-color: #ccc; text-decoration: none !important; } .paging_full_numbers a.paginate_active { background-color: #99B3FF; } /* * Processing indicator */ .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } /* * Sorting */ .sorting { background: url('../images/sort_both.png') no-repeat center right; } .sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; } .sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; } .sorting_asc_disabled { background: url('../images/sort_asc_disabled.png') no-repeat center right; } .sorting_desc_disabled { background: url('../images/sort_desc_disabled.png') no-repeat center right; } table.dataTable th:active { outline: none; } /* * Scrolling */ .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; }
zzblog
web/js/datatables/css/jquery.dataTables.css
CSS
asf20
4,479
/* * Table */ table.dataTable { margin: 0 auto; clear: both; width: 100%; } table.dataTable thead th { padding: 3px 0px 3px 10px; cursor: pointer; *cursor: hand; } table.dataTable tfoot th { padding: 3px 10px; } table.dataTable td { padding: 3px 10px; } table.dataTable td.center, table.dataTable td.dataTables_empty { text-align: center; } table.dataTable tr.odd { background-color: #E2E4FF; } table.dataTable tr.even { background-color: white; } table.dataTable tr.odd td.sorting_1 { background-color: #D3D6FF; } table.dataTable tr.odd td.sorting_2 { background-color: #DADCFF; } table.dataTable tr.odd td.sorting_3 { background-color: #E0E2FF; } table.dataTable tr.even td.sorting_1 { background-color: #EAEBFF; } table.dataTable tr.even td.sorting_2 { background-color: #F2F3FF; } table.dataTable tr.even td.sorting_3 { background-color: #F9F9FF; } /* * Table wrapper */ .dataTables_wrapper { position: relative; clear: both; *zoom: 1; } .dataTables_wrapper .ui-widget-header { font-weight: normal; } .dataTables_wrapper .ui-toolbar { padding: 5px; } /* * Page length menu */ .dataTables_length { float: left; } /* * Filter */ .dataTables_filter { float: right; text-align: right; } /* * Table information */ .dataTables_info { padding-top: 3px; clear: both; float: left; } /* * Pagination */ .dataTables_paginate { float: right; text-align: right; } .dataTables_paginate .ui-button { margin-right: -0.1em !important; } .paging_two_button .ui-button { float: left; cursor: pointer; * cursor: hand; } .paging_full_numbers .ui-button { padding: 2px 6px; margin: 0; cursor: pointer; * cursor: hand; color: #333 !important; } /* Two button pagination - previous / next */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; float: left; cursor: pointer; *cursor: hand; color: #111 !important; } .paginate_disabled_previous:hover, .paginate_enabled_previous:hover, .paginate_disabled_next:hover, .paginate_enabled_next:hover { text-decoration: none !important; } .paginate_disabled_previous:active, .paginate_enabled_previous:active, .paginate_disabled_next:active, .paginate_enabled_next:active { outline: none; } .paginate_disabled_previous, .paginate_disabled_next { color: #666 !important; } .paginate_disabled_previous, .paginate_enabled_previous { padding-left: 23px; } .paginate_disabled_next, .paginate_enabled_next { padding-right: 23px; margin-left: 10px; } .paginate_enabled_previous { background: url('../images/back_enabled.png') no-repeat top left; } .paginate_enabled_previous:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; } .paginate_disabled_previous { background: url('../images/back_disabled.png') no-repeat top left; } .paginate_enabled_next { background: url('../images/forward_enabled.png') no-repeat top right; } .paginate_enabled_next:hover { background: url('../images/forward_enabled_hover.png') no-repeat top right; } .paginate_disabled_next { background: url('../images/forward_disabled.png') no-repeat top right; } /* Full number pagination */ .paging_full_numbers a:active { outline: none } .paging_full_numbers a:hover { text-decoration: none; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; color: #333 !important; } .paging_full_numbers a.paginate_button { background-color: #ddd; } .paging_full_numbers a.paginate_button:hover { background-color: #ccc; text-decoration: none !important; } .paging_full_numbers a.paginate_active { background-color: #99B3FF; } /* * Processing indicator */ .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } /* * Sorting */ table.dataTable thead th div.DataTables_sort_wrapper { position: relative; padding-right: 20px; padding-right: 20px; } table.dataTable thead th div.DataTables_sort_wrapper span { position: absolute; top: 50%; margin-top: -8px; right: 0; } table.dataTable th:active { outline: none; } /* * Scrolling */ .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; }
zzblog
web/js/datatables/css/jquery.dataTables_themeroller.css
CSS
asf20
4,517
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * General page setup */ #dt_example { font: 80%/1.45em "Lucida Grande", Verdana, Arial, Helvetica, sans-serif; margin: 0; padding: 0; color: #333; background-color: #fff; } #dt_example #container { width: 800px; margin: 30px auto; padding: 0; } #dt_example #footer { margin: 50px auto 0 auto; padding: 0; } #dt_example #demo { margin: 30px auto 0 auto; } #dt_example .demo_jui { margin: 30px auto 0 auto; } #dt_example .big { font-size: 1.3em; font-weight: bold; line-height: 1.6em; color: #4E6CA3; } #dt_example .spacer { height: 20px; clear: both; } #dt_example .clear { clear: both; } #dt_example pre { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } #dt_example h1 { margin-top: 2em; font-size: 1.3em; font-weight: normal; line-height: 1.6em; color: #4E6CA3; border-bottom: 1px solid #B0BED9; clear: both; } #dt_example h2 { font-size: 1.2em; font-weight: normal; line-height: 1.6em; color: #4E6CA3; clear: both; } #dt_example a { color: #0063DC; text-decoration: none; } #dt_example a:hover { text-decoration: underline; } #dt_example ul { color: #4E6CA3; } .css_right { float: right; } .css_left { float: left; } .demo_links { float: left; width: 50%; margin-bottom: 1em; } #demo_info { padding: 5px; border: 1px solid #B0BED9; height: 100px; width: 100%; overflow: auto; }
zzblog
web/js/datatables/css/demo_page.css
CSS
asf20
1,447
/* * File: demo_table_jui.css * CVS: $Id$ * Description: CSS descriptions for DataTables demo pages * Author: Allan Jardine * Created: Tue May 12 06:47:22 BST 2009 * Modified: $Date$ by $Author$ * Language: CSS * Project: DataTables * * Copyright 2009 Allan Jardine. All Rights Reserved. * * *************************************************************************** * DESCRIPTION * * The styles given here are suitable for the demos that are used with the standard DataTables * distribution (see www.datatables.net). You will most likely wish to modify these styles to * meet the layout requirements of your site. * * Common issues: * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * no conflict between the two pagination types. If you want to use full_numbers pagination * ensure that you either have "example_alt_pagination" as a body class name, or better yet, * modify that selector. * Note that the path used for Images is relative. All images are by default located in * ../images/ - relative to this CSS file. */ /* * jQuery UI specific styling */ .paging_two_button .ui-button { float: left; cursor: pointer; * cursor: hand; } .paging_full_numbers .ui-button { padding: 2px 6px; margin: 0; cursor: pointer; * cursor: hand; color: #333 !important; } .dataTables_paginate .ui-button { margin-right: -0.1em !important; } .paging_full_numbers { width: 350px !important; } .dataTables_wrapper .ui-toolbar { padding: 5px; } .dataTables_paginate { width: auto; } .dataTables_info { padding-top: 3px; } table.display thead th { padding: 3px 0px 3px 10px; cursor: pointer; * cursor: hand; } div.dataTables_wrapper .ui-widget-header { font-weight: normal; } /* * Sort arrow icon positioning */ table.display thead th div.DataTables_sort_wrapper { position: relative; padding-right: 20px; padding-right: 20px; } table.display thead th div.DataTables_sort_wrapper span { position: absolute; top: 50%; margin-top: -8px; right: 0; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Everything below this line is the same as demo_table.css. This file is * required for 'cleanliness' of the markup * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables features */ .dataTables_wrapper { position: relative; clear: both; } .dataTables_processing { position: absolute; top: 0px; left: 50%; width: 250px; margin-left: -125px; border: 1px solid #ddd; text-align: center; color: #999; font-size: 11px; padding: 2px 0; } .dataTables_length { width: 40%; float: left; } .dataTables_filter { width: 50%; float: right; text-align: right; } .dataTables_info { width: 50%; float: left; } .dataTables_paginate { float: right; text-align: right; } /* Pagination nested */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; width: 19px; margin-left: 3px; float: left; } .paginate_disabled_previous { background-image: url('../images/back_disabled.jpg'); } .paginate_enabled_previous { background-image: url('../images/back_enabled.jpg'); } .paginate_disabled_next { background-image: url('../images/forward_disabled.jpg'); } .paginate_enabled_next { background-image: url('../images/forward_enabled.jpg'); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables display */ table.display { margin: 0 auto; width: 100%; clear: both; border-collapse: collapse; } table.display tfoot th { padding: 3px 0px 3px 10px; font-weight: bold; font-weight: normal; } table.display tr.heading2 td { border-bottom: 1px solid #aaa; } table.display td { padding: 3px 10px; } table.display td.center { text-align: center; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables sorting */ .sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; } .sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; } .sorting { background: url('../images/sort_both.png') no-repeat center right; } .sorting_asc_disabled { background: url('../images/sort_asc_disabled.png') no-repeat center right; } .sorting_desc_disabled { background: url('../images/sort_desc_disabled.png') no-repeat center right; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables row classes */ table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeC { background-color: #ddddff; } table.display tr.even.gradeC { background-color: #eeeeff; } table.display tr.odd.gradeX { background-color: #ffdddd; } table.display tr.even.gradeX { background-color: #ffeeee; } table.display tr.odd.gradeU { background-color: #ddd; } table.display tr.even.gradeU { background-color: #eee; } tr.odd { background-color: #E2E4FF; } tr.even { background-color: white; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Misc */ .dataTables_scroll { clear: both; } .top, .bottom { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } .top .dataTables_info { float: none; } .clear { clear: both; } .dataTables_empty { text-align: center; } tfoot input { margin: 0.5em 0; width: 100%; color: #444; } tfoot input.search_init { color: #999; } td.group { background-color: #d1cfd0; border-bottom: 2px solid #A19B9E; border-top: 2px solid #A19B9E; } td.details { background-color: #d1cfd0; border: 2px solid #A19B9E; } .example_alt_pagination div.dataTables_info { width: 40%; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; color: #333 !important; } .paging_full_numbers a.paginate_button { background-color: #ddd; } .paging_full_numbers a.paginate_button:hover { background-color: #ccc; text-decoration: none !important; } .paging_full_numbers a.paginate_active { background-color: #99B3FF; } tr.even.row_selected td { background-color: #B0BED9; } tr.odd.row_selected td { background-color: #9FAFD1; } /* * Sorting classes for columns */ /* For the standard odd/even */ tr.odd td.sorting_1 { background-color: #D3D6FF; } tr.odd td.sorting_2 { background-color: #DADCFF; } tr.odd td.sorting_3 { background-color: #E0E2FF; } tr.even td.sorting_1 { background-color: #EAEBFF; } tr.even td.sorting_2 { background-color: #F2F3FF; } tr.even td.sorting_3 { background-color: #F9F9FF; } /* For the Conditional-CSS grading rows */ /* Colour calculations (based off the main row colours) Level 1: dd > c4 ee > d5 Level 2: dd > d1 ee > e2 */ tr.odd.gradeA td.sorting_1 { background-color: #c4ffc4; } tr.odd.gradeA td.sorting_2 { background-color: #d1ffd1; } tr.odd.gradeA td.sorting_3 { background-color: #d1ffd1; } tr.even.gradeA td.sorting_1 { background-color: #d5ffd5; } tr.even.gradeA td.sorting_2 { background-color: #e2ffe2; } tr.even.gradeA td.sorting_3 { background-color: #e2ffe2; } tr.odd.gradeC td.sorting_1 { background-color: #c4c4ff; } tr.odd.gradeC td.sorting_2 { background-color: #d1d1ff; } tr.odd.gradeC td.sorting_3 { background-color: #d1d1ff; } tr.even.gradeC td.sorting_1 { background-color: #d5d5ff; } tr.even.gradeC td.sorting_2 { background-color: #e2e2ff; } tr.even.gradeC td.sorting_3 { background-color: #e2e2ff; } tr.odd.gradeX td.sorting_1 { background-color: #ffc4c4; } tr.odd.gradeX td.sorting_2 { background-color: #ffd1d1; } tr.odd.gradeX td.sorting_3 { background-color: #ffd1d1; } tr.even.gradeX td.sorting_1 { background-color: #ffd5d5; } tr.even.gradeX td.sorting_2 { background-color: #ffe2e2; } tr.even.gradeX td.sorting_3 { background-color: #ffe2e2; } tr.odd.gradeU td.sorting_1 { background-color: #c4c4c4; } tr.odd.gradeU td.sorting_2 { background-color: #d1d1d1; } tr.odd.gradeU td.sorting_3 { background-color: #d1d1d1; } tr.even.gradeU td.sorting_1 { background-color: #d5d5d5; } tr.even.gradeU td.sorting_2 { background-color: #e2e2e2; } tr.even.gradeU td.sorting_3 { background-color: #e2e2e2; } /* * Row highlighting example */ .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { background-color: #ECFFB3; } .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { background-color: #E6FF99; }
zzblog
web/js/datatables/css/demo_table_jui.css
CSS
asf20
8,935
/* * File: demo_table.css * CVS: $Id$ * Description: CSS descriptions for DataTables demo pages * Author: Allan Jardine * Created: Tue May 12 06:47:22 BST 2009 * Modified: $Date$ by $Author$ * Language: CSS * Project: DataTables * * Copyright 2009 Allan Jardine. All Rights Reserved. * * *************************************************************************** * DESCRIPTION * * The styles given here are suitable for the demos that are used with the standard DataTables * distribution (see www.datatables.net). You will most likely wish to modify these styles to * meet the layout requirements of your site. * * Common issues: * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * no conflict between the two pagination types. If you want to use full_numbers pagination * ensure that you either have "example_alt_pagination" as a body class name, or better yet, * modify that selector. * Note that the path used for Images is relative. All images are by default located in * ../images/ - relative to this CSS file. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables features */ .dataTables_wrapper { position: relative; clear: both; zoom: 1; /* Feeling sorry for IE */ } .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } .dataTables_length { width: 40%; float: left; } .dataTables_filter { width: 50%; float: right; text-align: right; } .dataTables_info { width: 60%; float: left; } .dataTables_paginate { float: right; text-align: right; } /* Pagination nested */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; float: left; cursor: pointer; *cursor: hand; color: #111 !important; } .paginate_disabled_previous:hover, .paginate_enabled_previous:hover, .paginate_disabled_next:hover, .paginate_enabled_next:hover { text-decoration: none !important; } .paginate_disabled_previous:active, .paginate_enabled_previous:active, .paginate_disabled_next:active, .paginate_enabled_next:active { outline: none; } .paginate_disabled_previous, .paginate_disabled_next { color: #666 !important; } .paginate_disabled_previous, .paginate_enabled_previous { padding-left: 23px; } .paginate_disabled_next, .paginate_enabled_next { padding-right: 23px; margin-left: 10px; } .paginate_disabled_previous { background: url('../images/back_disabled.png') no-repeat top left; } .paginate_enabled_previous { background: url('../images/back_enabled.png') no-repeat top left; } .paginate_enabled_previous:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; } .paginate_disabled_next { background: url('../images/forward_disabled.png') no-repeat top right; } .paginate_enabled_next { background: url('../images/forward_enabled.png') no-repeat top right; } .paginate_enabled_next:hover { background: url('../images/forward_enabled_hover.png') no-repeat top right; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables display */ table.display { margin: 0 auto; clear: both; width: 100%; /* Note Firefox 3.5 and before have a bug with border-collapse * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) * border-spacing: 0; is one possible option. Conditional-css.com is * useful for this kind of thing * * Further note IE 6/7 has problems when calculating widths with border width. * It subtracts one px relative to the other browsers from the first column, and * adds one to the end... * * If you want that effect I'd suggest setting a border-top/left on th/td's and * then filling in the gaps with other borders. */ } table.display thead th { padding: 3px 18px 3px 10px; border-bottom: 1px solid black; font-weight: bold; cursor: pointer; * cursor: hand; } table.display tfoot th { padding: 3px 18px 3px 10px; border-top: 1px solid black; font-weight: bold; } table.display tr.heading2 td { border-bottom: 1px solid #aaa; } table.display td { padding: 3px 10px; } table.display td.center { text-align: center; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables sorting */ .sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; } .sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; } .sorting { background: url('../images/sort_both.png') no-repeat center right; } .sorting_asc_disabled { background: url('../images/sort_asc_disabled.png') no-repeat center right; } .sorting_desc_disabled { background: url('../images/sort_desc_disabled.png') no-repeat center right; } th:active { outline: none; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables row classes */ table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeC { background-color: #ddddff; } table.display tr.even.gradeC { background-color: #eeeeff; } table.display tr.odd.gradeX { background-color: #ffdddd; } table.display tr.even.gradeX { background-color: #ffeeee; } table.display tr.odd.gradeU { background-color: #ddd; } table.display tr.even.gradeU { background-color: #eee; } tr.odd { background-color: #E2E4FF; } tr.even { background-color: white; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Misc */ .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; } .top, .bottom { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } .top .dataTables_info { float: none; } .clear { clear: both; } .dataTables_empty { text-align: center; } tfoot input { margin: 0.5em 0; width: 100%; color: #444; } tfoot input.search_init { color: #999; } td.group { background-color: #d1cfd0; border-bottom: 2px solid #A19B9E; border-top: 2px solid #A19B9E; } td.details { background-color: #d1cfd0; border: 2px solid #A19B9E; } .example_alt_pagination div.dataTables_info { width: 40%; } .paging_full_numbers { width: 400px; height: 22px; line-height: 22px; } .paging_full_numbers a:active { outline: none } .paging_full_numbers a:hover { text-decoration: none; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; color: #333 !important; } .paging_full_numbers a.paginate_button { background-color: #ddd; } .paging_full_numbers a.paginate_button:hover { background-color: #ccc; text-decoration: none !important; } .paging_full_numbers a.paginate_active { background-color: #99B3FF; } tr.row_selected { background-color: #B0BED9; } tr.row_selected { background-color: #9FAFD1; } /* * Sorting classes for columns */ /* For the standard odd/even */ tr.odd td.sorting_1 { background-color: #D3D6FF; } tr.odd td.sorting_2 { background-color: #DADCFF; } tr.odd td.sorting_3 { background-color: #E0E2FF; } tr.even td.sorting_1 { background-color: #EAEBFF; } tr.even td.sorting_2 { background-color: #F2F3FF; } tr.even td.sorting_3 { background-color: #F9F9FF; } /* For the Conditional-CSS grading rows */ /* Colour calculations (based off the main row colours) Level 1: dd > c4 ee > d5 Level 2: dd > d1 ee > e2 */ tr.odd.gradeA td.sorting_1 { background-color: #c4ffc4; } tr.odd.gradeA td.sorting_2 { background-color: #d1ffd1; } tr.odd.gradeA td.sorting_3 { background-color: #d1ffd1; } tr.even.gradeA td.sorting_1 { background-color: #d5ffd5; } tr.even.gradeA td.sorting_2 { background-color: #e2ffe2; } tr.even.gradeA td.sorting_3 { background-color: #e2ffe2; } tr.odd.gradeC td.sorting_1 { background-color: #c4c4ff; } tr.odd.gradeC td.sorting_2 { background-color: #d1d1ff; } tr.odd.gradeC td.sorting_3 { background-color: #d1d1ff; } tr.even.gradeC td.sorting_1 { background-color: #d5d5ff; } tr.even.gradeC td.sorting_2 { background-color: #e2e2ff; } tr.even.gradeC td.sorting_3 { background-color: #e2e2ff; } tr.odd.gradeX td.sorting_1 { background-color: #ffc4c4; } tr.odd.gradeX td.sorting_2 { background-color: #ffd1d1; } tr.odd.gradeX td.sorting_3 { background-color: #ffd1d1; } tr.even.gradeX td.sorting_1 { background-color: #ffd5d5; } tr.even.gradeX td.sorting_2 { background-color: #ffe2e2; } tr.even.gradeX td.sorting_3 { background-color: #ffe2e2; } tr.odd.gradeU td.sorting_1 { background-color: #c4c4c4; } tr.odd.gradeU td.sorting_2 { background-color: #d1d1d1; } tr.odd.gradeU td.sorting_3 { background-color: #d1d1d1; } tr.even.gradeU td.sorting_1 { background-color: #d5d5d5; } tr.even.gradeU td.sorting_2 { background-color: #e2e2e2; } tr.even.gradeU td.sorting_3 { background-color: #e2e2e2; } /* * Row highlighting example */ .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { background-color: #ECFFB3; } .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { background-color: #E6FF99; } .ex_highlight_row #example tr.even:hover { background-color: #ECFFB3; } .ex_highlight_row #example tr.even:hover td.sorting_1 { background-color: #DDFF75; } .ex_highlight_row #example tr.even:hover td.sorting_2 { background-color: #E7FF9E; } .ex_highlight_row #example tr.even:hover td.sorting_3 { background-color: #E2FF89; } .ex_highlight_row #example tr.odd:hover { background-color: #E6FF99; } .ex_highlight_row #example tr.odd:hover td.sorting_1 { background-color: #D6FF5C; } .ex_highlight_row #example tr.odd:hover td.sorting_2 { background-color: #E0FF84; } .ex_highlight_row #example tr.odd:hover td.sorting_3 { background-color: #DBFF70; } /* * KeyTable */ table.KeyTable td { border: 3px solid transparent; } table.KeyTable td.focus { border: 3px solid #3366FF; } table.display tr.gradeA { background-color: #eeffee; } table.display tr.gradeC { background-color: #ddddff; } table.display tr.gradeX { background-color: #ffdddd; } table.display tr.gradeU { background-color: #ddd; } div.box { height: 100px; padding: 10px; overflow: auto; border: 1px solid #8080FF; background-color: #E5E5FF; }
zzblog
web/js/datatables/css/demo_table.css
CSS
asf20
10,642
/*------------------------------------- zTree Style version: 3.0 author: Hunter.z email: hunter.z@263.net website: http://code.google.com/p/jquerytree/ -------------------------------------*/ .ztree * {padding:0; margin:0; font-size:12px; font-family: Verdana, Arial, Helvetica, AppleGothic, sans-serif} .ztree {margin:0; padding:5px; color:#333} .ztree li{padding:0; margin:0; list-style:none; line-height:14px; text-align:left; white-space:nowrap} .ztree li ul{ margin:0; padding:0 0 0 18px} .ztree li ul.line{ background:url(./img/line_conn.gif) 0 0 repeat-y;} .ztree li a {padding:1px 3px 0 0; margin:0 10px 0 0; cursor:pointer; height:16px; color:#333; background-color: transparent; text-decoration:none; vertical-align:top; display: inline-block} .ztree li a:hover {text-decoration:underline} .ztree li a.curSelectedNode {padding-top:0px; background-color:#FFE6B0; color:black; border:1px #FFB951 solid; opacity:0.8; filter:alpha(opacity=80)} .ztree li a.curSelectedNode_Edit {padding-top:0px; background-color:#FFE6B0; color:black; border:1px #FFB951 solid; opacity:0.8; filter:alpha(opacity=80)} .ztree li a.tmpTargetNode {padding-top:0px; background-color:#316AC5; color:white; border:1px #316AC5 solid; opacity:0.8; filter:alpha(opacity=80)} .ztree li a input.rename {height:14px; width:80px; padding:0; margin:0; font-size:12px; border:1px #7EC4CC solid; *border:0px} .ztree li span {line-height:16px; margin-right: 2px} .ztree li button {width:16px; height:16px; vertical-align:middle; border:0 none; cursor: pointer;outline:none; background-color:transparent; background-repeat:no-repeat; background-attachment: scroll; background-image:url("./img/zTreeStandard.png"); *background-image:url("./img/zTreeStandard.gif")} .ztree li button.chk {width:13px; height:13px; margin:0 3px 0 0; cursor: auto} .ztree li button.chk.checkbox_false_full {background-position:0 0} .ztree li button.chk.checkbox_false_full_focus {background-position:0 -12px} .ztree li button.chk.checkbox_true_full {background-position:0 -24px} .ztree li button.chk.checkbox_true_full_focus {background-position:0 -36px} .ztree li button.chk.checkbox_true_part {background-position:0 -48px} .ztree li button.chk.checkbox_true_part_focus {background-position:0 -60px} .ztree li button.chk.checkbox_false_part {background-position:0 -72px} .ztree li button.chk.checkbox_false_part_focus {background-position:0 -84px} .ztree li button.chk.checkbox_false_disable {background-position:0 -97px} .ztree li button.chk.checkbox_true_disable {background-position:0 -109px} .ztree li button.chk.radio_false_full {background-position:-13px 0} .ztree li button.chk.radio_false_full_focus {background-position:-13px -12px} .ztree li button.chk.radio_true_full {background-position:-13px -24px} .ztree li button.chk.radio_true_full_focus {background-position:-13px -36px} .ztree li button.chk.radio_true_part {background-position:-13px -48px} .ztree li button.chk.radio_true_part_focus {background-position:-13px -60px} .ztree li button.chk.radio_false_part {background-position:-13px -72px} .ztree li button.chk.radio_false_part_focus {background-position:-13px -84px} .ztree li button.chk.radio_false_disable {background-position:-13px -97px} .ztree li button.chk.radio_true_disable {background-position:-13px -109px} .ztree li button.switch {width:18px; height:18px} .ztree li button.root_open{background-position:-62px -54px} .ztree li button.root_close{background-position:-44px -54px} .ztree li button.roots_open{background-position:-62px 0} .ztree li button.roots_close{background-position:-44px 0} .ztree li button.center_open{background-position:-62px -18px} .ztree li button.center_close{background-position:-44px -18px} .ztree li button.bottom_open{background-position:-62px -36px} .ztree li button.bottom_close{background-position:-44px -36px} .ztree li button.noline_open{background-position:-62px -72px} .ztree li button.noline_close{background-position:-44px -72px} .ztree li button.root_docu{ background:none;} .ztree li button.roots_docu{background-position:-26px 0} .ztree li button.center_docu{background-position:-26px -18px} .ztree li button.bottom_docu{background-position:-26px -36px} .ztree li button.noline_docu{ background:none;} .ztree li button.ico_open{margin-right:2px; background-position:-80px -16px; vertical-align:top; *vertical-align:middle} .ztree li button.ico_close{margin-right:2px; background-position:-80px 0; vertical-align:top; *vertical-align:middle} .ztree li button.ico_docu{margin-right:2px; background-position:-80px -32px; vertical-align:top; *vertical-align:middle} .ztree li button.edit {margin-right:2px; background-position:-80px -48px; vertical-align:top; *vertical-align:middle} .ztree li button.remove {margin-right:2px; background-position:-80px -64px; vertical-align:top; *vertical-align:middle} .ztree li button.ico_loading{margin-right:2px; background:url(./img/loading.gif) no-repeat scroll 0 0 transparent; vertical-align:top; *vertical-align:middle} ul.tmpTargetzTree {background-color:#FFE6B0; opacity:0.8; filter:alpha(opacity=80)} button.tmpzTreeMove_arrow {width:16px; height:16px; padding:0; margin:2px 0 0 1px; border:0 none; position:absolute; background-color:transparent; background-repeat:no-repeat; background-attachment: scroll; background-position:-80px -80px; background-image:url("./img/zTreeStandard.png"); *background-image:url("./img/zTreeStandard.gif")} ul.ztree.zTreeDragUL {margin:0; padding:0; position:absolute; width:auto; height:auto;overflow:hidden; background-color:#cfcfcf; border:1px #00B83F dotted; opacity:0.8; filter:alpha(opacity=80)} .zTreeMask {z-index:10000; background-color:#cfcfcf; opacity:0.0; filter:alpha(opacity=0); position:absolute} /* level style*/ /*.ztree li button.level0 { display:none; } .ztree li ul.level0 { padding:0; background:none; }*/
zzblog
web/js/ztree/css/zTreeStyle.css
CSS
asf20
5,942
/** * jQuery JSON Plugin * version: 2.3 (2011-09-17) * * This document is licensed as free software under the terms of the * MIT License: http://www.opensource.org/licenses/mit-license.php * * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org * website's http://www.json.org/json2.js, which proclaims: * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that * I uphold. * * It is also influenced heavily by MochiKit's serializeJSON, which is * copyrighted 2005 by Bob Ippolito. */ (function( $ ) { var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; /** * jQuery.toJSON * Converts the given argument into a JSON respresentation. * * @param o {Mixed} The json-serializble *thing* to be converted * * If an object has a toJSON prototype, that will be used to get the representation. * Non-integer/string keys are skipped in the object, as are keys that point to a * function. * */ $.toJSON = typeof JSON === 'object' && JSON.stringify ? JSON.stringify : function( o ) { if ( o === null ) { return 'null'; } var type = typeof o; if ( type === 'undefined' ) { return undefined; } if ( type === 'number' || type === 'boolean' ) { return '' + o; } if ( type === 'string') { return $.quoteString( o ); } if ( type === 'object' ) { if ( typeof o.toJSON === 'function' ) { return $.toJSON( o.toJSON() ); } if ( o.constructor === Date ) { var month = o.getUTCMonth() + 1, day = o.getUTCDate(), year = o.getUTCFullYear(), hours = o.getUTCHours(), minutes = o.getUTCMinutes(), seconds = o.getUTCSeconds(), milli = o.getUTCMilliseconds(); if ( month < 10 ) { month = '0' + month; } if ( day < 10 ) { day = '0' + day; } if ( hours < 10 ) { hours = '0' + hours; } if ( minutes < 10 ) { minutes = '0' + minutes; } if ( seconds < 10 ) { seconds = '0' + seconds; } if ( milli < 100 ) { milli = '0' + milli; } if ( milli < 10 ) { milli = '0' + milli; } return '"' + year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"'; } if ( o.constructor === Array ) { var ret = []; for ( var i = 0; i < o.length; i++ ) { ret.push( $.toJSON( o[i] ) || 'null' ); } return '[' + ret.join(',') + ']'; } var name, val, pairs = []; for ( var k in o ) { type = typeof k; if ( type === 'number' ) { name = '"' + k + '"'; } else if (type === 'string') { name = $.quoteString(k); } else { // Keys must be numerical or string. Skip others continue; } type = typeof o[k]; if ( type === 'function' || type === 'undefined' ) { // Invalid values like these return undefined // from toJSON, however those object members // shouldn't be included in the JSON string at all. continue; } val = $.toJSON( o[k] ); pairs.push( name + ':' + val ); } return '{' + pairs.join( ',' ) + '}'; } }; /** * jQuery.evalJSON * Evaluates a given piece of json source. * * @param src {String} */ $.evalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function( src ) { return eval('(' + src + ')'); }; /** * jQuery.secureEvalJSON * Evals JSON in a way that is *more* secure. * * @param src {String} */ $.secureEvalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function( src ) { var filtered = src .replace( /\\["\\\/bfnrtu]/g, '@' ) .replace( /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace( /(?:^|:|,)(?:\s*\[)+/g, ''); if ( /^[\],:{}\s]*$/.test( filtered ) ) { return eval( '(' + src + ')' ); } else { throw new SyntaxError( 'Error parsing JSON, source is not valid.' ); } }; /** * jQuery.quoteString * Returns a string-repr of a string, escaping quotes intelligently. * Mostly a support function for toJSON. * Examples: * >>> jQuery.quoteString('apple') * "apple" * * >>> jQuery.quoteString('"Where are we going?", she asked.') * "\"Where are we going?\", she asked." */ $.quoteString = function( string ) { if ( string.match( escapeable ) ) { return '"' + string.replace( escapeable, function( a ) { var c = meta[a]; if ( typeof c === 'string' ) { return c; } c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + string + '"'; }; })( jQuery );
zzblog
web/js/json/jquery.json.js
JavaScript
asf20
4,712
function RollString(){ /*随机生成id*/ var ele = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; function rollChar(ele){ var randomInt = Math.round(Math.random() * ele.length - 1); return ele.charAt(randomInt); } this.roll = function(len){ var re = new Date().getTime().toString(); for(var x = 0;x < len;x++){ re = re + rollChar(ele); } return re; } } function Loop(array){ /*对输入的数组,进行循环输出*/ var color = array; var index = -1; var max = color.length - 1; this.loop = function(){ index++; if(index > max){ index = 0; } return color[index]; } } function formatDate(date){ /*输出格式化后的日期1988-08-08 17:18:30*/ var year = date.getFullYear(); var mon = date.getMonth() + 1; var day = date.getDate(); var hour = date.getHours(); var min = date.getMinutes(); var sec = date.getSeconds(); return year + "-" + mon + "-" + day + " " + hour + ":" + min + ":" + sec; } function setMid(target,speed,type){ /*对于设置为居中*/ var sw = document.documentElement.clientWidth; var sh = document.documentElement.clientHeight; $(target).css("position" , "absolute"); var w = d(target).width; var h = d(target).height; switch(type){ case "xy" : { $(target).stop(true,false).animate({ top : (sh - h) / 2, left : (sw - w) / 2 }, speed); break; } case "x" : { $(target).stop(true,false).animate({ left : (sw - w) / 2 }, speed); break; } case "y" : { $(target).stop(true,false).animate({ top : (sh - h) / 2 }, speed); break; } } } function d(jquery){ /*通过jquery,获取对象的位置大小信息*/ return{ top : $(jquery).offset().top, left : $(jquery).offset().left, right : $(jquery).offset().right, width : parseInt($(jquery).css("width")), height : parseInt($(jquery).css("height")) } } function createRelativePath(level){ var prefix = "../"; var re = ""; for(var x = 0;x < level;x++){ re = re + prefix; } return re; } function sleek(obj,speed){ /*滑动到指定的对象*/ $("html,body").animate({ scrollTop : d(obj).top }, speed); } function tableGetSelected(table){ /*datatable的专用方法,寻找被选中对行*/ var aTrs = table.fnGetNodes(); for (var i=0 ; i<aTrs.length ; i++){ if ($(aTrs[i]).hasClass("row_selected")){ return aTrs[i]; } } return null; } function getForm(string){ var re = {} var objs = $("*[" + string + "]"); $.each(objs,function(k,v){ re[$(v).attr(string)] = $(v).val(); }); return re; } function setForm(string,res){ $.each(res,function(k,v){ $("*[" + string + "=" + k + "]").val(v); }); }
zzblog
web/js/jquery.ez.js
JavaScript
asf20
3,819
<%-- Document : index Created on : 2011-9-27, 11:36:40 Author : EnzoZhong --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script> <script src="js/upload/ajaxfileupload.js"></script> <script> function ajaxFileUpload() { $.ajaxFileUpload({ url : "tool/send", secureuri: false, fileElementId: "file", dataType: "json" }); return false; } </script> <title>JSP Page</title> </head> <body> <input type="file" id="file" name="file" /> <input type="button" value="上传" onclick="ajaxFileUpload();"> </body> </html>
zzblog
web/newjsp.jsp
Java Server Pages
asf20
1,043
div.essay{ overflow: hidden; border-radius: 20px; opacity : 0.8; background-color: black; box-shadow : 18px 18px 38px black; margin-bottom: 68px; } div.essay *{ color: white; } div.body{ padding: 18px; } div.body_l0{ width: 100%; overflow: hidden; } div.body_l0 ul{ float: left; list-style-type: none; } li.mese{ font-size: 19px; margin-left: 20px; } li.giorno{ font-size: 33px; } li.title{ font-size: 28px; font-weight: 900; font-family:黑体; margin-top: -1px; } li.catalogo,li.tag,li.see{ font-size: 12px; } div.body_l0 ul li,div.body_l1{ color: white; }
zzblog
web/css/essay.css
CSS
asf20
696
*{ margin: 0; padding: 0; text-decoration: none; } body{ background-image: url("../../pic/bg.jpg"); } body div{ margin: 8px auto; } header{ width: 960px; height: 100px; margin: 0 auto; background-color: black; border-radius: 0 0 20px 20px; opacity : 0.8; } div.f_l1{ width: 960px; margin: 0 auto; overflow: hidden; } article,nav{ float: left; margin: 5px; overflow: hidden; } article{ width: 777px; } div.l1_right{ width: 160px; }
zzblog
web/css/pageessay.css
CSS
asf20
516
/* Document : crudCityCatalogo Created on : 2012-2-21, 14:54:08 Author : EnzoZhong Description: Purpose of the stylesheet follows. */ *{ margin: 0; padding: 0; font-size : 13px; } #comTab{ border : 0; } input,button,select,textarea{ outline:none } fieldset{ width: 310px; margin: 10px; border : 0; box-shadow: 0 0 8px rgba(0,0,0,0.25); } fieldset.big{ width: 668px; height : 400px; margin: 10px; border : 0; box-shadow: 0 0 8px rgba(0,0,0,0.25); } input{ width: 100%; border : 0; } textarea{ width: 100%; height: 100%; border : 0; } select{ width: 100%; height: 100%; }
zzblog
web/css/crudCityCatalogo.css
CSS
asf20
831
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <style> div.l0_title{ float: right; color: white; font-size: 28px; margin: 8px; } </style> <div class="l0_title" title="1.32">Enzo钟的博客</div>
zzblog
web/WEB-INF/blog/temp/header.jsp
Java Server Pages
asf20
229
<%-- Document : nav Created on : 2011-11-18, 11:24:51 Author : EnzoZhong --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <style> ul.navlist{ list-style-type: none; width: 160px; } ul.navlist li { text-align: center; padding: 3px; margin: 8px; border-radius: 6px; opacity : 0.8; background-color: black; color: white; } ul.navlist li a{ color: white; } </style> <script> $().ready(function(){ $("#navlist").css("position","fixed"); var maxTop = d($(".essay")[0]).top; var isIn; $("#navlist").hover(function(){ isIn = true; }, function(){ isIn= false; }); $(document).mousemove(function(e){ var h = d("#navlist").height; var y = e.pageY - $(window).scrollTop(); setTimeout(function(){ if(!isIn){ if(y - h / 2 < maxTop && $(window).scrollTop() == 0){ y = maxTop + h / 2; } $("#navlist").css("top",y - h / 2); } },123); }); $("#zero").click(function(){ $("html,body").animate({ scrollTop : 0 }, 668); }); }); </script> <ul id="navlist" class="navlist"> <li> </li> <li> <a href="/-_-">所有文章</a> </li> <li> <a href="/2login">图集</a> </li> <li> <a href="/2login">管理</a> </li> <li id="zero"> <a>Top</a> </li> </ul>
zzblog
web/WEB-INF/blog/temp/nav.jsp
Java Server Pages
asf20
1,364
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="../../js/jquery.min.js"></script> <script src="http://enzozhong.googlecode.com/svn/Ez/src/z/h/w/js/jquery/util/jquery.ez.js"></script> <style> @import "../../css/pageessay.css"; @import "../../css/essay.css"; </style> <title>Enzo钟</title> </head> <body> <header> <jsp:include page="temp/header.jsp"/> </header> <div class="f_l1"> <article ps="放文章"> <c:forEach items="${obj}" var="essay"> <div class="essay"> <div class="body"> <div class="body_l0"> <ul class="data"> <li class="anno"> <fmt:formatDate value="${essay.essayDate}" pattern="yyyy年" /> </li> <li class="mese"> <fmt:formatDate value="${essay.essayDate}" pattern="MM月" /> </li> <li class="giorno"> <fmt:formatDate value="${essay.essayDate}" pattern="dd日" /> </li> </ul> <ul class="info"> <li class="title"> <a href="/essay/${essay.essayId}">${essay.essayTitle}</a> </li> <li class="catalogo">目录: <a href="/catalogo/${essay.catalogo.catalogoId}">${essay.catalogo.catalogoName}</a> </li> <li class="tag"> 标签:<c:forEach items="${essay.tagList}" var="tag"> <a href="/tag/${tag.tagId}">${tag.tagName}</a> </c:forEach> </li> <li class="see"> 阅读: ${essay.essaySee} </li> </ul> </div> <div class="body_l1">${essay.essayHtml} <a href="/essay/${essay.essayId}" title="阅读"> ... ... </a> </div> </div> </div> </c:forEach> </article> <nav ps="导航"> <jsp:include page="temp/nav.jsp"/> </nav> </div> </body> </html>
zzblog
web/WEB-INF/blog/essaylist.jsp
Java Server Pages
asf20
2,074
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="../../js/jquery.min.js"></script> <script src="http://enzozhong.googlecode.com/svn/Ez/src/z/h/w/js/jquery/util/jquery.ez.js"></script> <style> @import "../../css/pageessay.css"; @import "../../css/essay.css"; </style> <title>${obj.essayTitle}</title> </head> <body> <header> <jsp:include page="temp/header.jsp"/> </header> <div class="f_l1"> <article ps="放文章"> <div class="essay"> <div class="body"> <div class="body_l0"> <ul class="data"> <li class="anno"> <fmt:formatDate value="${obj.essayDate}" pattern="yyyy年" /> </li> <li class="mese"> <fmt:formatDate value="${obj.essayDate}" pattern="MM月" /> </li> <li class="giorno"> <fmt:formatDate value="${obj.essayDate}" pattern="dd日" /> </li> </ul> <ul class="info"> <li class="title"> <a>${obj.essayTitle}</a> </li> <li class="catalogo">目录: <a href="/catalogo/${obj.catalogo.catalogoId}">${obj.catalogo.catalogoName}</a> </li> <li class="tag"> 标签:<c:forEach items="${obj.tagList}" var="tag"> <a href="/tag/${tag.tagId}">${tag.tagName}</a> </c:forEach> </li> <li class="see"> 阅读: ${obj.essaySee} </li> </ul> </div> <div class="body_l1">${obj.essayHtml} </div> <!-- JiaThis Button BEGIN --> <div id="ckepop" style="float:right;"> <span class="jiathis_txt">分享到:</span> <a class="jiathis_button_tsina">新浪微博</a> <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a> <a class="jiathis_counter_style"></a> </div> <script type="text/javascript" src="http://v2.jiathis.com/code/jia.js" charset="utf-8"></script> <!-- JiaThis Button END --> </div> </div> </article> <nav ps="导航"> <jsp:include page="temp/nav.jsp"/> </nav> </div> </body> </html>
zzblog
web/WEB-INF/blog/essay.jsp
Java Server Pages
asf20
3,874
<%-- Document : cityCr Created on : 2012-2-18, 17:39:02 Author : EnzoZhong --%> <%@ page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%--Jquery加载--%> <script src="${obj.path}js/jquery/jquery.js"></script> <script src="${obj.path}js/jquery/jquery.ui.js"></script> <script src="${obj.path}js/json/jquery.json.js"></script> <script src="${obj.path}js/jquery.ez.js"></script> <%--z-tree加载--%> <script src="${obj.path}js/ztree/jquery.ztree.all.js"></script> <script src="${obj.path}js/ztree/jquery.ztree.core.js"></script> <%--datatable--%> <script src="${obj.path}js/datatables/js/jquery.dataTables.min.js"></script> <%--css加载--%> <style> @import "${obj.path}js/jquery/css/jquery-ui-1.8.17.custom.css"; @import "${obj.path}js/ztree/css/zTreeStyle.css"; @import "${obj.path}js/datatables/css/demo_table_jui.css"; @import "${obj.path}css/crudCityCatalogo.css"; </style> <script> $().ready(function(){ var comTab = $("#comTab").tabs(); var comTable = $("#comTable").append("<tbody>").dataTable({ "bJQueryUI" : true, "sScrollX" : "99%", "bLengthChange" : false,//每行显示记录数 "bPaginate" : false,//分页按钮 "iDisplayLength" : -1, "aoColumns": ${obj.aoColumns} }); var comDialogo = $("#comDialogo").dialog({ modal : true, title : "Please wait..." }).dialog("close"); $("*[fast]").keypress(function(event){ if(event.keyCode == 13){ submit(); } }); tableRefresh(); function tableRefresh(){ $(comDialogo).dialog("open"); //表格更新数据方法 $.ajax({ url : "/back/${obj.type}/readAll", type : "get", dataType : "json", success : function(res) { //为了数据的同步性,把表格现有数据全部清除 comTable.fnClearTable(); $.each(res,function(k,v){ comTable.dataTable().fnAddData(v); }); $("#comTable tbody tr").click( function( e ) { //完成数据初始化后,添加点击变色事件 if ( $(this).hasClass('row_selected') ) { $(this).removeClass('row_selected'); }else { comTable.$('tr.row_selected').removeClass('row_selected'); $(this).addClass('row_selected'); } }); $(comDialogo).dialog("close"); } }); } $("#buttonCreate").button().click(function(){ comTab.tabs("select",1); }); $("#buttonRefresh").button().click(function(){ tableRefresh(); }); $("#buttonUpdate").button().click(function(){ var json = send4Read(); $(comDialogo).dialog("open"); $.ajax({ url : "/back/${obj.type}/readById", type : "post", data : json, dataType : "json", success : function(res) { $(comDialogo).dialog("close"); setForm("name",res); setForm("map",res.translate); comTab.tabs("select",1); } }); }); $("#buttonDelete").button().click(function(){ var json = send4Read(); $(comDialogo).dialog({ modal : true, title : "are u sure to del? " + json, buttons: [{ text: "Del", click: function() { $.ajax({ url : "/back/${obj.type}/delete", type : "post", data : json, dataType : "json", success : function(res) { tableRefresh(); $(comDialogo).dialog("close"); } }); } },{ text: "Cancel", click: function() { $(comDialogo).dialog({ modal : true, title : "Please wait..." }).dialog("close"); } } ] }); }); $("#buttonBack").button().click(function(){ cleanForm(); comTab.tabs("select",0); }); $("#buttonSubmit").button().click(function(){ submit(); }); function submit(){ $(comDialogo).dialog("open"); var json = send4Submit(); /*三目运算符*/ var url = $("input[name=${obj.id}]").val() == "" ? "create" : "update"; url = "/back/${obj.type}/" + url; $.ajax({ url : url, data : json, type : "post", dataType : "json", success : function(res) { cleanForm(); tableRefresh(); comTab.tabs("select",0); $(comDialogo).dialog("close"); } }); } function getSelected(){ try{ var anSelected = tableGetSelected(comTable); var aPos = comTable.fnGetPosition(anSelected); var aData = comTable.fnGetData(comTable.parentNode); }catch(e){ alert("Please choose one."); } return aData[aPos]; } function send4Read(){ var select = getSelected(); return $.toJSON({${obj.type} : {${obj.id} : select[0], tabName : select[1] } }); } function send4Submit(){ return $.toJSON({${obj.type} : getForm("name"), translate : getForm("map") }); } }); function cleanForm(){ $("*[name]").val(""); } </script> <title>${obj.title}</title> </head> <body> <div id="comTab"> <ul> <li> <a href="#datatable">数据列表</a> </li> <li> <a href="#opertion">操作列表</a> </li> </ul> <div id="datatable"> <button id="buttonCreate">添加</button> <button id="buttonRefresh">刷新</button> <button id="buttonUpdate">更新</button> <button id="buttonDelete">删除</button> <table id="comTable"></table> <label>状态 0:显示,1:隐藏:2:待删除</label> </div> <div id="opertion"> <button id="buttonBack">返回</button> <button id="buttonSubmit">提交</button> <fieldset> <legend>序列号</legend> <input name="${obj.id}" disabled="true"/> </fieldset> <fieldset> <legend>目录名</legend> <input name="tabName"/> </fieldset> <c:forEach items="${obj.lanList}" var="lan"> <fieldset> <legend>${lan.code}</legend> <input map="${lan.code}" name="${lan.code}"/> </fieldset> </c:forEach> <fieldset> <legend>状态</legend> <input name="state" type="number"fast/> <label>0:显示,1:隐藏:2:待删除</label> </fieldset> <div id="comDialogo"></div> </div> </div> </body> </html>
zzblog
web/WEB-INF/back/crudTab.jsp
Java Server Pages
asf20
15,267
<%-- Document : index Created on : 2012-2-17, 17:22:56 Author : EnzoZhong --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%--Jquery加载--%> <script src="${obj.path}js/jquery/jquery.js"></script> <script src="${obj.path}js/jquery/jquery.ui.js"></script> <script src="${obj.path}js/json/jquery.json.js"></script> <%--z-tree加载--%> <script src="${obj.path}js/ztree/jquery.ztree.all.js"></script> <script src="${obj.path}js/ztree/jquery.ztree.core.js"></script> <%--datatable--%> <script src="${obj.path}js/datatables/js/jquery.dataTables.min.js"></script> <script src="http://ezkit.googlecode.com/git/src/z/h/w/js/jquery/util/jquery.ez.js"></script> <%--css加载--%> <style> @import "${obj.path}js/jquery/css/jquery-ui-1.8.17.custom.css"; @import "${obj.path}js/ztree/css/zTreeStyle.css"; @import "${obj.path}js/datatables/css/demo_table_jui.css"; *{ margin: 0; padding: 0; } iframe[name]{ width: 100%; height: 100%; border: 0; } div.context { width: 100%; height: 640px; margin: 0 auto; } div.context div.context_right,div.context_left { width: auto; float: left; margin: 10px; box-shadow:0 0 10px rgba(0,0,0,0.25); } div.context_right{ min-width: 200px; } div.context_left{ height: 100%; } #台头{ height: 25px; width: 100%; box-shadow:0 0 10px rgba(0,0,0,0.25); } </style> <script> $().ready(function(){ $(document).mousemove(function(e){ changeDimesione(); }); $(window).resize(function(){ changeDimesione(); }); function changeDimesione(){ var screenWidth = document.body.clientWidth; var divWH = d($(".context_right")); var w = divWH.width; $(".context_left").css("width",screenWidth - w - 40); } var setting = { data: { simpleData: { enable: true } } }; $.ajax({ url : "/back/getNavTree", type : "get", dataType : "json", success : function(res) { $.fn.zTree.init($("#zTree"), setting, res); } }); }); </script> <title>${obj.title}</title> </head> <body> <div id="台头"></div> <div class="context"> <%--右列--%> <div class="context_right"> <ul id="zTree" class="ztree"></ul> </div> <%--左列--%> <div class="context_left"> <iframe name="myFrame" src="../progress.html"></iframe> </div> </div> </body> </html>
zzblog
web/WEB-INF/back/index.jsp
Java Server Pages
asf20
5,122
<%@ page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%--GoogleMapApi用来获取用户地理位置,暂时只支持非IE核心--%> <script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script> <script src="${obj.path}js/jquery/jquery.js"></script> <script src="${obj.path}js/jquery/jquery.ui.js"></script> <%--和后台数据交换用的--%> <script src="${obj.path}js/json/jquery.json.js"></script> <%--自己写的js库--%> <script src="${obj.path}js/jquery.ez.js"></script> <%--css加载--%> <style> @import "${obj.path}js/jquery/css/jquery-ui-1.8.17.custom.css"; *{ font-size : 13px; } fieldset.main{ width: 800px; height: 310px; border: 8px solid #f0f0f0; border-radius: 10px; box-shadow: 30px 30px 40px rgba(0,0,0,0.25), 0 0 10px rgba(0,0,0,0.68); } ul{ list-style-type: none; } legend{ padding: 2px 4px; border: 4px solid #f0f0f0; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.68); } </style> <script> function getGeo(){ var components; if(navigator.geolocation != null){ navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); geocoder = new google.maps.Geocoder(); geocoder.geocode({ "location": pos }, function(results, status) { components = results[0].address_components; $("input[name=country]").val(searchAddress("country",components,"long_name")); $("input[name=city]").val(searchAddress("locality",components,"long_name")); $("input[name=street]").val(searchAddress("route",components,"long_name")); $("input[name=civico]").val(searchAddress("street_number",components,"long_name")); }); }); }else{ alert("请使用非ie核心登陆该页面"); return null; } } function searchAddress(need,components,args){ var len = components.length; for(var x = 0;x < len;x++){ var type = components[x].types; var typeLen = type.length; for(var y = 0;y < typeLen;y++){ if(type[y] == need){ return components[x][args]; } } } return null; } $(document).ready(function(){ getGeo(); setMid("fieldset.main",1,"xy"); $(window).resize(function(){ setMid("fieldset.main",888,"xy"); }); changeCode(); $(document).mousemove(function(e){ var xyw = d($("input[name=account]")); var x = xyw.top; var y = xyw.left; var w = xyw.width; setTimeout(function(){ $("#codeimg").css("top",x).css("left",y + w + 8).css("display","block"); },88); }); //项目发布前需要Del!!!! $("input[name=account]").val("enzo.lvi@gmail.com"); $("input[name=password]").val("nji9mko0"); $("input[name=code]").val("${obj.age}"); $("#buttonLogin").button().click(function(){ login(); }); $("#buttonChangePic").button().click(function(){ changeCode(); }); $("input[name=code]").keypress(function(event){ if(event.keyCode == 13){ login(); } }); function login(){ $("button").attr("disabled",true); $("input").attr("disabled",true); var data = { manager : { account : $("input[name=account]").val(), password : $("input[name=password]").val() }, code : $("input[name=code]").val() }; var json = $.toJSON(data); $.ajax({ url : "/back/login", data : json, type : "post", dataType : "json", success : function(res) { if(res.res){ window.location = res.url; }else{ alert(res.tip); window.location = res.url; } } }); } function changeCode(){ $("#codeimg").css("display","none").css("position" , "absolute").attr("src","../back/code?t=" + new Date()); } $("input[name=code]").focus(function(){ var x = d($("input[name=account]")).top; var y = d($("input[name=account]")).left; var w = d($("input[name=account]")).width; $("#codeimg").css("top",x).css("left",y + w + 8).css("display","block"); }).blur(function(){ $("#codeimg").css("display","none") }); }); </script> <title>${obj.ip}</title> </head> <body> <fieldset class="main"> <legend>后台登陆</legend> <ul> <li>${msg.ciao}</li> <li>${obj.time}</li> <li> <label>账&nbsp;&nbsp;号: <input name="account" type="text"/> </label> </li> <li> <label>密&nbsp;&nbsp;码: <input name="password" type="password"/> </label> </li> <li> <label>验证码: <input name="code" type="text"/> </label> </li> <li> <button id="buttonLogin">登陆</button> <button id="buttonChangePic">换一张</button> </li> </ul> <input name="country"/> <input name="city"/> <input name="street"/> <input name="civico"/> <input name="ip" value="${obj.ip}"/> </fieldset> <img id="codeimg"/> </body> </html>
zzblog
web/WEB-INF/back/login.jsp
Java Server Pages
asf20
10,817
<%-- Document : crudLan Created on : 2012-3-8, 17:13:06 Author : EnzoZhong --%> <%@ page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%--Jquery加载--%> <script src="${obj.path}js/jquery/jquery.js"></script> <script src="${obj.path}js/jquery/jquery.ui.js"></script> <script src="${obj.path}js/json/jquery.json.js"></script> <script src="${obj.path}js/jquery.ez.js"></script> <%--z-tree加载--%> <script src="${obj.path}js/ztree/jquery.ztree.all.js"></script> <script src="${obj.path}js/ztree/jquery.ztree.core.js"></script> <%--datatable--%> <script src="${obj.path}js/datatables/js/jquery.dataTables.min.js"></script> <%--css加载--%> <style> @import "${obj.path}js/jquery/css/jquery-ui-1.8.17.custom.css"; @import "${obj.path}js/ztree/css/zTreeStyle.css"; @import "${obj.path}js/datatables/css/demo_table_jui.css"; @import "${obj.path}css/crudCityCatalogo.css"; </style> <script> $().ready(function(){ var comTab = $("#comTab").tabs(); var comTable = $("#comTable").append("<tbody>").dataTable({ "bJQueryUI" : true, "sScrollX" : "99%", "bLengthChange" : false,//每行显示记录数 "bPaginate" : false,//分页按钮 "iDisplayLength" : -1, "aoColumns": ${obj.aoColumns} }); var comDialogo = $("#comDialogo").dialog({ modal : true, title : "Please wait..." }).dialog("close"); $("*[fast]").keypress(function(event){ if(event.keyCode == 13){ submit(); } }); tableRefresh(); function tableRefresh(){ $(comDialogo).dialog("open"); //表格更新数据方法 $.ajax({ url : "/back/${obj.type}/readAll", type : "get", dataType : "json", success : function(res) { //为了数据的同步性,把表格现有数据全部清除 comTable.fnClearTable(); $.each(res,function(k,v){ comTable.dataTable().fnAddData(v); }); $("#comTable tbody tr").click( function( e ) { //完成数据初始化后,添加点击变色事件 if ( $(this).hasClass('row_selected') ) { $(this).removeClass('row_selected'); }else { comTable.$('tr.row_selected').removeClass('row_selected'); $(this).addClass('row_selected'); } }); $(comDialogo).dialog("close"); } }); } $("#buttonCreate").button().click(function(){ comTab.tabs("select",1); }); $("#buttonRefresh").button().click(function(){ tableRefresh(); }); $("#buttonUpdate").button().click(function(){ var json = send4Read(); $(comDialogo).dialog("open"); $.ajax({ url : "/back/${obj.type}/readById", type : "post", data : json, dataType : "json", success : function(res) { $(comDialogo).dialog("close"); setForm("name",res); comTab.tabs("select",1); } }); }); $("#buttonDelete").button().click(function(){ var json = send4Read(); $(comDialogo).dialog({ modal : true, title : "are u sure to del? " + json, buttons: [{ text: "Del", click: function() { $.ajax({ url : "/back/${obj.type}/delete", type : "post", data : json, dataType : "json", success : function(res) { tableRefresh(); $(comDialogo).dialog("close"); } }); } },{ text: "Cancel", click: function() { $(comDialogo).dialog({ modal : true, title : "Please wait..." }).dialog("close"); } } ] }); }); $("#buttonBack").button().click(function(){ cleanForm(); comTab.tabs("select",0); }); $("#buttonSubmit").button().click(function(){ submit(); }); function submit(){ $(comDialogo).dialog("open"); var json = send4Submit(); /*三目运算符*/ var url = $("input[name=${obj.id}]").val() == "" ? "create" : "update"; url = "/back/${obj.type}/" + url; $.ajax({ url : url, data : json, type : "post", dataType : "json", success : function(res) { cleanForm(); tableRefresh(); comTab.tabs("select",0); $(comDialogo).dialog("close"); } }); } function getSelected(){ try{ var anSelected = tableGetSelected(comTable); var aPos = comTable.fnGetPosition(anSelected); var aData = comTable.fnGetData(comTable.parentNode); }catch(e){ alert("Please choose one."); } return aData[aPos]; } function send4Read(){ var select = getSelected(); return $.toJSON({${obj.type} : {${obj.id} : select[0], lanName : select[1] } }); } function send4Submit(){ return $.toJSON({${obj.type} : getForm("name") }); } }); function cleanForm(){ $("*[name]").val(""); } </script> <title>${obj.title}</title> </head> <body> <div id="comTab"> <ul> <li> <a href="#datatable">数据列表</a> </li> <li> <a href="#opertion">操作列表</a> </li> </ul> <div id="datatable"> <button id="buttonCreate">添加</button> <button id="buttonRefresh">刷新</button> <button id="buttonUpdate">更新</button> <button id="buttonDelete">删除</button> <table id="comTable"></table> <label>状态 0:显示,1:隐藏:2:待删除</label> </div> <div id="opertion"> <button id="buttonBack">返回</button> <button id="buttonSubmit">提交</button> <fieldset> <legend>序列号</legend> <input name="${obj.id}" disabled="true"/> </fieldset> <fieldset> <legend>语言名</legend> <input name="lanName"/> </fieldset> <fieldset> <legend>语言代号</legend> <select name="code"> <c:forEach items="${obj.locale}" var="locale"> <option value="${locale}">${locale}</option> </c:forEach> </select> </fieldset> <fieldset> <legend>状态</legend> <input name="state" type="number"fast/> <label>0:显示,1:隐藏:2:待删除</label> </fieldset> <div id="comDialogo"></div> </div> </div> </body> </html>
zzblog
web/WEB-INF/back/crudLan.jsp
Java Server Pages
asf20
15,254
<%-- Document : cityCr Created on : 2012-2-18, 17:39:02 Author : EnzoZhong --%> <%@ page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%--Jquery加载--%> <script src="${obj.path}js/jquery/jquery.js"></script> <script src="${obj.path}js/jquery/jquery.ui.js"></script> <script src="${obj.path}js/json/jquery.json.js"></script> <script src="${obj.path}js/jquery.ez.js"></script> <%--z-tree加载--%> <script src="${obj.path}js/ztree/jquery.ztree.all.js"></script> <script src="${obj.path}js/ztree/jquery.ztree.core.js"></script> <%--datatable--%> <script src="${obj.path}js/datatables/js/jquery.dataTables.min.js"></script> <%--css加载--%> <style> @import "${obj.path}js/jquery/css/jquery-ui-1.8.17.custom.css"; @import "${obj.path}js/ztree/css/zTreeStyle.css"; @import "${obj.path}js/datatables/css/demo_table_jui.css"; @import "${obj.path}css/crudCityCatalogo.css"; </style> <script> $().ready(function(){ var comTab = $("#comTab").tabs(); var comTable = $("#comTable").append("<tbody>").dataTable({ "bJQueryUI" : true, "sScrollX" : "99%", "bLengthChange" : false,//每行显示记录数 "bPaginate" : false,//分页按钮 "iDisplayLength" : -1, "aoColumns": ${obj.aoColumns} }); var comDialogo = $("#comDialogo").dialog({ modal : true, title : "Please wait..." }).dialog("close"); $("*[fast]").keypress(function(event){ if(event.keyCode == 13){ submit(); } }); tableRefresh(); function tableRefresh(){ $(comDialogo).dialog("open"); //表格更新数据方法 $.ajax({ url : "/back/${obj.type}/readAll", type : "get", dataType : "json", success : function(res) { //为了数据的同步性,把表格现有数据全部清除 comTable.fnClearTable(); $.each(res,function(k,v){ comTable.dataTable().fnAddData(v); }); $("#comTable tbody tr").click( function( e ) { //完成数据初始化后,添加点击变色事件 if ( $(this).hasClass('row_selected') ) { $(this).removeClass('row_selected'); }else { comTable.$('tr.row_selected').removeClass('row_selected'); $(this).addClass('row_selected'); } }); $(comDialogo).dialog("close"); } }); } $("#buttonCreate").button().click(function(){ comTab.tabs("select",1); }); $("#buttonRefresh").button().click(function(){ tableRefresh(); }); $("#buttonUpdate").button().click(function(){ var json = send4Read(); $(comDialogo).dialog("open"); $.ajax({ url : "/back/${obj.type}/readById", type : "post", data : json, dataType : "json", success : function(res) { $(comDialogo).dialog("close"); setForm("name",res); setForm("map",res.translate); comTab.tabs("select",1); } }); }); $("#buttonDelete").button().click(function(){ var json = send4Read(); $(comDialogo).dialog({ modal : true, title : "are u sure to del? " + json, buttons: [{ text: "Del", click: function() { $.ajax({ url : "/back/${obj.type}/delete", type : "post", data : json, dataType : "json", success : function(res) { tableRefresh(); $(comDialogo).dialog("close"); } }); } },{ text: "Cancel", click: function() { $(comDialogo).dialog({ modal : true, title : "Please wait..." }).dialog("close"); } } ] }); }); $("#buttonBack").button().click(function(){ cleanForm(); comTab.tabs("select",0); }); $("#buttonSubmit").button().click(function(){ submit(); }); function submit(){ $(comDialogo).dialog("open"); var json = send4Submit(); /*三目运算符*/ var url = $("input[name=${obj.id}]").val() == "" ? "create" : "update"; url = "/back/${obj.type}/" + url; $.ajax({ url : url, data : json, type : "post", dataType : "json", success : function(res) { cleanForm(); tableRefresh(); comTab.tabs("select",0); $(comDialogo).dialog("close"); } }); } function getSelected(){ try{ var anSelected = tableGetSelected(comTable); var aPos = comTable.fnGetPosition(anSelected); var aData = comTable.fnGetData(comTable.parentNode); }catch(e){ alert("Please choose one."); } return aData[aPos]; } function send4Read(){ var select = getSelected(); return $.toJSON({${obj.type} : {${obj.id} : select[0], tagName : select[1] } }); } function send4Submit(){ return $.toJSON({${obj.type} : getForm("name"), translate : getForm("map") }); } }); function cleanForm(){ $("*[name]").val(""); } </script> <title>${obj.title}</title> </head> <body> <div id="comTab"> <ul> <li> <a href="#datatable">数据列表</a> </li> <li> <a href="#opertion">操作列表</a> </li> </ul> <div id="datatable"> <button id="buttonCreate">添加</button> <button id="buttonRefresh">刷新</button> <button id="buttonUpdate">更新</button> <button id="buttonDelete">删除</button> <table id="comTable"></table> <label>状态 0:显示,1:隐藏:2:待删除</label> </div> <div id="opertion"> <button id="buttonBack">返回</button> <button id="buttonSubmit">提交</button> <fieldset> <legend>序列号</legend> <input name="${obj.id}" disabled="true"/> </fieldset> <fieldset> <legend>目录名</legend> <input name="tagName"/> </fieldset> <c:forEach items="${obj.lanList}" var="lan"> <fieldset> <legend>${lan.code}</legend> <input map="${lan.code}" name="${lan.code}"/> </fieldset> </c:forEach> <fieldset> <legend>状态</legend> <input name="state" type="number"fast/> <label>0:显示,1:隐藏:2:待删除</label> </fieldset> <div id="comDialogo"></div> </div> </div> </body> </html>
zzblog
web/WEB-INF/back/crudTag.jsp
Java Server Pages
asf20
15,267
<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body> <h3>Notices for files:</h3><ul> <li>YouTubeAndroidPlayerApi.jar</li> </ul> <pre>Copyright 2012 Google, Inc. All rights reserved. YouTube Android Player API </pre> <h3>Notices for files:</h3><ul> <li>volley.jar</li> </ul> <pre>Copyright (C) 2011 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </pre> <h3>Notices for files:</h3><ul> <li>svg-android.jar</li> </ul> <pre>SVG Android Copyright 2011 Larva Labs LLC and Google, Inc. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). --- Apache Batik Copyright 1999-2007 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). This software contains code from the World Wide Web Consortium (W3C) for the Document Object Model API (DOM API) and SVG Document Type Definition (DTD). This software contains code from the International Organisation for Standardization for the definition of character entities used in the software's documentation. This product includes images from the Tango Desktop Project (http://tango.freedesktop.org/). This product includes images from the Pasodoble Icon Theme (http://www.jesusda.com/projects/pasodoble). </pre> <h3>Notices for files:</h3><ul> <li>google-api-client-1.14.1-beta.jar</li> </ul> <pre>Copyright (c) 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </pre> <h3>Notices for files:</h3><ul> <li>basic-http-client.jar</li> </ul> <pre>Copyright 2012 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </pre> <h3>Notices for files:</h3><ul> <li>AccountActivity.java</li> <li>AccountUtils.java</li> <li>Announcement.java</li> <li>AnnouncementsFetcher.java</li> <li>AnnouncementsResponse.java</li> <li>BaseActivity.java</li> <li>BeamUtils.java</li> <li>BezelImageView.java</li> <li>BitmapCache.java</li> <li>BlocksHandler.java</li> <li>ButtonBar.java</li> <li>CheckableFrameLayout.java</li> <li>Config.java</li> <li>Day.java</li> <li>EditMyScheduleResponse.java</li> <li>Error.java</li> <li>ErrorResponse.java</li> <li>Errors.java</li> <li>Event.java</li> <li>EventSlots.java</li> <li>FeedbackHandler.java</li> <li>FractionalTouchDelegate.java</li> <li>GCMIntentService.java</li> <li>GCMRedirectedBroadcastReceiver.java</li> <li>GenericResponse.java</li> <li>HandlerException.java</li> <li>HelpUtils.java</li> <li>HomeActivity.java</li> <li>ImageLoader.java</li> <li>JSONHandler.java</li> <li>Lists.java</li> <li>Location.java</li> <li>LogUtils.java</li> <li>MapActivity.java</li> <li>MapFragment.java</li> <li>MapMultiPaneActivity.java</li> <li>MapPropertyHandler.java</li> <li>Maps.java</li> <li>MultiSelectionUtil.java</li> <li>MyScheduleFragment.java</li> <li>MyScheduleHandler.java</li> <li>MyScheduleItem.java</li> <li>MyScheduleResponse.java</li> <li>MyScheduleWidgetProvider.java</li> <li>MyScheduleWidgetService.java</li> <li>NetUtils.java</li> <li>ParserUtils.java</li> <li>ReflectionUtils.java</li> <li>Room.java</li> <li>Rooms.java</li> <li>RoomsHandler.java</li> <li>SandboxCompany.java</li> <li>ScheduleContract.java</li> <li>ScheduleDatabase.java</li> <li>ScheduleProvider.java</li> <li>ScheduleUpdaterService.java</li> <li>SearchActivity.java</li> <li>SearchSuggestHandler.java</li> <li>SearchSuggestions.java</li> <li>SelectionBuilder.java</li> <li>ServerUtilities.java</li> <li>SessionAlarmReceiver.java</li> <li>SessionAlarmService.java</li> <li>SessionDetailActivity.java</li> <li>SessionDetailFragment.java</li> <li>SessionFeedbackActivity.java</li> <li>SessionFeedbackFragment.java</li> <li>SessionLivestreamActivity.java</li> <li>SessionsActivity.java</li> <li>SessionsFragment.java</li> <li>SessionsHandler.java</li> <li>SessionsHelper.java</li> <li>SessionsResponse.java</li> <li>SessionsResult.java</li> <li>SessionsSandboxMultiPaneActivity.java</li> <li>SimpleSectionedListAdapter.java</li> <li>SimpleSinglePaneActivity.java</li> <li>Speaker.java</li> <li>SpeakersHandler.java</li> <li>SyncAdapter.java</li> <li>SyncHelper.java</li> <li>SyncService.java</li> <li>TagStreamActivity.java</li> <li>TagStreamFragment.java</li> <li>TimeSlot.java</li> <li>TimeUtils.java</li> <li>Track.java</li> <li>TrackDetailActivity.java</li> <li>TrackInfoHelperFragment.java</li> <li>Tracks.java</li> <li>TracksAdapter.java</li> <li>TracksDropdownFragment.java</li> <li>TracksFragment.java</li> <li>TracksHandler.java</li> <li>TriggerSyncReceiver.java</li> <li>UIUtils.java</li> <li>SandboxDetailActivity.java</li> <li>SandboxDetailFragment.java</li> <li>SandboxFragment.java</li> <li>WhatsOnFragment.java</li> <li>WiFiUtils.java</li> <li>gcm</li> </ul> <pre>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ </pre> <h3>Notices for files:</h3><ul> <li>libGoogleAnalyticsV2.jar</li> </ul> <pre>Google Analytics Android SDK version 2.0 beta 4 Copyright 2009 - 2013 Google, Inc. All rights reserved.</pre> <h3>Notices for files:</h3><ul> <li>google-api-client-android-1.14.1-beta</li> <li>google-api-services-plus-v1-rev67-1.14.2-beta.jar</li> <li>google-http-client-1.14.1-beta.jar</li> <li>google-http-client-android-1.14.1-beta.jar</li> <li>google-http-client-gson-1.14.1-beta.jar</li> <li>google-oauth-client-1.14.1-beta.jar</li> </ul> <pre>Copyright (c) 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </pre> <h3>Notices for files:</h3><ul> <li>AnnouncementCommand.java</li> <li>AnnouncementsActivity.java</li> <li>AnnouncementsFragment.java</li> <li>CheckableLinearLayout.java</li> <li>DashClockExtension.java</li> <li>EllipsizedTextView.java</li> <li>GCMCommand.java</li> <li>MapInfoWindowAdapter.java</li> <li>NfcBadgeActivity.java</li> <li>ObservableScrollView.java</li> <li>PlayServicesUtils.java</li> <li>PlusStreamRowViewBinder.java</li> <li>PrefUtils.java</li> <li>SVGTileProvider.java</li> <li>SessionTracksHandler.java</li> <li>SettingsActivity.java</li> <li>SyncCommand.java</li> <li>SyncUserCommand.java</li> <li>TaskStackBuilderProxyActivity.java</li> <li>TestCommand.java</li> <li>TrackInfo.java</li> <li>dashclock-api-r1.1</li> </ul> <pre>Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</pre> <h3>Notices for files:</h3><ul> <li>UnusedStub.java</li> </ul> <pre>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */</pre> <h3>Notices for files:</h3><ul> <li>gson-2.1.jar</li> </ul> <pre>Copyright 2008-2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</pre> <h3>Notices for files:</h3><ul> <li>guava-11.0.1.jar</li> </ul> <pre>Copyright (C) 2010 The Guava Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </pre> <h3>Notices for files:</h3><ul> <li>abc_action_mode_bar.xml</li> <li>config.xml</li> </ul> <pre>/* ** Copyright 2012, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */</pre> <h3>Notices for files:</h3><ul> <li>protobuf-java-2.2.0.jar</li> </ul> <pre>Protocol Buffer Java API BSD License: Copyright (c) 2007, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </pre> <h3>Notices for files:</h3><ul> <li>jsr305-1.3.9.jar</li> </ul> <pre>Copyright (c) 2007-2009, JSR305 expert group All rights reserved. http://www.opensource.org/licenses/bsd-license.php Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the JSR305 expert group nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </pre> </body></html>
zzc88915-iosched
android/src/main/assets/licenses.html
HTML
asf20
15,010
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Room; import com.google.android.apps.iosched.io.model.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class RoomsHandler extends JSONHandler { private static final String TAG = makeLogTag(RoomsHandler.class); public RoomsHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); Rooms roomsJson = new Gson().fromJson(json, Rooms.class); int noOfRooms = roomsJson.rooms.length; for (int i = 0; i < noOfRooms; i++) { parseRoom(roomsJson.rooms[i], batch); } return batch; } private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Rooms.CONTENT_URI)); builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id); builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name); builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor); batch.add(builder.build()); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/RoomsHandler.java
Java
asf20
2,283
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class SearchSuggestions { public String[] words; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/SearchSuggestions.java
Java
asf20
710
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Tracks { Track[] track; public Track[] getTrack() { return track; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/Tracks.java
Java
asf20
752
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class TimeSlot { public String start; public String end; public String title; public String type; public String meta; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/TimeSlot.java
Java
asf20
795
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class EventSlots { public Day[] day; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/EventSlots.java
Java
asf20
700
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Room { public String id; public String name; public String floor; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/Room.java
Java
asf20
741
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class Track { public String id; public String name; public String color; @SerializedName("abstract") public String _abstract; public int level; public int order_in_level; public int meta; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/Track.java
Java
asf20
929
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Day { public String date; public TimeSlot[] slot; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/Day.java
Java
asf20
721
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Rooms { public Room[] rooms; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/model/Rooms.java
Java
asf20
696
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; import java.util.Map; public class MapResponse { public MapConfig config; public Map<String, Marker[]> markers; public Map<String, Tile> tiles; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/map/model/MapResponse.java
Java
asf20
812
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; public class Tile { public String filename; public String url; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/map/model/Tile.java
Java
asf20
726
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; public class MapConfig { public boolean enableMyLocation; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/map/model/MapConfig.java
Java
asf20
716
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.map.model; public class Marker { public String id; public String type; public float lat; public float lng; public String title; public String track; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/map/model/Marker.java
Java
asf20
817
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.SearchSuggestions; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; public class SearchSuggestHandler extends JSONHandler { public SearchSuggestHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class); if (suggestions.words != null) { // Clear out suggestions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .build()); // Rebuild suggestions for (String word : suggestions.words) { batch.add(ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word) .build()); } } return batch; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/SearchSuggestHandler.java
Java
asf20
2,219
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import java.io.IOException; /** * General {@link IOException} that indicates a problem occurred while parsing or applying a {@link * JSONHandler}. */ public class HandlerException extends IOException { public HandlerException() { super(); } public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
Java
asf20
1,320
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase; import com.google.android.apps.iosched.util.*; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.services.googledevelopers.Googledevelopers; import com.google.api.services.googledevelopers.model.SessionResponse; import com.google.api.services.googledevelopers.model.SessionsResponse; import com.google.api.services.googledevelopers.model.TrackResponse; import com.google.api.services.googledevelopers.model.TracksResponse; import java.io.IOException; import java.util.*; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import static com.google.android.apps.iosched.util.LogUtils.*; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; public class SessionsHandler { private static final String TAG = makeLogTag(SessionsHandler.class); private static final String BASE_SESSION_URL = "https://developers.google.com/events/io/sessions/"; private static final String EVENT_TYPE_KEYNOTE = Sessions.SESSION_TYPE_KEYNOTE; private static final String EVENT_TYPE_OFFICE_HOURS = Sessions.SESSION_TYPE_OFFICE_HOURS; private static final String EVENT_TYPE_CODELAB = Sessions.SESSION_TYPE_CODELAB; private static final String EVENT_TYPE_SANDBOX = Sessions.SESSION_TYPE_SANDBOX; private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1; private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2; private Context mContext; public SessionsHandler(Context context) { mContext = context; } public ArrayList<ContentProviderOperation> fetchAndParse( Googledevelopers conferenceAPI) throws IOException { // Set up the HTTP transport and JSON factory SessionsResponse sessions; SessionsResponse starredSessions = null; TracksResponse tracks; try { sessions = conferenceAPI.events().sessions().list(Config.EVENT_ID).setLimit(9999L).execute(); tracks = conferenceAPI.events().tracks().list(Config.EVENT_ID).execute(); if (sessions == null || sessions.getSessions() == null) { throw new HandlerException("Sessions list was null."); } if (tracks == null || tracks.getTracks() == null) { throw new HandlerException("trackDetails list was null."); } } catch (HandlerException e) { LOGE(TAG, "Fatal: error fetching sessions/tracks", e); return Lists.newArrayList(); } final boolean profileAvailableBefore = PrefUtils.isDevsiteProfileAvailable(mContext); boolean profileAvailableNow = false; try { starredSessions = conferenceAPI.users().events().sessions().list(Config.EVENT_ID).execute(); // If this succeeded, the user has a DevSite profile PrefUtils.markDevSiteProfileAvailable(mContext, true); profileAvailableNow = true; } catch (GoogleJsonResponseException e) { // Hack: If the user doesn't have a developers.google.com profile, the Conference API // will respond with HTTP 401 and include something like // "Provided user does not have a developers.google.com profile" in the message. if (401 == e.getStatusCode() && e.getDetails() != null && e.getDetails().getMessage() != null && e.getDetails().getMessage().contains("developers.google.com")) { LOGE(TAG, "User does not have a developers.google.com profile. Not syncing remote " + "personalized schedule."); starredSessions = null; // Record that the user's profile is offline. If this changes later, we'll re-upload any local // starred sessions. PrefUtils.markDevSiteProfileAvailable(mContext, false); } else { LOGW(TAG, "Auth token invalid, requesting refresh", e); AccountUtils.refreshAuthToken(mContext); } } if (profileAvailableNow && !profileAvailableBefore) { LOGI(TAG, "developers.google.com mode change: DEVSITE_PROFILE_AVAILABLE=false -> true"); // User's DevSite profile has come into existence. Re-upload tracks. ContentResolver cr = mContext.getContentResolver(); String[] projection = new String[] {ScheduleContract.Sessions.SESSION_ID, Sessions.SESSION_TITLE}; Cursor c = cr.query(ScheduleContract.BASE_CONTENT_URI.buildUpon(). appendPath("sessions").appendPath("starred").build(), projection, null, null, null); if (c != null) { c.moveToFirst(); while (!c.isAfterLast()) { String id = c.getString(0); String title = c.getString(1); LOGI(TAG, "Adding session: (" + id + ") " + title); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(id); SessionsHelper.uploadStarredSession(mContext, sessionUri, true); c.moveToNext(); } } // Hack: Use local starred sessions for now, to give the new sessions time to take effect // TODO(trevorjohns): Upload starred sessions should be synchronous to avoid this hack starredSessions = null; } return buildContentProviderOperations(sessions, starredSessions, tracks); } public ArrayList<ContentProviderOperation> parseString(String sessionsJson, String tracksJson) { JsonFactory jsonFactory = new AndroidJsonFactory(); try { SessionsResponse sessions = jsonFactory.fromString(sessionsJson, SessionsResponse.class); TracksResponse tracks = jsonFactory.fromString(tracksJson, TracksResponse.class); return buildContentProviderOperations(sessions, null, tracks); } catch (IOException e) { LOGE(TAG, "Error reading speakers from packaged data", e); return Lists.newArrayList(); } } private ArrayList<ContentProviderOperation> buildContentProviderOperations( SessionsResponse sessions, SessionsResponse starredSessions, TracksResponse tracks) { // If there was no starred sessions response (e.g. there was an auth issue, // or this is a local sync), keep all the locally starred sessions. boolean retainLocallyStarredSessions = (starredSessions == null); final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Build lookup table for starredSessions mappings HashSet<String> starredSessionsMap = new HashSet<String>(); if (starredSessions != null) { List<SessionResponse> starredSessionList = starredSessions.getSessions(); if (starredSessionList != null) { for (SessionResponse session : starredSessionList) { String sessionId = session.getId(); starredSessionsMap.add(sessionId); } } } // Build lookup table for track mappings // Assumes that sessions can only have one track. Not guarenteed by the Conference API, // but is being enforced by conference organizer policy. HashMap<String, TrackResponse> trackMap = new HashMap<String, TrackResponse>(); if (tracks != null) { for (TrackResponse track : tracks.getTracks()) { List<String> sessionIds = track.getSessions(); if (sessionIds != null) { for (String sessionId : sessionIds) { trackMap.put(sessionId, track); } } } } if (sessions != null) { List<SessionResponse> sessionList = sessions.getSessions(); int numSessions = sessionList.size(); if (numSessions > 0) { LOGI(TAG, "Updating sessions data"); Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created session block IDs Set<String> blockIds = new HashSet<String>(); // Maintain a map of insert operations for sandbox-only blocks HashMap<String, ContentProviderOperation> sandboxBlocks = new HashMap<String, ContentProviderOperation>(); for (SessionResponse session : sessionList) { int flags = 0; String sessionId = session.getId(); if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(sessionId) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title String sessionTitle = session.getTitle(); String sessionSubtype = session.getSubtype(); if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) { sessionTitle = mContext.getString( R.string.codelab_title_template, sessionTitle); } // Whether or not it's in the schedule boolean inSchedule = starredSessionsMap.contains(sessionId); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) { // Keynotes are always in your schedule. inSchedule = true; } // Clean up session abstract String sessionAbstract = session.getDescription(); if (sessionAbstract != null) { sessionAbstract = sessionAbstract.replace('\r', '\n'); } // Hashtags TrackResponse track = trackMap.get(sessionId); String hashtag = null; if (track != null) { hashtag = ParserUtils.sanitizeId(track.getTitle()); } boolean isLivestream = false; try { isLivestream = session.getIsLivestream(); } catch (NullPointerException ignored) { } String youtubeUrl = session.getYoutubeUrl(); // Get block id long sessionStartTime = session.getStartTimestamp().longValue() * 1000; long sessionEndTime = session.getEndTimestamp().longValue() * 1000; String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId) && !EVENT_TYPE_SANDBOX.equals(sessionSubtype)) { // New non-sandbox block if (sandboxBlocks.containsKey(blockId)) { sandboxBlocks.remove(blockId); } String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) { blockType = ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) { blockType = ScheduleContract.Blocks.BLOCK_TYPE_CODELAB; blockTitle = mContext.getString( R.string.schedule_block_title_code_labs); } else if (EVENT_TYPE_OFFICE_HOURS.equals(sessionSubtype)) { blockType = ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS; blockTitle = mContext.getString( R.string.schedule_block_title_office_hours); } else { blockType = ScheduleContract.Blocks.BLOCK_TYPE_SESSION; blockTitle = mContext.getString( R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } else if (!sandboxBlocks.containsKey(blockId) && !blockIds.contains(blockId) && EVENT_TYPE_SANDBOX.equals(sessionSubtype)) { // New sandbox-only block, add insert operation to map String blockType = ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX; String blockTitle = mContext.getString( R.string.schedule_block_title_sandbox); sandboxBlocks.put(blockId, ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); } // Insert session info final ContentProviderOperation.Builder builder; if (EVENT_TYPE_SANDBOX.equals(sessionSubtype)) { // Sandbox companies go in the special sandbox table builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(ScheduleContract.Sandbox.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(ScheduleContract.Sandbox.COMPANY_ID, sessionId) .withValue(ScheduleContract.Sandbox.COMPANY_NAME, sessionTitle) .withValue(ScheduleContract.Sandbox.COMPANY_DESC, sessionAbstract) .withValue(ScheduleContract.Sandbox.COMPANY_URL, makeSessionUrl(sessionId)) .withValue(ScheduleContract.Sandbox.COMPANY_LOGO_URL, session.getIconUrl()) .withValue(ScheduleContract.Sandbox.ROOM_ID, sanitizeId(session.getLocation())) .withValue(ScheduleContract.Sandbox.TRACK_ID, (track != null ? track.getId() : null)) .withValue(ScheduleContract.Sandbox.BLOCK_ID, blockId); batch.add(builder.build()); } else { // All other fields go in the normal sessions table builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, sessionSubtype) .withValue(Sessions.SESSION_LEVEL, null) // Not available .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, sessionAbstract) .withValue(Sessions.SESSION_HASHTAGS, hashtag) .withValue(Sessions.SESSION_TAGS, null) // Not available .withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId)) .withValue(Sessions.SESSION_LIVESTREAM_URL, isLivestream ? youtubeUrl : null) .withValue(Sessions.SESSION_MODERATOR_URL, null) // Not available .withValue(Sessions.SESSION_REQUIREMENTS, null) // Not available .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_YOUTUBE_URL, isLivestream ? null : youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, null) // Not available .withValue(Sessions.SESSION_NOTES_URL, null) // Not available .withValue(Sessions.ROOM_ID, sanitizeId(session.getLocation())) .withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); } // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); List<String> presenterIds = session.getPresenterIds(); if (presenterIds != null) { for (String presenterId : presenterIds) { batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, presenterId).build()); } } // Add track mapping if (track != null) { String trackId = track.getId(); if (trackId != null) { final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId) .withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, trackId).build()); } } // Codelabs: Add mapping to codelab table if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) { final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId) .withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, "CODE_LABS").build()); } } // Insert sandbox-only blocks batch.addAll(sandboxBlocks.values()); } } return batch; } private String makeSessionUrl(String sessionId) { if (TextUtils.isEmpty(sessionId)) { return null; } return BASE_SESSION_URL + sessionId; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/SessionsHandler.java
Java
asf20
23,279
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import android.database.Cursor; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.api.services.googledevelopers.Googledevelopers; import com.google.api.services.googledevelopers.model.FeedbackResponse; import com.google.api.services.googledevelopers.model.ModifyFeedbackRequest; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.*; public class FeedbackHandler { private static final String TAG = makeLogTag(FeedbackHandler.class); private Context mContext; public FeedbackHandler(Context context) { mContext = context; } public ArrayList<ContentProviderOperation> uploadNew(Googledevelopers conferenceApi) { // Collect rows of feedback Cursor feedbackCursor = mContext.getContentResolver().query( ScheduleContract.Feedback.CONTENT_URI, null, null, null, null); int sessionIdIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_ID); int ratingIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_RATING); int relIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_RELEVANCE); int contentIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_CONTENT); int speakerIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_SPEAKER); int willUseIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_WILLUSE); int commentsIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.COMMENTS); final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); while (feedbackCursor.moveToNext()) { String sessionId = feedbackCursor.getString(sessionIdIndex); LOGI(TAG, "Uploading feedback for: " + sessionId); int rating = feedbackCursor.getInt(ratingIndex); int answerRelevance = feedbackCursor.getInt(relIndex); int answerContent = feedbackCursor.getInt(contentIndex); int answerSpeaker = feedbackCursor.getInt(speakerIndex); int answerWillUseRaw = feedbackCursor.getInt(willUseIndex); boolean answerWillUse = (answerWillUseRaw != 0); String comments = feedbackCursor.getString(commentsIndex); ModifyFeedbackRequest feedbackRequest = new ModifyFeedbackRequest(); feedbackRequest.setOverallScore(rating); feedbackRequest.setRelevancyScore(answerRelevance); feedbackRequest.setContentScore(answerContent); feedbackRequest.setSpeakerScore(answerSpeaker); // In this case, -1 means the user didn't answer the question. if (answerWillUseRaw != -1) { feedbackRequest.setWillUse(answerWillUse); } // Only post something If the comments field isn't empty if (comments != null && comments.length() > 0) { feedbackRequest.setAdditionalFeedback(comments); } feedbackRequest.setSessionId(sessionId); feedbackRequest.setEventId(Config.EVENT_ID); try { Googledevelopers.Events.Sessions.Feedback feedback = conferenceApi.events().sessions() .feedback(Config.EVENT_ID, sessionId, feedbackRequest); FeedbackResponse response = feedback.execute(); if (response != null) { LOGI(TAG, "Successfully sent feedback for: " + sessionId + ", comment: " + comments); } else { LOGE(TAG, "Sending logs failed"); } } catch (IOException ioe) { LOGE(TAG, "Sending logs failed and caused IOE", ioe); return batch; } } feedbackCursor.close(); // Clear out feedback forms we've just uploaded batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Feedback.CONTENT_URI)) .build()); return batch; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/FeedbackHandler.java
Java
asf20
5,030
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.json.JsonFactory; import com.google.api.services.googledevelopers.Googledevelopers; import com.google.api.services.googledevelopers.model.PresenterResponse; import com.google.api.services.googledevelopers.model.PresentersResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import static com.google.android.apps.iosched.util.LogUtils.*; public class SpeakersHandler { private static final String TAG = makeLogTag(SpeakersHandler.class); public SpeakersHandler(Context context) {} public ArrayList<ContentProviderOperation> fetchAndParse( Googledevelopers conferenceAPI) throws IOException { PresentersResponse presenters; try { presenters = conferenceAPI.events().presenters().list(Config.EVENT_ID).execute(); if (presenters == null || presenters.getPresenters() == null) { throw new HandlerException("Speakers list was null."); } } catch (HandlerException e) { LOGE(TAG, "Error fetching speakers", e); return Lists.newArrayList(); } return buildContentProviderOperations(presenters); } public ArrayList<ContentProviderOperation> parseString(String json) { JsonFactory jsonFactory = new AndroidJsonFactory(); try { PresentersResponse presenters = jsonFactory.fromString(json, PresentersResponse.class); return buildContentProviderOperations(presenters); } catch (IOException e) { LOGE(TAG, "Error reading speakers from packaged data", e); return Lists.newArrayList(); } } private ArrayList<ContentProviderOperation> buildContentProviderOperations( PresentersResponse presenters) { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); if (presenters != null) { List<PresenterResponse> presenterList = presenters.getPresenters(); int numSpeakers = presenterList.size(); if (numSpeakers > 0) { LOGI(TAG, "Updating presenters data"); // Clear out existing speakers batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( Speakers.CONTENT_URI)) .build()); // Insert latest speaker data for (PresenterResponse presenter : presenterList) { // Hack: Fix speaker URL so that it's not being resized // Depends on thumbnail URL being exactly in the format we want String thumbnail = presenter.getThumbnailUrl(); if (thumbnail != null) { thumbnail = thumbnail.replace("?sz=50", "?sz=100"); } batch.add(ContentProviderOperation.newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Speakers.SPEAKER_ID, presenter.getId()) .withValue(Speakers.SPEAKER_NAME, presenter.getName()) .withValue(Speakers.SPEAKER_ABSTRACT, presenter.getBio()) .withValue(Speakers.SPEAKER_IMAGE_URL, thumbnail) .withValue(Speakers.SPEAKER_URL, presenter.getPlusoneUrl()) .build()); } } } return batch; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/SpeakersHandler.java
Java
asf20
4,815
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.Context; import android.content.OperationApplicationException; import android.os.RemoteException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; public abstract class JSONHandler { protected static Context mContext; public JSONHandler(Context context) { mContext = context; } public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException; public final void parseAndApply(String json) throws IOException { try { final ContentResolver resolver = mContext.getContentResolver(); ArrayList<ContentProviderOperation> batch = parse(json); resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } } public static String parseResource(Context context, int resource) throws IOException { InputStream is = context.getResources().openRawResource(resource); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/JSONHandler.java
Java
asf20
2,541
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Day; import com.google.android.apps.iosched.io.model.EventSlots; import com.google.android.apps.iosched.io.model.TimeSlot; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class BlocksHandler extends JSONHandler { private static final String TAG = makeLogTag(BlocksHandler.class); public BlocksHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); try { Gson gson = new Gson(); EventSlots eventSlots = gson.fromJson(json, EventSlots.class); int numDays = eventSlots.day.length; //2011-05-10T07:00:00.000-07:00 for (int i = 0; i < numDays; i++) { Day day = eventSlots.day[i]; String date = day.date; TimeSlot[] timeSlots = day.slot; for (TimeSlot timeSlot : timeSlots) { parseSlot(date, timeSlot, batch); } } } catch (Throwable e) { LOGE(TAG, e.toString()); } return batch; } private static void parseSlot(String date, TimeSlot slot, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI)); //LOGD(TAG, "Inside parseSlot:" + date + ", " + slot); String start = slot.start; String end = slot.end; String type = Blocks.BLOCK_TYPE_GENERIC; if (slot.type != null) { type = slot.type; } String title = "N_D"; if (slot.title != null) { title = slot.title; } String startTime = date + "T" + start + ":00.000-07:00"; String endTime = date + "T" + end + ":00.000-07:00"; LOGV(TAG, "startTime:" + startTime); long startTimeL = ParserUtils.parseTime(startTime); long endTimeL = ParserUtils.parseTime(endTime); final String blockId = Blocks.generateBlockId(startTimeL, endTimeL); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "title:" + title); LOGV(TAG, "start:" + startTimeL); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTimeL); builder.withValue(Blocks.BLOCK_END, endTimeL); builder.withValue(Blocks.BLOCK_TYPE, type); builder.withValue(Blocks.BLOCK_META, slot.meta); batch.add(builder.build()); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/BlocksHandler.java
Java
asf20
3,957
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import android.graphics.Color; import com.google.android.apps.iosched.io.model.Track; import com.google.android.apps.iosched.io.model.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class TracksHandler extends JSONHandler { private static final String TAG = makeLogTag(TracksHandler.class); public TracksHandler(Context context) { super(context); } @Override public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Tracks.CONTENT_URI)).build()); Tracks tracksJson = new Gson().fromJson(json, Tracks.class); int noOfTracks = tracksJson.getTrack().length; for (int i = 0; i < noOfTracks; i++) { parseTrack(tracksJson.getTrack()[i], batch); } return batch; } private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Tracks.CONTENT_URI)); builder.withValue(ScheduleContract.Tracks.TRACK_ID, track.id); builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name); builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color)); builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract); builder.withValue(ScheduleContract.Tracks.TRACK_LEVEL, track.level); builder.withValue(ScheduleContract.Tracks.TRACK_ORDER_IN_LEVEL, track.order_in_level); builder.withValue(ScheduleContract.Tracks.TRACK_META, track.meta); builder.withValue(ScheduleContract.Tracks.TRACK_HASHTAG, ParserUtils.sanitizeId(track.name)); batch.add(builder.build()); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/TracksHandler.java
Java
asf20
3,091
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import android.content.ContentProviderOperation; import android.content.Context; import android.util.Log; import com.google.android.apps.iosched.io.map.model.MapConfig; import com.google.android.apps.iosched.io.map.model.MapResponse; import com.google.android.apps.iosched.io.map.model.Marker; import com.google.android.apps.iosched.io.map.model.Tile; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.MapUtils; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapPropertyHandler extends JSONHandler { private static final String TAG = makeLogTag(MapPropertyHandler.class); private Collection<Tile> mTiles; public MapPropertyHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); MapResponse mapJson = new Gson().fromJson(json, MapResponse.class); parseTileOverlays(mapJson.tiles, batch, mContext); parseMarkers(mapJson.markers, batch); parseConfig(mapJson.config, mContext); mTiles = mapJson.tiles.values(); return batch; } private void parseConfig(MapConfig config, Context mContext) { boolean enableMyLocation = config.enableMyLocation; MapUtils.setMyLocationEnabled(mContext,enableMyLocation); } private void parseMarkers(Map<String, Marker[]> markers, ArrayList<ContentProviderOperation> batch) { for (Entry<String, Marker[]> entry : markers.entrySet()) { String floor = entry.getKey(); // add each Marker for (Marker marker : entry.getValue()) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(ScheduleContract.MapMarkers.CONTENT_URI)); builder.withValue(ScheduleContract.MapMarkers.MARKER_ID, marker.id); builder.withValue(ScheduleContract.MapMarkers.MARKER_FLOOR, floor); builder.withValue(ScheduleContract.MapMarkers.MARKER_LABEL, marker.title); builder.withValue(ScheduleContract.MapMarkers.MARKER_LATITUDE, marker.lat); builder.withValue(ScheduleContract.MapMarkers.MARKER_LONGITUDE, marker.lng); builder.withValue(ScheduleContract.MapMarkers.MARKER_TYPE, marker.type); builder.withValue(ScheduleContract.MapMarkers.MARKER_TRACK, marker.track); batch.add(builder.build()); } } } private void parseTileOverlays(Map<String, Tile> tiles, ArrayList<ContentProviderOperation> batch, Context context) { for (Entry<String, Tile> entry : tiles.entrySet()) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(ScheduleContract.MapTiles.CONTENT_URI)); String floor = entry.getKey(); Tile value = entry.getValue(); builder.withValue( ScheduleContract.MapTiles.TILE_FLOOR, floor); builder.withValue( ScheduleContract.MapTiles.TILE_FILE, value.filename); builder.withValue( ScheduleContract.MapTiles.TILE_URL, value.url); Log.d(TAG, "adding overlay: " + floor + ", " + value.filename); /* * Setup the tile overlay file. Copy it from the app assets or * download it if it does not exist locally. This is done here to * ensure that the data stored in the content provider always points * to valid tile files. */ batch.add(builder.build()); } } public Collection<Tile> getTiles(){ return mTiles; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/MapPropertyHandler.java
Java
asf20
5,033
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.NetUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import android.content.ContentProviderOperation; import android.content.Context; import android.text.TextUtils; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class AnnouncementsFetcher { private static final String TAG = makeLogTag(AnnouncementsFetcher.class); private Context mContext; public AnnouncementsFetcher(Context context) { mContext = context; } public ArrayList<ContentProviderOperation> fetchAndParse() throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Set up the HTTP transport and JSON factory HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new AndroidJsonFactory(); // Set up the main Google+ class Plus plus = new Plus.Builder(httpTransport, jsonFactory, null) .setApplicationName(NetUtils.getUserAgent(mContext)) .setGoogleClientRequestInitializer( new CommonGoogleClientRequestInitializer(Config.API_KEY)) .build(); ActivityFeed activities; try { activities = plus.activities().list(Config.ANNOUNCEMENTS_PLUS_ID, "public") .setMaxResults(100l) .execute(); if (activities == null || activities.getItems() == null) { throw new IOException("Activities list was null."); } } catch (IOException e) { LOGE(TAG, "Error fetching announcements", e); return batch; } LOGI(TAG, "Updating announcements data"); // Clear out existing announcements batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Announcements.CONTENT_URI)) .build()); StringBuilder sb = new StringBuilder(); for (Activity activity : activities.getItems()) { // Filter out anything not including the conference hashtag. sb.setLength(0); appendIfNotEmpty(sb, activity.getAnnotation()); if (activity.getObject() != null) { appendIfNotEmpty(sb, activity.getObject().getContent()); } if (!sb.toString().contains(UIUtils.CONFERENCE_HASHTAG)) { continue; } // Insert announcement info batch.add(ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Announcements.ANNOUNCEMENT_ID, activity.getId()) .withValue(Announcements.ANNOUNCEMENT_DATE, activity.getUpdated().getValue()) .withValue(Announcements.ANNOUNCEMENT_TITLE, activity.getTitle()) .withValue(Announcements.ANNOUNCEMENT_ACTIVITY_JSON, activity.toPrettyString()) .withValue(Announcements.ANNOUNCEMENT_URL, activity.getUrl()) .build()); } return batch; } private static void appendIfNotEmpty(StringBuilder sb, String s) { if (!TextUtils.isEmpty(s)) { sb.append(s); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/io/AnnouncementsFetcher.java
Java
asf20
5,103
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import android.accounts.Account; import android.content.ContentResolver; import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.FeedbackColumns; import com.google.android.apps.iosched.provider.ScheduleContract.MapMarkerColumns; import com.google.android.apps.iosched.provider.ScheduleContract.MapTileColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sandbox; import android.app.SearchManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.util.AccountUtils; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Helper for managing {@link SQLiteDatabase} that stores data for * {@link ScheduleProvider}. */ public class ScheduleDatabase extends SQLiteOpenHelper { private static final String TAG = makeLogTag(ScheduleDatabase.class); private static final String DATABASE_NAME = "schedule.db"; // NOTE: carefully update onUpgrade() when bumping database versions to make // sure user data is saved. private static final int VER_2013_LAUNCH = 104; // 1.0 private static final int VER_2013_RM2 = 105; // 1.1 private static final int DATABASE_VERSION = VER_2013_RM2; private final Context mContext; interface Tables { String BLOCKS = "blocks"; String TRACKS = "tracks"; String ROOMS = "rooms"; String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String SESSIONS_SPEAKERS = "sessions_speakers"; String SESSIONS_TRACKS = "sessions_tracks"; String SANDBOX = "sandbox"; String ANNOUNCEMENTS = "announcements"; String MAPMARKERS = "mapmarkers"; String MAPTILES = "mapoverlays"; String FEEDBACK = "feedback"; String SESSIONS_SEARCH = "sessions_search"; String SEARCH_SUGGEST = "search_suggest"; String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_JOIN_ROOMS = "sessions " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS = "sandbox " + "LEFT OUTER JOIN tracks ON sandbox.track_id=tracks.track_id " + "LEFT OUTER JOIN blocks ON sandbox.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sandbox.room_id=rooms.room_id"; String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers " + "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id"; String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers " + "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks " + "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id"; String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks " + "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search " + "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions " + "LEFT OUTER JOIN sessions_tracks ON " + "sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id"; String BLOCKS_JOIN_SESSIONS = "blocks " + "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id"; String MAPMARKERS_JOIN_TRACKS = "mapmarkers " + "LEFT OUTER JOIN tracks ON tracks.track_id=mapmarkers.track_id "; } private interface Triggers { // Deletes from session_tracks and sessions_speakers when corresponding sessions // are deleted. String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete"; String SESSIONS_SPEAKERS_DELETE = "sessions_speakers_delete"; String SESSIONS_FEEDBACK_DELETE = "sessions_feedback_delete"; } public interface SessionsSpeakers { String SESSION_ID = "session_id"; String SPEAKER_ID = "speaker_id"; } public interface SessionsTracks { String SESSION_ID = "session_id"; String TRACK_ID = "track_id"; } interface SessionsSearchColumns { String SESSION_ID = "session_id"; String BODY = "body"; } /** Fully-qualified field names. */ private interface Qualified { String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID + "," + SessionsSearchColumns.BODY + ")"; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS+ "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS+ "." + SessionsSpeakers.SPEAKER_ID; String SPEAKERS_SPEAKER_ID = Tables.SPEAKERS + "." + Speakers.SPEAKER_ID; String FEEDBACK_SESSION_ID = Tables.FEEDBACK + "." + FeedbackColumns.SESSION_ID; } /** {@code REFERENCES} clauses. */ private interface References { String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")"; String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")"; String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")"; String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")"; String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")"; } public ScheduleDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.BLOCKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + BlocksColumns.BLOCK_ID + " TEXT NOT NULL," + BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL," + BlocksColumns.BLOCK_START + " INTEGER NOT NULL," + BlocksColumns.BLOCK_END + " INTEGER NOT NULL," + BlocksColumns.BLOCK_TYPE + " TEXT," + BlocksColumns.BLOCK_META + " TEXT," + "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TracksColumns.TRACK_ID + " TEXT NOT NULL," + TracksColumns.TRACK_NAME + " TEXT," + TracksColumns.TRACK_COLOR + " INTEGER," + TracksColumns.TRACK_LEVEL + " INTEGER," + TracksColumns.TRACK_ORDER_IN_LEVEL + " INTEGER," + TracksColumns.TRACK_META + " INTEGER NOT NULL DEFAULT 0," + TracksColumns.TRACK_ABSTRACT + " TEXT," + TracksColumns.TRACK_HASHTAG + " TEXT," + "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ROOMS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + RoomsColumns.ROOM_ID + " TEXT NOT NULL," + RoomsColumns.ROOM_NAME + " TEXT," + RoomsColumns.ROOM_FLOOR + " TEXT," + "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SessionsColumns.SESSION_ID + " TEXT NOT NULL," + Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + "," + SessionsColumns.SESSION_TYPE + " TEXT," + SessionsColumns.SESSION_LEVEL + " TEXT," + SessionsColumns.SESSION_TITLE + " TEXT," + SessionsColumns.SESSION_ABSTRACT + " TEXT," + SessionsColumns.SESSION_REQUIREMENTS + " TEXT," + SessionsColumns.SESSION_TAGS + " TEXT," + SessionsColumns.SESSION_HASHTAGS + " TEXT," + SessionsColumns.SESSION_URL + " TEXT," + SessionsColumns.SESSION_YOUTUBE_URL + " TEXT," + SessionsColumns.SESSION_MODERATOR_URL + " TEXT," + SessionsColumns.SESSION_PDF_URL + " TEXT," + SessionsColumns.SESSION_NOTES_URL + " TEXT," + SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0," + SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER," + SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT," + "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL," + SpeakersColumns.SPEAKER_NAME + " TEXT," + SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT," + SpeakersColumns.SPEAKER_COMPANY + " TEXT," + SpeakersColumns.SPEAKER_ABSTRACT + " TEXT," + SpeakersColumns.SPEAKER_URL + " TEXT," + "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + "," + "UNIQUE (" + SessionsSpeakers.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID + ")"); db.execSQL("CREATE TABLE " + Tables.SANDBOX + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + ScheduleContract.SandboxColumns.COMPANY_ID + " TEXT NOT NULL," + Sandbox.TRACK_ID + " TEXT " + References.TRACK_ID + "," + Sandbox.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sandbox.ROOM_ID + " TEXT " + References.ROOM_ID + "," + ScheduleContract.SandboxColumns.COMPANY_NAME + " TEXT," + ScheduleContract.SandboxColumns.COMPANY_DESC + " TEXT," + ScheduleContract.SandboxColumns.COMPANY_URL + " TEXT," + ScheduleContract.SandboxColumns.COMPANY_LOGO_URL + " TEXT," + "UNIQUE (" + ScheduleContract.SandboxColumns.COMPANY_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL," + AnnouncementsColumns.ANNOUNCEMENT_ACTIVITY_JSON + " BLOB," + AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)"); db.execSQL("CREATE TABLE " + Tables.MAPTILES + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + MapTileColumns.TILE_FLOOR+ " INTEGER NOT NULL," + MapTileColumns.TILE_FILE+ " TEXT NOT NULL," + MapTileColumns.TILE_URL+ " TEXT NOT NULL," + "UNIQUE (" + MapTileColumns.TILE_FLOOR+ ") ON CONFLICT REPLACE)"); doMigration2013RM2(db); // Full-text search index. Update using updateSessionSearchIndex method. // Use the porter tokenizer for simple stemming, so that "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSearchColumns.BODY + " TEXT NOT NULL," + SessionsSearchColumns.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // Search suggestions db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)"); // Session deletion triggers db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " " + " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SPEAKERS_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SPEAKERS + " " + " WHERE " + Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); } private void doMigration2013RM2(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.FEEDBACK + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + Sessions.SESSION_ID + " TEXT " + References.SESSION_ID + "," + FeedbackColumns.SESSION_RATING + " INTEGER NOT NULL," + FeedbackColumns.ANSWER_RELEVANCE + " INTEGER NOT NULL," + FeedbackColumns.ANSWER_CONTENT + " INTEGER NOT NULL," + FeedbackColumns.ANSWER_SPEAKER + " INTEGER NOT NULL," + FeedbackColumns.ANSWER_WILLUSE + " INTEGER NOT NULL," + FeedbackColumns.COMMENTS + " TEXT)"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_FEEDBACK_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.FEEDBACK + " " + " WHERE " + Qualified.FEEDBACK_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TABLE " + Tables.MAPMARKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + MapMarkerColumns.MARKER_ID+ " TEXT NOT NULL," + MapMarkerColumns.MARKER_TYPE+ " TEXT NOT NULL," + MapMarkerColumns.MARKER_LATITUDE+ " DOUBLE NOT NULL," + MapMarkerColumns.MARKER_LONGITUDE+ " DOUBLE NOT NULL," + MapMarkerColumns.MARKER_LABEL+ " TEXT," + MapMarkerColumns.MARKER_FLOOR+ " INTEGER NOT NULL," + MapMarkerColumns.MARKER_TRACK+ " TEXT," + "UNIQUE (" + MapMarkerColumns.MARKER_ID + ") ON CONFLICT REPLACE)"); } /** * Updates the session search index. This should be done sparingly, as the queries are rather * complex. */ static void updateSessionSearchIndex(SQLiteDatabase db) { db.execSQL("DELETE FROM " + Tables.SESSIONS_SEARCH); db.execSQL("INSERT INTO " + Qualified.SESSIONS_SEARCH + " SELECT s." + Sessions.SESSION_ID + ",(" // Full text body + Sessions.SESSION_TITLE + "||'; '||" + Sessions.SESSION_ABSTRACT + "||'; '||" + "IFNULL(" + Sessions.SESSION_TAGS + ",'')||'; '||" + "IFNULL(GROUP_CONCAT(t." + Speakers.SPEAKER_NAME + ",' '),'')||'; '||" + "'')" + " FROM " + Tables.SESSIONS + " s " + " LEFT OUTER JOIN" // Subquery resulting in session_id, speaker_id, speaker_name + "(SELECT " + Sessions.SESSION_ID + "," + Qualified.SPEAKERS_SPEAKER_ID + "," + Speakers.SPEAKER_NAME + " FROM " + Tables.SESSIONS_SPEAKERS + " INNER JOIN " + Tables.SPEAKERS + " ON " + Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=" + Qualified.SPEAKERS_SPEAKER_ID + ") t" // Grand finale + " ON s." + Sessions.SESSION_ID + "=t." + Sessions.SESSION_ID + " GROUP BY s." + Sessions.SESSION_ID); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // Cancel any sync currently in progress Account account = AccountUtils.getChosenAccount(mContext); if (account != null) { LOGI(TAG, "Cancelling any pending syncs for for account"); ContentResolver.cancelSync(account, ScheduleContract.CONTENT_AUTHORITY); } // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { // Note: Data from prior years not preserved. case VER_2013_LAUNCH: LOGI(TAG, "Performing migration for DB version " + version); // Reset BLOCKS table db.execSQL("DELETE FROM " + Tables.BLOCKS); // Reset MapMarkers table db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPMARKERS); // Apply new schema changes doMigration2013RM2(db); case VER_2013_RM2: version = VER_2013_RM2; LOGI(TAG, "DB at version " + version); // Current version, no further action necessary } LOGD(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { LOGW(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SANDBOX); db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS); db.execSQL("DROP TABLE IF EXISTS " + Tables.FEEDBACK); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SPEAKERS_DELETE); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_FEEDBACK_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH); db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST); db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPMARKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPTILES); onCreate(db); } if (account != null) { LOGI(TAG, "DB upgrade complete. Requesting resync."); SyncHelper.requestManualSync(account); } } public static void deleteDatabase(Context context) { context.deleteDatabase(DATABASE_NAME); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/provider/ScheduleDatabase.java
Java
asf20
22,932
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.appwidget.ScheduleWidgetProvider; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Feedback; import com.google.android.apps.iosched.provider.ScheduleContract.MapMarkers; import com.google.android.apps.iosched.provider.ScheduleContract.MapTiles; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Sandbox; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import android.text.TextUtils; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various * {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = makeLogTag(ScheduleProvider.class); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int BLOCKS_ID_SESSIONS_STARRED = 104; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_SANDBOX = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_WITH_TRACK = 402; private static final int SESSIONS_SEARCH = 403; private static final int SESSIONS_AT = 404; private static final int SESSIONS_ID = 405; private static final int SESSIONS_ID_SPEAKERS = 406; private static final int SESSIONS_ID_TRACKS = 407; private static final int SESSIONS_ID_WITH_TRACK = 408; private static final int SESSIONS_ROOM_AFTER = 410; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int SANDBOX = 600; private static final int SANDBOX_SEARCH = 603; private static final int SANDBOX_ID = 604; private static final int ANNOUNCEMENTS = 700; private static final int ANNOUNCEMENTS_ID = 701; private static final int SEARCH_SUGGEST = 800; private static final int SEARCH_INDEX = 801; private static final int MAPMARKERS = 900; private static final int MAPMARKERS_FLOOR = 901; private static final int MAPMARKERS_ID = 902; private static final int MAPTILES = 1000; private static final int MAPTILES_FLOOR = 1001; private static final int FEEDBACK_ALL = 1002; private static final int FEEDBACK_FOR_SESSION = 1003; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/sandbox", TRACKS_ID_SANDBOX); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/room/*/after/*", SESSIONS_ROOM_AFTER); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "sandbox", SANDBOX); matcher.addURI(authority, "sandbox/search/*", SANDBOX_SEARCH); matcher.addURI(authority, "sandbox/*", SANDBOX_ID); matcher.addURI(authority, "announcements", ANNOUNCEMENTS); matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); matcher.addURI(authority, "search_index", SEARCH_INDEX); // 'update' only matcher.addURI(authority, "mapmarkers", MAPMARKERS); matcher.addURI(authority, "mapmarkers/floor/*", MAPMARKERS_FLOOR); matcher.addURI(authority, "mapmarkers/*", MAPMARKERS_ID); matcher.addURI(authority, "maptiles", MAPTILES); matcher.addURI(authority, "maptiles/*", MAPTILES_FLOOR); matcher.addURI(authority, "feedback/*", FEEDBACK_FOR_SESSION); matcher.addURI(authority, "feedback*", FEEDBACK_ALL); matcher.addURI(authority, "feedback", FEEDBACK_ALL); return matcher; } @Override public boolean onCreate() { mOpenHelper = new ScheduleDatabase(getContext()); return true; } private void deleteDatabase() { // TODO: wait for content provider operations to finish, then tear down mOpenHelper.close(); Context context = getContext(); ScheduleDatabase.deleteDatabase(context); mOpenHelper = new ScheduleDatabase(getContext()); } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case BLOCKS_ID_SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_SANDBOX: return Sandbox.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_WITH_TRACK: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SESSIONS_ID_WITH_TRACK: return Sessions.CONTENT_TYPE; case SESSIONS_ROOM_AFTER: return Sessions.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SANDBOX: return Sandbox.CONTENT_TYPE; case SANDBOX_SEARCH: return ScheduleContract.Sandbox.CONTENT_TYPE; case SANDBOX_ID: return ScheduleContract.Sandbox.CONTENT_ITEM_TYPE; case ANNOUNCEMENTS: return Announcements.CONTENT_TYPE; case ANNOUNCEMENTS_ID: return Announcements.CONTENT_ITEM_TYPE; case MAPMARKERS: return MapMarkers.CONTENT_TYPE; case MAPMARKERS_FLOOR: return MapMarkers.CONTENT_TYPE; case MAPMARKERS_ID: return MapMarkers.CONTENT_ITEM_TYPE; case MAPTILES: return MapTiles.CONTENT_TYPE; case MAPTILES_FLOOR: return MapTiles.CONTENT_ITEM_TYPE; case FEEDBACK_FOR_SESSION: return Feedback.CONTENT_ITEM_TYPE; case FEEDBACK_ALL: return Feedback.CONTENT_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); String uriFilter = uri.getQueryParameter(Sessions.QUERY_PARAMETER_FILTER); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); // If a special filter was specified, try to apply it if (!TextUtils.isEmpty(uriFilter)) { if (Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY.equals(uriFilter)) { builder.where(Sessions.SESSION_TYPE + " NOT IN ('" + Sessions.SESSION_TYPE_OFFICE_HOURS + "','" + Sessions.SESSION_TYPE_KEYNOTE + "')"); } else if (Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY.equals(uriFilter)) { builder.where(Sessions.SESSION_TYPE + " = ?", Sessions.SESSION_TYPE_OFFICE_HOURS); } } return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); notifyChange(uri, syncToNetwork); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); notifyChange(uri, syncToNetwork); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); notifyChange(uri, syncToNetwork); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); notifyChange(uri, syncToNetwork); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); notifyChange(uri, syncToNetwork); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); notifyChange(uri, syncToNetwork); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); notifyChange(uri, syncToNetwork); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case SANDBOX: { db.insertOrThrow(Tables.SANDBOX, null, values); notifyChange(uri, syncToNetwork); return Sandbox.buildCompanyUri(values.getAsString(Sandbox.COMPANY_ID)); } case ANNOUNCEMENTS: { db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values); notifyChange(uri, syncToNetwork); return Announcements.buildAnnouncementUri(values .getAsString(Announcements.ANNOUNCEMENT_ID)); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); notifyChange(uri, syncToNetwork); return SearchSuggest.CONTENT_URI; } case MAPMARKERS: { db.insertOrThrow(Tables.MAPMARKERS, null, values); notifyChange(uri, syncToNetwork); return MapMarkers.buildMarkerUri(values.getAsString(MapMarkers.MARKER_ID)); } case MAPTILES: { db.insertOrThrow(Tables.MAPTILES, null, values); notifyChange(uri, syncToNetwork); return MapTiles.buildFloorUri(values.getAsString(MapTiles.TILE_FLOOR)); } case FEEDBACK_FOR_SESSION: { db.insertOrThrow(Tables.FEEDBACK, null, values); notifyChange(uri, syncToNetwork); return Feedback.buildFeedbackUri(values.getAsString(Feedback.SESSION_ID)); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); if (match == SEARCH_INDEX) { // update the search index ScheduleDatabase.updateSessionSearchIndex(db); return 1; } final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).update(db, values); boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri); notifyChange(uri, syncToNetwork); return retVal; } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { LOGV(TAG, "delete(uri=" + uri + ")"); if (uri == ScheduleContract.BASE_CONTENT_URI) { // Handle whole database deletes (e.g. when signing out) deleteDatabase(); notifyChange(uri, false); return 1; } final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).delete(db); notifyChange(uri, !ScheduleContract.hasCallerIsSyncAdapterParameter(uri)); return retVal; } private void notifyChange(Uri uri, boolean syncToNetwork) { Context context = getContext(); context.getContentResolver().notifyChange(uri, null, syncToNetwork); // Widgets can't register content observers so we refresh widgets separately. context.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(context, false)); } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SANDBOX: { return builder.table(Tables.SANDBOX); } case SANDBOX_ID: { final String companyId = ScheduleContract.Sandbox.getCompanyId(uri); return builder.table(Tables.SANDBOX) .where(Sandbox.COMPANY_ID + "=?", companyId); } case ANNOUNCEMENTS: { return builder.table(Tables.ANNOUNCEMENTS); } case ANNOUNCEMENTS_ID: { final String announcementId = Announcements.getAnnouncementId(uri); return builder.table(Tables.ANNOUNCEMENTS) .where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId); } case MAPMARKERS: { return builder.table(Tables.MAPMARKERS); } case MAPMARKERS_FLOOR: { final String floor = MapMarkers.getMarkerFloor(uri); return builder.table(Tables.MAPMARKERS) .where(MapMarkers.MARKER_FLOOR+ "=?", floor); } case MAPMARKERS_ID: { final String markerId = MapMarkers.getMarkerId(uri); return builder.table(Tables.MAPMARKERS) .where(MapMarkers.MARKER_ID+ "=?", markerId); } case MAPTILES: { return builder.table(Tables.MAPTILES); } case MAPTILES_FLOOR: { final String floor = MapTiles.getFloorId(uri); return builder.table(Tables.MAPTILES) .where(MapTiles.TILE_FLOOR+ "=?", floor); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } case FEEDBACK_FOR_SESSION: { final String session_id = Feedback.getSessionId(uri); return builder.table(Tables.FEEDBACK) .where(Feedback.SESSION_ID + "=?", session_id); } case FEEDBACK_ALL: { return builder.table(Tables.FEEDBACK); } default: { throw new UnsupportedOperationException("Unknown uri for " + match + ": " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder .table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.NUM_LIVESTREAMED_SESSIONS, Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS) .map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID) .map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE) .map(Blocks.STARRED_SESSION_HASHTAGS, Subquery.BLOCK_STARRED_SESSION_HASHTAGS) .map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL) .map(Blocks.STARRED_SESSION_LIVESTREAM_URL, Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL) .map(Blocks.STARRED_SESSION_ROOM_NAME, Subquery.BLOCK_STARRED_SESSION_ROOM_NAME) .map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.NUM_LIVESTREAMED_SESSIONS, Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.NUM_LIVESTREAMED_SESSIONS, Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.NUM_LIVESTREAMED_SESSIONS, Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS_STARRED: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.NUM_LIVESTREAMED_SESSIONS, Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId) .where(Qualified.SESSIONS_STARRED + "=1"); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.OFFICE_HOURS_COUNT, Subquery.TRACK_OFFICE_HOURS_COUNT) .map(Tracks.SANDBOX_COUNT, Subquery.TRACK_SANDBOX_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_SANDBOX: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS) .mapToTable(ScheduleContract.Sandbox._ID, Tables.SANDBOX) .mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX) .mapToTable(ScheduleContract.Sandbox.BLOCK_ID, Tables.BLOCKS) .mapToTable(Sandbox.ROOM_ID, Tables.ROOMS) .where(Qualified.SANDBOX_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.SESSION_STARRED + "=1"); } case SESSIONS_WITH_TRACK: { return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_NAME, Tables.TRACKS) .mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS); } case SESSIONS_ID_WITH_TRACK: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_NAME, Tables.TRACKS) .mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SESSIONS_ROOM_AFTER: { final String room = Sessions.getRoom(uri); final String time = Sessions.getAfter(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID+ "=?", room) .where("("+Sessions.BLOCK_START + "<= ? AND "+Sessions.BLOCK_END+">= ?) OR ("+Sessions.BLOCK_START+" >= ?)", time,time,time); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case SANDBOX: { return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS) .mapToTable(Sandbox._ID, Tables.SANDBOX) .mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX) .mapToTable(Sandbox.BLOCK_ID, Tables.SANDBOX) .mapToTable(Sandbox.ROOM_ID, Tables.SANDBOX); } case SANDBOX_ID: { final String companyId = ScheduleContract.Sandbox.getCompanyId(uri); return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS) .mapToTable(ScheduleContract.Sandbox._ID, Tables.SANDBOX) .mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX) .mapToTable(Sandbox.BLOCK_ID, Tables.SANDBOX) .mapToTable(Sandbox.ROOM_ID, Tables.SANDBOX) .where(Sandbox.COMPANY_ID + "=?", companyId); } case ANNOUNCEMENTS: { return builder.table(Tables.ANNOUNCEMENTS); } case ANNOUNCEMENTS_ID: { final String announcementId = Announcements.getAnnouncementId(uri); return builder.table(Tables.ANNOUNCEMENTS) .where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId); } case MAPMARKERS: { return builder.table(Tables.MAPMARKERS); } case MAPMARKERS_FLOOR: { final String floor = MapMarkers.getMarkerFloor(uri); return builder.table(Tables.MAPMARKERS) .where(MapMarkers.MARKER_FLOOR+ "=?", floor); } case MAPMARKERS_ID: { final String roomId = MapMarkers.getMarkerId(uri); return builder.table(Tables.MAPMARKERS) .where(MapMarkers.MARKER_ID+ "=?", roomId); } case MAPTILES: { return builder.table(Tables.MAPTILES); } case MAPTILES_FLOOR: { final String floor = MapTiles.getFloorId(uri); return builder.table(Tables.MAPTILES) .where(MapTiles.TILE_FLOOR+ "=?", floor); } case FEEDBACK_FOR_SESSION: { final String sessionId = Feedback.getSessionId(uri); return builder.table(Tables.FEEDBACK) .where(Feedback.SESSION_ID + "=?", sessionId); } case FEEDBACK_ALL: { return builder.table(Tables.FEEDBACK); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)"; String BLOCK_NUM_LIVESTREAMED_SESSIONS = "(SELECT COUNT(1) FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND IFNULL(" + Qualified.SESSIONS_LIVESTREAM_URL + ",'')!='')"; String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT " + Qualified.SESSIONS_LIVESTREAM_URL + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM " + Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM " + Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " INNER JOIN " + Tables.SESSIONS + " ON " + Qualified.SESSIONS_SESSION_ID + "=" + Qualified.SESSIONS_TRACKS_SESSION_ID + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + " AND " + Qualified.SESSIONS_SESSION_TYPE + " != \"" + Sessions.SESSION_TYPE_OFFICE_HOURS + "\")"; String TRACK_OFFICE_HOURS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " INNER JOIN " + Tables.SESSIONS + " ON " + Qualified.SESSIONS_SESSION_ID + "=" + Qualified.SESSIONS_TRACKS_SESSION_ID + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + " AND " + Qualified.SESSIONS_SESSION_TYPE + " = \"" + Sessions.SESSION_TYPE_OFFICE_HOURS + "\")"; String TRACK_SANDBOX_COUNT = "(SELECT COUNT(" + Qualified.SANDBOX_COMPANY_ID + ") FROM " + Tables.SANDBOX + " WHERE " + Qualified.SANDBOX_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_SESSION_TYPE = Tables.SESSIONS+ "." + Sessions.SESSION_TYPE; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String SANDBOX_COMPANY_ID = Tables.SANDBOX + "." + Sandbox.COMPANY_ID; String SANDBOX_TRACK_ID = Tables.SANDBOX + "." + Sandbox.TRACK_ID; String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED; String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE; String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS; String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL; String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL; String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME; String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/provider/ScheduleProvider.java
Java
asf20
48,391
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.util.ParserUtils; import android.app.SearchManager; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.text.TextUtils; import android.text.format.DateUtils; import java.util.List; /** * Contract class for interacting with {@link ScheduleProvider}. Unless * otherwise noted, all time-based fields are milliseconds since epoch and can * be compared against {@link System#currentTimeMillis()}. * <p> * The backing {@link android.content.ContentProvider} assumes that {@link Uri} * are generated using stronger {@link String} identifiers, instead of * {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during * sync. */ public class ScheduleContract { /** * Special value for {@link SyncColumns#UPDATED} indicating that an entry * has never been updated, or doesn't exist yet. */ public static final long UPDATED_NEVER = -2; /** * Special value for {@link SyncColumns#UPDATED} indicating that the last * update time is unknown, usually when inserted from a local file source. */ public static final long UPDATED_UNKNOWN = -1; public interface SyncColumns { /** Last time this entry was updated or synchronized. */ String UPDATED = "updated"; } interface BlocksColumns { /** Unique string identifying this block of time. */ String BLOCK_ID = "block_id"; /** Title describing this block of time. */ String BLOCK_TITLE = "block_title"; /** Time when this block starts. */ String BLOCK_START = "block_start"; /** Time when this block ends. */ String BLOCK_END = "block_end"; /** Type describing this block. */ String BLOCK_TYPE = "block_type"; /** Extra string metadata for the block. */ String BLOCK_META = "block_meta"; } interface TracksColumns { /** Unique string identifying this track. */ String TRACK_ID = "track_id"; /** Name describing this track. */ String TRACK_NAME = "track_name"; /** Color used to identify this track, in {@link Color#argb} format. */ String TRACK_COLOR = "track_color"; /** The level (1 being primary, 2 being secondary) of the track. */ String TRACK_LEVEL = "track_level"; /** The sort order of the track within the level. */ String TRACK_ORDER_IN_LEVEL = "track_order_in_level"; /** Type of meta-track this is, or 0 if not meta. */ String TRACK_META = "track_is_meta"; /** Type of track. */ String TRACK_ABSTRACT = "track_abstract"; /** Hashtag for track. */ String TRACK_HASHTAG = "track_hashtag"; } interface RoomsColumns { /** Unique string identifying this room. */ String ROOM_ID = "room_id"; /** Name describing this room. */ String ROOM_NAME = "room_name"; /** Building floor this room exists on. */ String ROOM_FLOOR = "room_floor"; } interface SessionsColumns { /** Unique string identifying this session. */ String SESSION_ID = "session_id"; /** The type of session (session, keynote, codelab, etc). */ String SESSION_TYPE = "session_type"; /** Difficulty level of the session. */ String SESSION_LEVEL = "session_level"; /** Title describing this track. */ String SESSION_TITLE = "session_title"; /** Body of text explaining this session in detail. */ String SESSION_ABSTRACT = "session_abstract"; /** Requirements that attendees should meet. */ String SESSION_REQUIREMENTS = "session_requirements"; /** Kewords/tags for this session. */ String SESSION_TAGS = "session_keywords"; /** Hashtag for this session. */ String SESSION_HASHTAGS = "session_hashtag"; /** Full URL to session online. */ String SESSION_URL = "session_url"; /** Full URL to YouTube. */ String SESSION_YOUTUBE_URL = "session_youtube_url"; /** Full URL to PDF. */ String SESSION_PDF_URL = "session_pdf_url"; /** Full URL to official session notes. */ String SESSION_NOTES_URL = "session_notes_url"; /** User-specific flag indicating starred status. */ String SESSION_STARRED = "session_starred"; /** Key for session Calendar event. (Used in ICS or above) */ String SESSION_CAL_EVENT_ID = "session_cal_event_id"; /** The YouTube live stream URL. */ String SESSION_LIVESTREAM_URL = "session_livestream_url"; /** The Moderator URL. */ String SESSION_MODERATOR_URL = "session_moderator_url"; } interface SpeakersColumns { /** Unique string identifying this speaker. */ String SPEAKER_ID = "speaker_id"; /** Name of this speaker. */ String SPEAKER_NAME = "speaker_name"; /** Profile photo of this speaker. */ String SPEAKER_IMAGE_URL = "speaker_image_url"; /** Company this speaker works for. */ String SPEAKER_COMPANY = "speaker_company"; /** Body of text describing this speaker in detail. */ String SPEAKER_ABSTRACT = "speaker_abstract"; /** Full URL to the speaker's profile. */ String SPEAKER_URL = "speaker_url"; } interface SandboxColumns { /** Unique string identifying this sandbox company. */ String COMPANY_ID = "company_id"; /** Name of this sandbox company. */ String COMPANY_NAME = "company_name"; /** Body of text describing this sandbox company. */ String COMPANY_DESC = "company_desc"; /** Link to sandbox company online. */ String COMPANY_URL = "company_url"; /** Link to sandbox company logo. */ String COMPANY_LOGO_URL = "company_logo_url"; } interface AnnouncementsColumns { /** Unique string identifying this announcment. */ String ANNOUNCEMENT_ID = "announcement_id"; /** Title of the announcement. */ String ANNOUNCEMENT_TITLE = "announcement_title"; /** Google+ activity JSON for the announcement. */ String ANNOUNCEMENT_ACTIVITY_JSON = "announcement_activity_json"; /** Full URL for the announcement. */ String ANNOUNCEMENT_URL = "announcement_url"; /** Date of the announcement. */ String ANNOUNCEMENT_DATE = "announcement_date"; } interface MapMarkerColumns { /** Unique string identifying this marker. */ String MARKER_ID = "map_marker_id"; /** Type of marker. */ String MARKER_TYPE = "map_marker_type"; /** Latitudinal position of marker. */ String MARKER_LATITUDE = "map_marker_latitude"; /** Longitudinal position of marker. */ String MARKER_LONGITUDE = "map_marker_longitude"; /** Label (title) for this marker. */ String MARKER_LABEL = "map_marker_label"; /** Building floor this marker is on. */ String MARKER_FLOOR = "map_marker_floor"; /** Track of sandbox marker */ String MARKER_TRACK = "track_id"; } interface FeedbackColumns { String SESSION_ID = "session_id"; String SESSION_RATING = "feedback_session_rating"; String ANSWER_RELEVANCE = "feedback_answer_q1"; String ANSWER_CONTENT = "feedback_answer_q2"; String ANSWER_SPEAKER = "feedback_answer_q3"; String ANSWER_WILLUSE = "feedback_answer_q4"; String COMMENTS = "feedback_comments"; } interface MapTileColumns { /** Floor **/ String TILE_FLOOR = "map_tile_floor"; /** Filename **/ String TILE_FILE = "map_tile_file"; /** Url **/ String TILE_URL = "map_tile_url"; } public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_BLOCKS = "blocks"; private static final String PATH_AT = "at"; private static final String PATH_AFTER = "after"; private static final String PATH_BETWEEN = "between"; private static final String PATH_TRACKS = "tracks"; private static final String PATH_ROOM = "room"; private static final String PATH_ROOMS = "rooms"; private static final String PATH_SESSIONS = "sessions"; private static final String PATH_FEEDBACK = "feedback"; private static final String PATH_WITH_TRACK = "with_track"; private static final String PATH_STARRED = "starred"; private static final String PATH_SPEAKERS = "speakers"; private static final String PATH_SANDBOX = "sandbox"; private static final String PATH_ANNOUNCEMENTS = "announcements"; private static final String PATH_MAP_MARKERS = "mapmarkers"; private static final String PATH_MAP_FLOOR = "floor"; private static final String PATH_MAP_TILES= "maptiles"; private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH_SUGGEST = "search_suggest_query"; private static final String PATH_SEARCH_INDEX = "search_index"; /** * Blocks are generic timeslots that {@link Sessions} and other related * events fall into. */ public static class Blocks implements BlocksColumns, BaseColumns { public static final String BLOCK_TYPE_GENERIC = "generic"; public static final String BLOCK_TYPE_FOOD = "food"; public static final String BLOCK_TYPE_SESSION = "session"; public static final String BLOCK_TYPE_CODELAB = "codelab"; public static final String BLOCK_TYPE_KEYNOTE = "keynote"; public static final String BLOCK_TYPE_OFFICE_HOURS = "officehours"; public static final String BLOCK_TYPE_SANDBOX = "sandbox_only"; public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.block"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.block"; /** Count of {@link Sessions} inside given block. */ public static final String SESSIONS_COUNT = "sessions_count"; /** * Flag indicating the number of sessions inside this block that have * {@link Sessions#SESSION_STARRED} set. */ public static final String NUM_STARRED_SESSIONS = "num_starred_sessions"; /** * Flag indicating the number of sessions inside this block that have a * {@link Sessions#SESSION_LIVESTREAM_URL} set. */ public static final String NUM_LIVESTREAMED_SESSIONS = "num_livestreamed_sessions"; /** * The {@link Sessions#SESSION_ID} of the first starred session in this * block. */ public static final String STARRED_SESSION_ID = "starred_session_id"; /** * The {@link Sessions#SESSION_TITLE} of the first starred session in * this block. */ public static final String STARRED_SESSION_TITLE = "starred_session_title"; /** * The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred * session in this block. */ public static final String STARRED_SESSION_LIVESTREAM_URL = "starred_session_livestream_url"; /** * The {@link Rooms#ROOM_NAME} of the first starred session in this * block. */ public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name"; /** * The {@link Rooms#ROOM_ID} of the first starred session in this block. */ public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id"; /** * The {@link Sessions#SESSION_HASHTAGS} of the first starred session in * this block. */ public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags"; /** * The {@link Sessions#SESSION_URL} of the first starred session in this * block. */ public static final String STARRED_SESSION_URL = "starred_session_url"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, " + BlocksColumns.BLOCK_END + " ASC"; public static final String EMPTY_SESSIONS_SELECTION = BLOCK_TYPE + " IN ('" + Blocks.BLOCK_TYPE_SESSION + "','" + Blocks.BLOCK_TYPE_CODELAB + "','" + Blocks.BLOCK_TYPE_OFFICE_HOURS + "') AND " + SESSIONS_COUNT + " = 0"; /** Build {@link Uri} for requested {@link #BLOCK_ID}. */ public static Uri buildBlockUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references starred {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildStarredSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS) .appendPath(PATH_STARRED).build(); } /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */ public static String getBlockId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #BLOCK_ID} that will always match the requested * {@link Blocks} details. */ public static String generateBlockId(long startTime, long endTime) { startTime /= DateUtils.SECOND_IN_MILLIS; endTime /= DateUtils.SECOND_IN_MILLIS; return ParserUtils.sanitizeId(startTime + "-" + endTime); } } /** * Tracks are overall categories for {@link Sessions} and {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox}, * such as "Android" or "Enterprise." */ public static class Tracks implements TracksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build(); public static final int TRACK_META_NONE = 0; public static final int TRACK_META_SESSIONS_ONLY = 1; public static final int TRACK_META_SANDBOX_OFFICE_HOURS_ONLY = 2; public static final int TRACK_META_OFFICE_HOURS_ONLY = 3; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.track"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.track"; /** "All tracks" ID. */ public static final String ALL_TRACK_ID = "all"; /** Count of {@link Sessions} inside given track that aren't office hours. */ public static final String SESSIONS_COUNT = "sessions_count"; /** Count of {@link Sessions} inside given track that are office hours. */ public static final String OFFICE_HOURS_COUNT = "office_hours_count"; /** Count of {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} inside given track. */ public static final String SANDBOX_COUNT = "sandbox_count"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = TracksColumns.TRACK_LEVEL + ", " + TracksColumns.TRACK_ORDER_IN_LEVEL + ", " + TracksColumns.TRACK_NAME; /** Build {@link Uri} for requested {@link #TRACK_ID}. */ public static Uri buildTrackUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #TRACK_ID}. */ public static Uri buildSessionsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} associated with * the requested {@link #TRACK_ID}. */ public static Uri buildSandboxUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SANDBOX).build(); } /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */ public static String getTrackId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Rooms are physical locations at the conference venue. */ public static class Rooms implements RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.room"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.room"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, " + RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ROOM_ID}. */ public static Uri buildRoomUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #ROOM_ID}. */ public static Uri buildSessionsDirUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */ public static String getRoomId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Each session is a block of time that has a {@link Tracks}, a * {@link Rooms}, and zero or more {@link Speakers}. */ public static class Feedback implements BaseColumns, FeedbackColumns, SyncColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FEEDBACK).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session_feedback"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session_feedback"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BaseColumns._ID + " ASC, "; /** Build {@link Uri} to feedback for given session. */ public static Uri buildFeedbackUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** Read {@link #SESSION_ID} from {@link Feedback} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } } public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns, SyncColumns, BaseColumns { public static final String SESSION_TYPE_SESSION = "SESSION"; public static final String SESSION_TYPE_CODELAB = "CODE_LAB"; public static final String SESSION_TYPE_KEYNOTE = "KEYNOTE"; public static final String SESSION_TYPE_OFFICE_HOURS = "OFFICE_HOURS"; public static final String SESSION_TYPE_SANDBOX = "DEVELOPER_SANDBOX"; public static final String QUERY_PARAMETER_FILTER = "filter"; public static final String QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY = "sessions_codelabs_only"; // excludes keynote and office hours public static final String QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY = "office_hours_only"; public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session"; public static final String BLOCK_ID = "block_id"; public static final String ROOM_ID = "room_id"; public static final String SEARCH_SNIPPET = "search_snippet"; // TODO: shortcut primary track to offer sub-sorting here /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC," + SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC"; public static final String LIVESTREAM_SELECTION = SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''"; // Used to fetch sessions for a particular time public static final String AT_TIME_SELECTION = BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?"; // Builds selectionArgs for {@link AT_TIME_SELECTION} public static String[] buildAtTimeSelectionArgs(long time) { final String timeString = String.valueOf(time); return new String[] { timeString, timeString }; } // Used to fetch upcoming sessions public static final String UPCOMING_SELECTION = BLOCK_START + " = (select min(" + BLOCK_START + ") from " + ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION + " and " + BLOCK_START + " >" + " ?)"; // Builds selectionArgs for {@link UPCOMING_SELECTION} public static String[] buildUpcomingSelectionArgs(long minTime) { return new String[] { String.valueOf(minTime) }; } /** Build {@link Uri} for requested {@link #SESSION_ID}. */ public static Uri buildSessionUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** * Build {@link Uri} that references any {@link Speakers} associated * with the requested {@link #SESSION_ID}. */ public static Uri buildSpeakersDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build(); } /** * Build {@link Uri} that includes track detail with list of sessions. */ public static Uri buildWithTracksUri() { return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build(); } /** * Build {@link Uri} that includes track detail for a specific session. */ public static Uri buildWithTracksUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId) .appendPath(PATH_WITH_TRACK).build(); } /** * Build {@link Uri} that references any {@link Tracks} associated with * the requested {@link #SESSION_ID}. */ public static Uri buildTracksDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Build {@link Uri} that references sessions in a room that have begun after the requested time **/ public static Uri buildSessionsInRoomAfterUri(String room,long time) { return CONTENT_URI.buildUpon().appendPath(PATH_ROOM).appendPath(room).appendPath(PATH_AFTER) .appendPath(String.valueOf(time)).build(); } public static String getRoom(Uri uri){ return uri.getPathSegments().get(2); } public static String getAfter(Uri uri){ return uri.getPathSegments().get(4); } /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } } /** * Speakers are individual people that lead {@link Sessions}. */ public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.speaker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.speaker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */ public static Uri buildSpeakerUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #SPEAKER_ID}. */ public static Uri buildSessionsDirUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */ public static String getSpeakerId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Each sandbox company is a company appearing at the conference that may be * associated with a specific {@link Tracks} and time block. */ public static class Sandbox implements SandboxColumns, SyncColumns, BlocksColumns, RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SANDBOX).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.sandbox"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.sandbox"; /** {@link Tracks#TRACK_ID} that this sandbox company belongs to. */ public static final String TRACK_ID = "track_id"; // Used to fetch sandbox companies at a particular time public static final String AT_TIME_IN_ROOM_SELECTION = BLOCK_START + " < ? and " + BLOCK_END + " " + "> ? and " + " SANDBOX.ROOM_ID = ?"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SandboxColumns.COMPANY_NAME + " COLLATE NOCASE ASC"; // Builds selectionArgs for {@link AT_TIME_SELECTION} public static String[] buildAtTimeInRoomSelectionArgs(long time, String roomId) { final String timeString = String.valueOf(time); return new String[] { timeString, timeString, roomId }; } /** Build {@link Uri} for requested {@link #COMPANY_ID}. */ public static Uri buildCompanyUri(String companyId) { return CONTENT_URI.buildUpon().appendPath(companyId).build(); } /** Read {@link #COMPANY_ID} from {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} {@link Uri}. */ public static String getCompanyId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Announcements of breaking news */ public static class Announcements implements AnnouncementsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.announcement"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.announcement"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE + " COLLATE NOCASE DESC"; /** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */ public static Uri buildAnnouncementUri(String announcementId) { return CONTENT_URI.buildUpon().appendPath(announcementId).build(); } /** * Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}. */ public static String getAnnouncementId(Uri uri) { return uri.getPathSegments().get(1); } } /** * TileProvider entries are used to create an overlay provider for the map. */ public static class MapTiles implements MapTileColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(PATH_MAP_TILES).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.maptiles"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.maptiles"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = MapTileColumns.TILE_FLOOR + " ASC"; /** Build {@link Uri} for all overlay zoom entries */ public static Uri buildUri() { return CONTENT_URI; } /** Build {@link Uri} for requested floor. */ public static Uri buildFloorUri(String floor) { return CONTENT_URI.buildUpon() .appendPath(String.valueOf(floor)).build(); } /** Read floor from {@link MapMarkers} {@link Uri}. */ public static String getFloorId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Markers refer to marked positions on the map. */ public static class MapMarkers implements MapMarkerColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(PATH_MAP_MARKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.mapmarker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.mapmarker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = MapMarkerColumns.MARKER_FLOOR + " ASC, " + MapMarkerColumns.MARKER_ID + " ASC"; /** Build {@link Uri} for requested {@link #MARKER_ID}. */ public static Uri buildMarkerUri(String markerId) { return CONTENT_URI.buildUpon().appendPath(markerId).build(); } /** Build {@link Uri} for all markers */ public static Uri buildMarkerUri() { return CONTENT_URI; } /** Build {@link Uri} for requested {@link #MARKER_ID}. */ public static Uri buildFloorUri(int floor) { return CONTENT_URI.buildUpon().appendPath(PATH_MAP_FLOOR) .appendPath("" + floor).build(); } /** Read {@link #MARKER_ID} from {@link MapMarkers} {@link Uri}. */ public static String getMarkerId(Uri uri) { return uri.getPathSegments().get(1); } /** Read {@link #FLOOR} from {@link MapMarkers} {@link Uri}. */ public static String getMarkerFloor(Uri uri) { return uri.getPathSegments().get(2); } } public static class SearchSuggest { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build(); public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1 + " COLLATE NOCASE ASC"; } public static class SearchIndex { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_INDEX).build(); } public static Uri addCallerIsSyncAdapterParameter(Uri uri) { return uri.buildUpon().appendQueryParameter( ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); } public static boolean hasCallerIsSyncAdapterParameter(Uri uri) { return TextUtils.equals("true", uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER)); } private ScheduleContract() { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/provider/ScheduleContract.java
Java
asf20
34,155
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.service; import android.app.Service; import android.content.Intent; import android.os.*; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.gcm.ServerUtilities; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.util.AccountUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.turbomanage.httpclient.AsyncCallback; import com.turbomanage.httpclient.HttpResponse; import com.turbomanage.httpclient.ParameterMap; import com.turbomanage.httpclient.android.AndroidHttpClient; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Background {@link android.app.Service} that adds or removes sessions from your calendar via the * Conference API. * * @see com.google.android.apps.iosched.sync.SyncHelper */ public class ScheduleUpdaterService extends Service { private static final String TAG = makeLogTag(ScheduleUpdaterService.class); public static final String EXTRA_SESSION_ID = "com.google.android.apps.iosched.extra.SESSION_ID"; public static final String EXTRA_IN_SCHEDULE = "com.google.android.apps.iosched.extra.IN_SCHEDULE"; private static final int SCHEDULE_UPDATE_DELAY_MILLIS = 5000; private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler; private final LinkedList<Intent> mScheduleUpdates = new LinkedList<Intent>(); // Handler pattern copied from IntentService private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { processPendingScheduleUpdates(); int numRemainingUpdates; synchronized (mScheduleUpdates) { numRemainingUpdates = mScheduleUpdates.size(); } if (numRemainingUpdates == 0) { notifyGcmDevices(); stopSelf(); } else { // More updates were added since the current pending set was processed. Reschedule // another pass. removeMessages(0); sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS); } } } // private static class NotifyGcmDevicesTask extends AsyncTask<String, Void, Void> { // // @Override // protected Void doInBackground(String... params) { // BasicHttp // String gPlusID = params[0]; // Uri uri = new Uri(Config.GCM_SERVER_URL + "/send/" + gPlusID + "/sync_user"); // connection = (HttpURLConnection) url.openConnection(); // connection.setDoOutput(true); // connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // connection.setRequestMethod("POST"); // // request = new OutputStreamWriter(connection.getOutputStream()); // request.write(parameters); // request.flush(); // request.close(); // // } // } private void notifyGcmDevices() { String plusID = AccountUtils.getPlusProfileId(getApplicationContext()); if (plusID != null) { LOGI(TAG, "Sending device sync notification"); AndroidHttpClient httpClient = new AndroidHttpClient(Config.GCM_SERVER_URL); httpClient.setMaxRetries(1); ParameterMap params = httpClient.newParams() .add("key", Config.GCM_API_KEY) .add("squelch", ServerUtilities.getGcmId(this)); String path = "/send/" + plusID + "/sync_user"; httpClient.post(path, params, new AsyncCallback() { @Override public void onComplete(HttpResponse httpResponse) { LOGI(TAG, "Device sync notification sent"); } @Override public void onError(Exception e) { LOGW(TAG, "Device sync notification failed", e); } }); } else { LOGI(TAG, "No gPlusID, skipping device sync notification"); } } public ScheduleUpdaterService() { } @Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread(ScheduleUpdaterService.class.getSimpleName()); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // When receiving a new intent, delay the schedule until 5 seconds from now. mServiceHandler.removeMessages(0); mServiceHandler.sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS); // Remove pending updates involving this session ID. String sessionId = intent.getStringExtra(EXTRA_SESSION_ID); Iterator<Intent> updatesIterator = mScheduleUpdates.iterator(); while (updatesIterator.hasNext()) { Intent existingIntent = updatesIterator.next(); if (sessionId.equals(existingIntent.getStringExtra(EXTRA_SESSION_ID))) { updatesIterator.remove(); } } // Queue this schedule update. synchronized (mScheduleUpdates) { mScheduleUpdates.add(intent); } return START_REDELIVER_INTENT; } @Override public void onDestroy() { mServiceLooper.quit(); } @Override public IBinder onBind(Intent intent) { return null; } void processPendingScheduleUpdates() { try { // Operate on a local copy of the schedule update list so as not to block // the main thread adding to this list List<Intent> scheduleUpdates = new ArrayList<Intent>(); synchronized (mScheduleUpdates) { scheduleUpdates.addAll(mScheduleUpdates); mScheduleUpdates.clear(); } SyncHelper syncHelper = new SyncHelper(this); for (Intent updateIntent : scheduleUpdates) { String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID); boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false); LOGI(TAG, "addOrRemoveSessionFromSchedule:" + " sessionId=" + sessionId + " inSchedule=" + inSchedule); syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule); } } catch (IOException e) { // TODO: do something useful here, like revert the changes locally in the // content provider to maintain client/server sync LOGE(TAG, "Error processing schedule update", e); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/service/ScheduleUpdaterService.java
Java
asf20
7,620
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.service; import android.content.Intent; import android.database.Cursor; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.DateUtils; import com.google.android.apps.dashclock.api.ExtensionData; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.UIUtils; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Locale; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An I/O 2013 extension for DashClock. */ public class DashClockExtension extends com.google.android.apps.dashclock.api.DashClockExtension { private static final String TAG = makeLogTag(DashClockExtension.class); private static final long MINUTE_MILLIS = 60 * 1000; private static final long NOW_BUFFER_TIME_MILLIS = 15 * MINUTE_MILLIS; private static final int MAX_BLOCKS = 5; private static final long CONTENT_CHANGE_DELAY_MILLIS = 5 * 1000; private static long mLastChange = 0; @Override protected void onInitialize(boolean isReconnect) { super.onInitialize(isReconnect); setUpdateWhenScreenOn(true); addWatchContentUris(new String[]{ ScheduleContract.Sessions.CONTENT_URI.toString() }); } @Override protected void onUpdateData(int reason) { if (reason == DashClockExtension.UPDATE_REASON_CONTENT_CHANGED) { long time = System.currentTimeMillis(); if (time < mLastChange + CONTENT_CHANGE_DELAY_MILLIS) { return; } mLastChange = time; } long currentTime = UIUtils.getCurrentTime(this); if (currentTime >= UIUtils.CONFERENCE_END_MILLIS) { publishUpdate(new ExtensionData() .visible(true) .icon(R.drawable.dashclock_extension) .status(getString(R.string.whats_on_thank_you_short)) .expandedTitle(getString(R.string.whats_on_thank_you_title)) .expandedBody(getString(R.string.whats_on_thank_you_subtitle)) .clickIntent(new Intent(this, HomeActivity.class))); return; } Cursor cursor = tryOpenBlocksCursor(); if (cursor == null) { LOGE(TAG, "Null blocks cursor, short-circuiting."); return; } StringBuilder buffer = new StringBuilder(); Formatter formatter = new Formatter(buffer, Locale.getDefault()); String firstBlockStartTime = null; List<String> blocks = new ArrayList<String>(); long lastBlockStart = 0; while (cursor.moveToNext()) { if (blocks.size() >= MAX_BLOCKS) { break; } final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final String blockType = cursor.getString(BlocksQuery.BLOCK_TYPE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); buffer.setLength(0); boolean showWeekday = !DateUtils.isToday(blockStart) && !UIUtils.isSameDayDisplay(lastBlockStart, blockStart, this); String blockStartTime = DateUtils.formatDateRange(this, formatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME | (showWeekday ? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY : 0), PrefUtils.getDisplayTimeZone(this).getID()).toString(); lastBlockStart = blockStart; if (firstBlockStartTime == null) { firstBlockStartTime = blockStartTime; } if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); if (numStarredSessions == 1) { // exactly 1 session starred String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); String room = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (room == null) { room = getString(R.string.unknown_room); } blocks.add(blockStartTime + ", " + room + " — " + title); } else { // 2 or more sessions starred String title = getString(R.string.schedule_conflict_title, numStarredSessions); blocks.add(blockStartTime + " — " + title); } } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) { final String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); blocks.add(blockStartTime + " — " + title); } else { blocks.add(blockStartTime + " — " + blockTitle); } } cursor.close(); LOGD(TAG, blocks.size() + " blocks"); if (blocks.size() > 0) { publishUpdate(new ExtensionData() .visible(true) .icon(R.drawable.dashclock_extension) .status(firstBlockStartTime) .expandedTitle(blocks.get(0)) .expandedBody(TextUtils.join("\n", blocks.subList(1, blocks.size()))) .clickIntent(new Intent(this, HomeActivity.class))); } else { publishUpdate(new ExtensionData().visible(false)); } } private Cursor tryOpenBlocksCursor() { try { String liveStreamedOnlyBlocksSelection = "(" + (UIUtils.shouldShowLiveSessionsOnly(this) ? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','" + ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')" + " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 " : "1==1") + ")"; String onlyStarredSelection = "(" + ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "') " + " OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)"; String excludeSandbox = ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX + "'"; return getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, ScheduleContract.Blocks.BLOCK_START + " >= ? AND " + liveStreamedOnlyBlocksSelection + " AND " + onlyStarredSelection + " AND " + excludeSandbox, new String[]{ Long.toString(UIUtils.getCurrentTime(this) - NOW_BUFFER_TIME_MILLIS) }, ScheduleContract.Blocks.DEFAULT_SORT); } catch (Exception e) { LOGE(TAG, "Error querying I/O 2013 content provider", e); return null; } } public interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS, }; int _ID = 0; int BLOCK_TITLE = 1; int BLOCK_START = 2; int BLOCK_TYPE = 3; int NUM_STARRED_SESSIONS = 4; int STARRED_SESSION_TITLE = 5; int STARRED_SESSION_ROOM_NAME = 6; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/service/DashClockExtension.java
Java
asf20
9,590
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.service; import android.graphics.Bitmap; import android.provider.BaseColumns; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import android.app.AlarmManager; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background service to handle scheduling of starred session notification via * {@link android.app.AlarmManager}. */ public class SessionAlarmService extends IntentService { private static final String TAG = makeLogTag(SessionAlarmService.class); public static final String ACTION_NOTIFY_SESSION = "com.google.android.apps.iosched.action.NOTIFY_SESSION"; public static final String ACTION_SCHEDULE_STARRED_BLOCK = "com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK"; public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS = "com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS"; public static final String EXTRA_SESSION_START = "com.google.android.apps.iosched.extra.SESSION_START"; public static final String EXTRA_SESSION_END = "com.google.android.apps.iosched.extra.SESSION_END"; public static final String EXTRA_SESSION_ALARM_OFFSET = "com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET"; private static final int NOTIFICATION_ID = 100; // pulsate every 1 second, indicating a relatively high degree of urgency private static final int NOTIFICATION_LED_ON_MS = 100; private static final int NOTIFICATION_LED_OFF_MS = 1000; private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan private static final long MILLI_TEN_MINUTES = 600000; private static final long MILLI_ONE_MINUTE = 60000; private static final long UNDEFINED_ALARM_OFFSET = -1; private static final long UNDEFINED_VALUE = -1; public SessionAlarmService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { final String action = intent.getAction(); if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) { scheduleAllStarredBlocks(); return; } final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, UNDEFINED_VALUE); if (sessionStart == UNDEFINED_VALUE) return; final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, UNDEFINED_VALUE); if (sessionEnd == UNDEFINED_VALUE) return; final long sessionAlarmOffset = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, UNDEFINED_ALARM_OFFSET); if (ACTION_NOTIFY_SESSION.equals(action)) { notifySession(sessionStart, sessionEnd, sessionAlarmOffset); } else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) { scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset); } } private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(NOTIFICATION_ID); final long currentTime = UIUtils.getCurrentTime(this); // If the session is already started, do not schedule system notification. if (currentTime > sessionStart) return; // By default, sets alarm to go off at 10 minutes before session start time. If alarm // offset is provided, alarm is set to go off by that much time from now. long alarmTime; if (alarmOffset == UNDEFINED_ALARM_OFFSET) { alarmTime = sessionStart - MILLI_TEN_MINUTES; } else { alarmTime = currentTime + alarmOffset; } final Intent notifIntent = new Intent( ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class); // Setting data to ensure intent's uniqueness for different session start times. notifIntent.setData( new Uri.Builder().authority("com.google.android.apps.iosched") .path(String.valueOf(sessionStart)).build()); notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset); PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // Schedule an alarm to be fired to notify user of added sessions are about to begin. am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi); } // Starred sessions are about to begin. Constructs and triggers system notification. private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) { long currentTime; if (sessionStart < (currentTime = UIUtils.getCurrentTime(this))) return; // Avoid repeated notifications. if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock( this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) { return; } final ContentResolver cr = getContentResolver(); final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri( ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd) ); Cursor c = cr.query(starredBlockUri, SessionDetailQuery.PROJECTION, null, null, null); int starredCount = 0; ArrayList<String> starredSessionTitles = new ArrayList<String>(); ArrayList<String> starredSessionRoomIds = new ArrayList<String>(); String sessionId = null; // needed to get session track icon while (c.moveToNext()) { sessionId = c.getString(SessionDetailQuery.SESSION_ID); starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS); starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE)); starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID)); } if (starredCount < 1) { return; } // Generates the pending intent which gets fired when the user taps on the notification. // NOTE: Use TaskStackBuilder to comply with Android's design guidelines // related to navigation from notifications. PendingIntent pi = TaskStackBuilder.create(this) .addNextIntent(new Intent(this, HomeActivity.class)) .addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri)) .getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT); final Resources res = getResources(); String contentText; int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000; if (minutesLeft < 1) { minutesLeft = 1; } if (starredCount == 1) { contentText = res.getString(R.string.session_notification_text_1, minutesLeft); } else { contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft, starredCount - 1); } NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this) .setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights( SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification) .setContentIntent(pi) .setPriority(Notification.PRIORITY_MAX) .setAutoCancel(true); if (starredCount == 1) { // get the track icon to show as the notification big picture Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId); Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION, null, null, null); if (tracksCursor.moveToFirst()) { String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME); int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR); Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(), trackName, trackColour); if (trackIcon != null) { notifBuilder.setLargeIcon(trackIcon); } } } if (minutesLeft > 5) { notifBuilder.addAction(R.drawable.ic_alarm_holo_dark, String.format(res.getString(R.string.snooze_x_min), 5), createSnoozeIntent(sessionStart, sessionEnd, 5)); } if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) { notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map), createRoomMapIntent(starredSessionRoomIds.get(0))); } NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle( notifBuilder) .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft, starredCount)); // Adds starred sessions starting at this time block to the notification. for (int i = 0; i < starredCount; i++) { richNotification.addLine(starredSessionTitles.get(i)); } NotificationManager nm = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, richNotification.build()); } private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd, final int snoozeMinutes) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, this, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, snoozeMinutes * MILLI_ONE_MINUTE); return PendingIntent.getService(this, 0, scheduleIntent, PendingIntent.FLAG_CANCEL_CURRENT); } private PendingIntent createRoomMapIntent(final String roomId) { Intent mapIntent = new Intent(getApplicationContext(), UIUtils.getMapActivityClass(getApplicationContext())); mapIntent.putExtra(MapFragment.EXTRA_ROOM, roomId); return PendingIntent.getActivity(this, 0, mapIntent, 0); } private void scheduleAllStarredBlocks() { final ContentResolver cr = getContentResolver(); final Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_STARRED_URI, new String[]{"distinct " + ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END}, null, null, null); if (c == null) { return; } while (c.moveToNext()) { final long sessionStart = c.getLong(0); final long sessionEnd = c.getLong(1); scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET); } } public interface SessionDetailQuery { String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.ROOM_ID }; int SESSION_ID = 0; int NUM_STARRED_SESSIONS = 1; int SESSION_TITLE = 2; int ROOM_ID = 3; } public interface SessionTrackQuery { String[] PROJECTION = { ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 2; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/service/SessionAlarmService.java
Java
asf20
14,594
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.google.android.apps.iosched.service.SessionAlarmService; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred * session blocks. */ public class SessionAlarmReceiver extends BroadcastReceiver { public static final String TAG = makeLogTag(SessionAlarmReceiver.class); @Override public void onReceive(Context context, Intent intent) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS, null, context, SessionAlarmService.class); context.startService(scheduleIntent); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/receiver/SessionAlarmReceiver.java
Java
asf20
1,459
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; /** * {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing * then against fractional dimensions of the source view. * <p> * This is particularly useful when you want to define a rectangle in terms of * the source dimensions, but when those dimensions might change due to pending * or future layout passes. * <p> * One example is catching touches that occur in the top-right quadrant of * {@code sourceParent}, and relaying them to {@code targetChild}. This could be * done with: <code> * FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f)); * </code> */ public class FractionalTouchDelegate extends TouchDelegate { private View mSource; private View mTarget; private RectF mSourceFraction; private Rect mScrap = new Rect(); /** Cached full dimensions of {@link #mSource}. */ private Rect mSourceFull = new Rect(); /** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */ private Rect mSourcePartial = new Rect(); private boolean mDelegateTargeted; public FractionalTouchDelegate(View source, View target, RectF sourceFraction) { super(new Rect(0, 0, 0, 0), target); mSource = source; mTarget = target; mSourceFraction = sourceFraction; } /** * Helper to create and setup a {@link FractionalTouchDelegate} between the * given {@link View}. * * @param source Larger source {@link View}, usually a parent, that will be * assigned {@link View#setTouchDelegate(TouchDelegate)}. * @param target Smaller target {@link View} which will receive * {@link MotionEvent} that land in requested fractional area. * @param sourceFraction Fractional area projected onto source {@link View} * which determines when {@link MotionEvent} will be passed to * target {@link View}. */ public static void setupDelegate(View source, View target, RectF sourceFraction) { source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction)); } /** * Consider updating {@link #mSourcePartial} when {@link #mSource} * dimensions have changed. */ private void updateSourcePartial() { mSource.getHitRect(mScrap); if (!mScrap.equals(mSourceFull)) { // Copy over and calculate fractional rectangle mSourceFull.set(mScrap); final int width = mSourceFull.width(); final int height = mSourceFull.height(); mSourcePartial.left = (int) (mSourceFraction.left * width); mSourcePartial.top = (int) (mSourceFraction.top * height); mSourcePartial.right = (int) (mSourceFraction.right * width); mSourcePartial.bottom = (int) (mSourceFraction.bottom * height); } } @Override public boolean onTouchEvent(MotionEvent event) { updateSourcePartial(); // The logic below is mostly copied from the parent class, since we // can't update private mBounds variable. // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob; // f=core/java/android/view/TouchDelegate.java;hb=eclair#l98 final Rect sourcePartial = mSourcePartial; final View target = mTarget; int x = (int)event.getX(); int y = (int)event.getY(); boolean sendToDelegate = false; boolean hit = true; boolean handled = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (sourcePartial.contains(x, y)) { mDelegateTargeted = true; sendToDelegate = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: sendToDelegate = mDelegateTargeted; if (sendToDelegate) { if (!sourcePartial.contains(x, y)) { hit = false; } } break; case MotionEvent.ACTION_CANCEL: sendToDelegate = mDelegateTargeted; mDelegateTargeted = false; break; } if (sendToDelegate) { if (hit) { event.setLocation(target.getWidth() / 2, target.getHeight() / 2); } else { event.setLocation(-1, -1); } handled = target.dispatchTouchEvent(event); } return handled; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/FractionalTouchDelegate.java
Java
asf20
5,324
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.annotation.TargetApi; import android.app.Activity; import android.content.AsyncQueryHandler; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v4.app.ShareCompat; import android.view.ActionProvider; import android.view.MenuItem; import android.widget.ShareActionProvider; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.appwidget.ScheduleWidgetProvider; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.service.ScheduleUpdaterService; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SocialStreamActivity; import com.google.android.apps.iosched.ui.SocialStreamFragment; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper class for dealing with common actions to take on a session. */ public final class SessionsHelper { private static final String TAG = makeLogTag(SessionsHelper.class); private final Activity mActivity; public SessionsHelper(Activity activity) { mActivity = activity; } public void startMapActivity(String roomId) { Intent intent = new Intent(mActivity.getApplicationContext(), UIUtils.getMapActivityClass(mActivity)); intent.putExtra(MapFragment.EXTRA_ROOM, roomId); mActivity.startActivity(intent); } public Intent createShareIntent(int messageTemplateResId, String title, String hashtags, String url) { ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(mActivity) .setType("text/plain") .setText(mActivity.getString(messageTemplateResId, title, UIUtils.getSessionHashtagsString(hashtags), url)); return builder.getIntent(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void tryConfigureShareMenuItem(MenuItem menuItem, int messageTemplateResId, final String title, String hashtags, String url) { if (UIUtils.hasICS()) { ActionProvider itemProvider = menuItem.getActionProvider(); ShareActionProvider provider; if (!(itemProvider instanceof ShareActionProvider)) { provider = new ShareActionProvider(mActivity); } else { provider = (ShareActionProvider) itemProvider; } provider.setShareIntent(createShareIntent(messageTemplateResId, title, hashtags, url)); provider.setOnShareTargetSelectedListener( new ShareActionProvider.OnShareTargetSelectedListener() { @Override public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) { EasyTracker.getTracker().sendEvent("Session", "Shared", title, 0L); LOGD("Tracker", "Shared: " + title); return false; } }); menuItem.setActionProvider(provider); } } public void shareSession(Context context, int messageTemplateResId, String title, String hashtags, String url) { EasyTracker.getTracker().sendEvent("Session", "Shared", title, 0L); LOGD("Tracker", "Shared: " + title); context.startActivity(Intent.createChooser( createShareIntent(messageTemplateResId, title, hashtags, url), context.getString(R.string.title_share))); } public void setSessionStarred(Uri sessionUri, boolean starred, String title) { LOGD(TAG, "setSessionStarred uri=" + sessionUri + " starred=" + starred + " title=" + title); sessionUri = ScheduleContract.addCallerIsSyncAdapterParameter(sessionUri); final ContentValues values = new ContentValues(); values.put(ScheduleContract.Sessions.SESSION_STARRED, starred); AsyncQueryHandler handler = new AsyncQueryHandler(mActivity.getContentResolver()) { }; handler.startUpdate(-1, null, sessionUri, values, null, null); EasyTracker.getTracker().sendEvent( "Session", starred ? "Starred" : "Unstarred", title, 0L); // Because change listener is set to null during initialization, these // won't fire on pageview. mActivity.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(mActivity, false)); // Sync to the cloudz. uploadStarredSession(mActivity, sessionUri, starred); } public static void uploadStarredSession(Context context, Uri sessionUri, boolean starred) { final Intent updateServerIntent = new Intent(context, ScheduleUpdaterService.class); updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_SESSION_ID, ScheduleContract.Sessions.getSessionId(sessionUri)); updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_IN_SCHEDULE, starred); context.startService(updateServerIntent); } public void startSocialStream(String hashtags) { Intent intent = new Intent(mActivity, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(hashtags)); mActivity.startActivity(intent); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/SessionsHelper.java
Java
asf20
6,244
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.ArrayList; import java.util.Collections; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public class Lists { /** * Creates an empty {@code ArrayList} instance. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } /** * Creates a resizable {@code ArrayList} instance containing the given * elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of * {@code Base}, not of {@code Base} itself. To get around this, you must * use: * * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} * * @param elements the elements that the list should contain, in order * @return a newly-created {@code ArrayList} containing those elements */ public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/Lists.java
Java
asf20
2,170
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.Html; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebView; import android.widget.TextView; /** * This is a set of helper methods for showing contextual help information in the app. */ public class HelpUtils { public static void showAbout(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_about"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new AboutDialog().show(ft, "dialog_about"); } public static class AboutDialog extends DialogFragment { private static final String VERSION_UNAVAILABLE = "N/A"; public AboutDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Get app version PackageManager pm = getActivity().getPackageManager(); String packageName = getActivity().getPackageName(); String versionName; try { PackageInfo info = pm.getPackageInfo(packageName, 0); versionName = info.versionName; } catch (PackageManager.NameNotFoundException e) { versionName = VERSION_UNAVAILABLE; } // Build the about body view and append the link to see OSS licenses SpannableStringBuilder aboutBody = new SpannableStringBuilder(); aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName))); SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses)); licensesLink.setSpan(new ClickableSpan() { @Override public void onClick(View view) { HelpUtils.showOpenSourceLicenses(getActivity()); } }, 0, licensesLink.length(), 0); aboutBody.append("\n\n"); aboutBody.append(licensesLink); SpannableString eulaLink = new SpannableString(getString(R.string.about_eula)); eulaLink.setSpan(new ClickableSpan() { @Override public void onClick(View view) { HelpUtils.showEula(getActivity()); } }, 0, eulaLink.length(), 0); aboutBody.append("\n\n"); aboutBody.append(eulaLink); LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null); aboutBodyView.setText(aboutBody); aboutBodyView.setMovementMethod(new LinkMovementMethod()); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_about) .setView(aboutBodyView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } } public static void showOpenSourceLicenses(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_licenses"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new OpenSourceLicensesDialog().show(ft, "dialog_licenses"); } public static class OpenSourceLicensesDialog extends DialogFragment { public OpenSourceLicensesDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { WebView webView = new WebView(getActivity()); webView.loadUrl("file:///android_asset/licenses.html"); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.about_licenses) .setView(webView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } } public static void showEula(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_eula"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new EulaDialog().show(ft, "dialog_eula"); } public static class EulaDialog extends DialogFragment { public EulaDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal); TextView eulaTextView = new TextView(getActivity()); eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text))); eulaTextView.setMovementMethod(LinkMovementMethod.getInstance()); eulaTextView.setPadding(padding, padding, padding, padding); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.about_eula) .setView(eulaTextView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/HelpUtils.java
Java
asf20
7,817
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications: * -Imported from AOSP frameworks/base/core/java/com/android/internal/content * -Changed package name */ package com.google.android.apps.iosched.util; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Map; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper for building selection clauses for {@link SQLiteDatabase}. Each * appended clause is combined using {@code AND}. This class is <em>not</em> * thread safe. */ public class SelectionBuilder { private static final String TAG = makeLogTag(SelectionBuilder.class); private String mTable = null; private Map<String, String> mProjectionMap = Maps.newHashMap(); private StringBuilder mSelection = new StringBuilder(); private ArrayList<String> mSelectionArgs = Lists.newArrayList(); /** * Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { mTable = null; mSelection.setLength(0); mSelectionArgs.clear(); return this; } /** * Append the given selection clause to the internal state. Each clause is * surrounded with parenthesis and combined using {@code AND}. */ public SelectionBuilder where(String selection, String... selectionArgs) { if (TextUtils.isEmpty(selection)) { if (selectionArgs != null && selectionArgs.length > 0) { throw new IllegalArgumentException( "Valid selection required when including arguments="); } // Shortcut when clause is empty return this; } if (mSelection.length() > 0) { mSelection.append(" AND "); } mSelection.append("(").append(selection).append(")"); if (selectionArgs != null) { Collections.addAll(mSelectionArgs, selectionArgs); } return this; } public SelectionBuilder table(String table) { mTable = table; return this; } private void assertTable() { if (mTable == null) { throw new IllegalStateException("Table not specified"); } } public SelectionBuilder mapToTable(String column, String table) { mProjectionMap.put(column, table + "." + column); return this; } public SelectionBuilder map(String fromColumn, String toClause) { mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); return this; } /** * Return selection string for current internal state. * * @see #getSelectionArgs() */ public String getSelection() { return mSelection.toString(); } /** * Return selection arguments for current internal state. * * @see #getSelection() */ public String[] getSelectionArgs() { return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); } private void mapColumns(String[] columns) { for (int i = 0; i < columns.length; i++) { final String target = mProjectionMap.get(columns[i]); if (target != null) { columns[i] = target; } } } @Override public String toString() { return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { return query(db, columns, null, null, orderBy, null); } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having, String orderBy, String limit) { assertTable(); if (columns != null) mapColumns(columns); LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy, limit); } /** * Execute update using the current internal state as {@code WHERE} clause. */ public int update(SQLiteDatabase db, ContentValues values) { assertTable(); LOGV(TAG, "update() " + this); return db.update(mTable, values, getSelection(), getSelectionArgs()); } /** * Execute delete using the current internal state as {@code WHERE} clause. */ public int delete(SQLiteDatabase db) { assertTable(); LOGV(TAG, "delete() " + this); return db.delete(mTable, getSelection(), getSelectionArgs()); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/SelectionBuilder.java
Java
asf20
5,630
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.Context; import android.content.SharedPreferences; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceManager; import com.google.android.apps.iosched.Config; import java.util.TimeZone; /** * Utilities and constants related to app preferences. */ public class PrefUtils { /** * Boolean preference that when checked, indicates that the user would like to see times * in their local timezone throughout the app. */ public static final String PREF_LOCAL_TIMES = "pref_local_times"; /** * Boolean preference that when checked, indicates that the user will be attending the * conference. */ public static final String PREF_ATTENDEE_AT_VENUE = "pref_attendee_at_venue"; /** * Boolean preference that when checked, indicates that the user has completed account * authentication and the initial set up flow. */ public static final String PREF_SETUP_DONE = "pref_setup_done"; /** * Integer preference that indicates what conference year the application is configured * for. Typically, if this isn't an exact match, preferences should be wiped to re-run * setup. */ public static final String PREF_CONFERENCE_YEAR = "pref_conference_year"; /** * Boolean indicating whether a user's DevSite profile is available. Defaults to true. */ public static final String PREF_DEVSITE_PROFILE_AVAILABLE = "pref_devsite_profile_available"; private static int sIsUsingLocalTime = -1; private static int sAttendeeAtVenue = -1; public static TimeZone getDisplayTimeZone(Context context) { return isUsingLocalTime(context) ? TimeZone.getDefault() : UIUtils.CONFERENCE_TIME_ZONE; } public static boolean isUsingLocalTime(Context context) { return isUsingLocalTime(context, false); } public static boolean isUsingLocalTime(Context context, boolean forceRequery) { if (sIsUsingLocalTime == -1 || forceRequery) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sIsUsingLocalTime = sp.getBoolean(PREF_LOCAL_TIMES, false) ? 1 : 0; } return sIsUsingLocalTime == 1; } public static void setUsingLocalTime(final Context context, final boolean usingLocalTime) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean(PREF_LOCAL_TIMES, usingLocalTime).commit(); } public static boolean isAttendeeAtVenue(final Context context) { return isAttendeeAtVenue(context, false); } public static boolean isAttendeeAtVenue(final Context context, boolean forceRequery) { if (sAttendeeAtVenue == -1 || forceRequery) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sAttendeeAtVenue = sp.getBoolean(PREF_ATTENDEE_AT_VENUE, false) ? 1 : 0; } return sAttendeeAtVenue == 1; } public static void markSetupDone(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean(PREF_SETUP_DONE, true).commit(); } public static boolean isSetupDone(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Check what year we're configured for int conferenceYear = sp.getInt(PREF_CONFERENCE_YEAR, 0); if (conferenceYear != Config.CONFERENCE_YEAR) { // Application is configured for a different conference year. Reset // preferences and re-run setup. sp.edit().clear().putInt(PREF_CONFERENCE_YEAR, Config.CONFERENCE_YEAR).commit(); } return sp.getBoolean(PREF_SETUP_DONE, false); } public static void setAttendeeAtVenue(final Context context, final boolean isAtVenue) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean(PREF_ATTENDEE_AT_VENUE, isAtVenue).commit(); } public static void markDevSiteProfileAvailable(final Context context, final boolean isAvailable) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean(PREF_DEVSITE_PROFILE_AVAILABLE, isAvailable).commit(); } public static boolean isDevsiteProfileAvailable(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean(PREF_DEVSITE_PROFILE_AVAILABLE, true); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/PrefUtils.java
Java
asf20
5,327
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.BuildConfig; import android.util.Log; public class LogUtils { private static final String LOG_PREFIX = "iosched_"; private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); private static final int MAX_LOG_TAG_LENGTH = 23; public static String makeLogTag(String str) { if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); } return LOG_PREFIX + str; } /** * Don't use this when obfuscating class names! */ public static String makeLogTag(Class cls) { return makeLogTag(cls.getSimpleName()); } public static void LOGD(final String tag, String message) { //noinspection PointlessBooleanExpression,ConstantConditions if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, message); } } public static void LOGD(final String tag, String message, Throwable cause) { //noinspection PointlessBooleanExpression,ConstantConditions if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, message, cause); } } public static void LOGV(final String tag, String message) { //noinspection PointlessBooleanExpression,ConstantConditions if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) { Log.v(tag, message); } } public static void LOGV(final String tag, String message, Throwable cause) { //noinspection PointlessBooleanExpression,ConstantConditions if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) { Log.v(tag, message, cause); } } public static void LOGI(final String tag, String message) { Log.i(tag, message); } public static void LOGI(final String tag, String message, Throwable cause) { Log.i(tag, message, cause); } public static void LOGW(final String tag, String message) { Log.w(tag, message); } public static void LOGW(final String tag, String message, Throwable cause) { Log.w(tag, message, cause); } public static void LOGE(final String tag, String message) { Log.e(tag, message); } public static void LOGE(final String tag, String message, Throwable cause) { Log.e(tag, message, cause); } private LogUtils() { } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
Java
asf20
3,122
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.HashMap; import java.util.LinkedHashMap; /** * Provides static methods for creating mutable {@code Maps} instances easily. */ public class Maps { /** * Creates a {@code HashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/Maps.java
Java
asf20
1,038
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.annotation.TargetApi; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.preference.PreferenceManager; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.ui.phone.MapActivity; import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity; import java.io.*; import java.lang.ref.WeakReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Formatter; import java.util.Locale; import java.util.TimeZone; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An assortment of UI helpers. */ public class UIUtils { private static final String TAG = makeLogTag(UIUtils.class); /** * Time zone to use when formatting all session times. To always use the * phone local time, use {@link TimeZone#getDefault()}. */ public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles"); public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime( "2013-05-15T09:00:00.000-07:00"); public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime( "2013-05-17T16:00:00.000-07:00"); public static final String CONFERENCE_HASHTAG = "#io13"; public static final String TARGET_FORM_FACTOR_ACTIVITY_METADATA = "com.google.android.apps.iosched.meta.TARGET_FORM_FACTOR"; public static final String TARGET_FORM_FACTOR_HANDSET = "handset"; public static final String TARGET_FORM_FACTOR_TABLET = "tablet"; /** * Flags used with {@link DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; /** * Regex to search for HTML escape sequences. * * <p></p>Searches for any continuous string of characters starting with an ampersand and ending with a * semicolon. (Example: &amp;amp;) */ private static final Pattern REGEX_HTML_ESCAPE = Pattern.compile(".*&\\S;.*"); /** * Used in {@link #tryTranslateHttpIntent(android.app.Activity)}. */ private static final Uri SESSION_DETAIL_WEB_URL_PREFIX = Uri.parse("https://developers.google.com/events/io/sessions/"); private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); private static ForegroundColorSpan sColorSpan = new ForegroundColorSpan(0xff111111); private static CharSequence sEmptyRoomText; private static CharSequence sNowPlayingText; private static CharSequence sLivestreamNowText; private static CharSequence sLivestreamAvailableText; public static final String GOOGLE_PLUS_PACKAGE_NAME = "com.google.android.apps.plus"; public static final int ANIMATION_FADE_IN_TIME = 250; public static final String TRACK_ICONS_TAG = "tracks"; /** * Format and return the given {@link Blocks} and {@link Rooms} values using * {@link #CONFERENCE_TIME_ZONE}. */ public static String formatSessionSubtitle(String sessionTitle, long blockStart, long blockEnd, String roomName, StringBuilder recycle, Context context) { // Determine if the session is in the past long currentTimeMillis = UIUtils.getCurrentTime(context); boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS; boolean blockEnded = currentTimeMillis > blockEnd; if (blockEnded && !conferenceEnded) { return context.getString(R.string.session_finished); } if (sEmptyRoomText == null) { sEmptyRoomText = context.getText(R.string.unknown_room); } if (roomName == null) { return context.getString(R.string.session_subtitle, formatBlockTimeString(blockStart, blockEnd, recycle, context), sEmptyRoomText); } return context.getString(R.string.session_subtitle, formatBlockTimeString(blockStart, blockEnd, recycle, context), roomName); } /** * Format and return the given {@link Blocks} values using {@link #CONFERENCE_TIME_ZONE} * (unless local time was explicitly requested by the user). */ public static String formatBlockTimeString(long blockStart, long blockEnd, StringBuilder recycle, Context context) { if (recycle == null) { recycle = new StringBuilder(); } else { recycle.setLength(0); } Formatter formatter = new Formatter(recycle); return DateUtils.formatDateRange(context, formatter, blockStart, blockEnd, TIME_FLAGS, PrefUtils.getDisplayTimeZone(context).getID()).toString(); } public static boolean isSameDayDisplay(long time1, long time2, Context context) { TimeZone displayTimeZone = PrefUtils.getDisplayTimeZone(context); Calendar cal1 = Calendar.getInstance(displayTimeZone); Calendar cal2 = Calendar.getInstance(displayTimeZone); cal1.setTimeInMillis(time1); cal2.setTimeInMillis(time2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); } /** * Populate the given {@link TextView} with the requested text, formatting * through {@link Html#fromHtml(String)} when applicable. Also sets * {@link TextView#setMovementMethod} so inline links are handled. */ public static void setTextMaybeHtml(TextView view, String text) { if (TextUtils.isEmpty(text)) { view.setText(""); return; } if ((text.contains("<") && text.contains(">")) || REGEX_HTML_ESCAPE.matcher(text).find()) { view.setText(Html.fromHtml(text)); view.setMovementMethod(LinkMovementMethod.getInstance()); } else { view.setText(text); } } public static void updateTimeAndLivestreamBlockUI(final Context context, long blockStart, long blockEnd, boolean hasLivestream, TextView titleView, TextView subtitleView, CharSequence subtitle) { long currentTimeMillis = getCurrentTime(context); boolean conferenceEnded = currentTimeMillis > CONFERENCE_END_MILLIS; boolean blockEnded = currentTimeMillis > blockEnd; boolean blockNow = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd); if (titleView != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { titleView.setTypeface(Typeface.create((blockEnded && !conferenceEnded) ? "sans-serif-light" : "sans-serif", Typeface.NORMAL)); } else { titleView.setTypeface(Typeface.SANS_SERIF, (blockEnded && !conferenceEnded) ? Typeface.NORMAL : Typeface.BOLD); } } if (subtitleView != null) { boolean empty = true; SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle if (subtitle != null) { sb.append(subtitle); empty = false; } if (blockNow) { if (sNowPlayingText == null) { sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge)); } if (!empty) { sb.append(" "); } sb.append(sNowPlayingText); if (hasLivestream) { if (sLivestreamNowText == null) { sLivestreamNowText = Html.fromHtml("&nbsp;&nbsp;" + context.getString(R.string.live_now_badge)); } sb.append(sLivestreamNowText); } } else if (hasLivestream) { if (sLivestreamAvailableText == null) { sLivestreamAvailableText = Html.fromHtml( context.getString(R.string.live_available_badge)); } if (!empty) { sb.append(" "); } sb.append(sLivestreamAvailableText); } subtitleView.setText(sb); } } /** * Given a snippet string with matching segments surrounded by curly * braces, turn those areas into bold spans, removing the curly braces. */ public static Spannable buildStyledSnippet(String snippet) { final SpannableStringBuilder builder = new SpannableStringBuilder(snippet); // Walk through string, inserting bold snippet spans int startIndex, endIndex = -1, delta = 0; while ((startIndex = snippet.indexOf('{', endIndex)) != -1) { endIndex = snippet.indexOf('}', startIndex); // Remove braces from both sides builder.delete(startIndex - delta, startIndex - delta + 1); builder.delete(endIndex - delta - 1, endIndex - delta); // Insert bold style builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(sColorSpan, startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); delta += 2; } return builder; } public static void preferPackageForIntent(Context context, Intent intent, String packageName) { PackageManager pm = context.getPackageManager(); for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) { if (resolveInfo.activityInfo.packageName.equals(packageName)) { intent.setPackage(packageName); break; } } } public static String getSessionHashtagsString(String hashtags) { if (!TextUtils.isEmpty(hashtags)) { if (!hashtags.startsWith("#")) { hashtags = "#" + hashtags; } if (hashtags.contains(CONFERENCE_HASHTAG)) { return hashtags; } return CONFERENCE_HASHTAG + " " + hashtags; } else { return CONFERENCE_HASHTAG; } } private static final int BRIGHTNESS_THRESHOLD = 130; /** * Calculate whether a color is light or dark, based on a commonly known * brightness formula. * * @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness} */ public static boolean isColorDark(int color) { return ((30 * Color.red(color) + 59 * Color.green(color) + 11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD; } /** * Create the track icon bitmap. Don't call this directly, instead use either * {@link UIUtils.TrackIconAsyncTask} or {@link UIUtils.TrackIconViewAsyncTask} to * asynchronously load the track icon. */ private static Bitmap createTrackIcon(Context context, String trackName, int trackColor) { final Resources res = context.getResources(); int iconSize = res.getDimensionPixelSize(R.dimen.track_icon_source_size); Bitmap icon = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(trackColor); canvas.drawCircle(iconSize / 2, iconSize / 2, iconSize / 2, paint); int iconResId = res.getIdentifier( "track_" + ParserUtils.sanitizeId(trackName), "drawable", context.getPackageName()); if (iconResId != 0) { Drawable sourceIconDrawable = res.getDrawable(iconResId); sourceIconDrawable.setBounds(0, 0, iconSize, iconSize); sourceIconDrawable.draw(canvas); } return icon; } /** * Synchronously get the track icon bitmap. Don't call this from the main thread, instead use either * {@link UIUtils.TrackIconAsyncTask} or {@link UIUtils.TrackIconViewAsyncTask} to * asynchronously load the track icon. */ public static Bitmap getTrackIconSync(Context ctx, String trackName, int trackColor) { if (TextUtils.isEmpty(trackName)) { return null; } // Find a suitable disk cache directory for the track icons and create if it doesn't // already exist. File outputDir = ImageLoader.getDiskCacheDir(ctx, TRACK_ICONS_TAG); if (!outputDir.exists()) { outputDir.mkdirs(); } // Generate a unique filename to store this track icon in using a hash function. File imageFile = new File(outputDir + File.separator + hashKeyForDisk(trackName)); Bitmap bitmap = null; // If file already exists and is readable, try and decode the bitmap from the disk. if (imageFile.exists() && imageFile.canRead()) { bitmap = BitmapFactory.decodeFile(imageFile.toString()); } // If bitmap is still null here the track icon was not found in the disk cache. if (bitmap == null) { // Create the icon using the provided track name and color. bitmap = UIUtils.createTrackIcon(ctx, trackName, trackColor); // Now write it out to disk for future use. BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(imageFile)); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); } catch (FileNotFoundException e) { LOGE(TAG, "TrackIconAsyncTask - unable to open file - " + e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ignored) { } } } } return bitmap; } /** * A hashing method that changes a string (like a URL) into a hash suitable for using as a * disk filename. */ private static String hashKeyForDisk(String key) { String cacheKey; try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(key.getBytes()); cacheKey = bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { cacheKey = String.valueOf(key.hashCode()); } return cacheKey; } private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } /** * A subclass of {@link TrackIconAsyncTask} that loads the generated track icon bitmap into * the provided {@link ImageView}. This class also handles concurrency in the case the * ImageView is recycled (eg. in a ListView adapter) so that the incorrect image will not show * in a recycled view. */ public static class TrackIconViewAsyncTask extends TrackIconAsyncTask { private WeakReference<ImageView> mImageViewReference; public TrackIconViewAsyncTask(ImageView imageView, String trackName, int trackColor, BitmapCache bitmapCache) { super(trackName, trackColor, bitmapCache); // Store this AsyncTask in the tag of the ImageView so we can compare if the same task // is still running on this ImageView once processing is complete. This helps with // view recycling that takes place in a ListView type adapter. imageView.setTag(this); // If we have a BitmapCache, check if this track icon is available already. Bitmap bitmap = bitmapCache != null ? bitmapCache.getBitmapFromMemCache(trackName) : null; // If found in BitmapCache set the Bitmap directly and cancel the task. if (bitmap != null) { imageView.setImageBitmap(bitmap); cancel(true); } else { // Otherwise clear the ImageView and store a WeakReference for later use. Better // to use a WeakReference here in case the task runs long and the holding Activity // or Fragment goes away. imageView.setImageDrawable(null); mImageViewReference = new WeakReference<ImageView>(imageView); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override protected void onPostExecute(Bitmap bitmap) { ImageView imageView = mImageViewReference != null ? mImageViewReference.get() : null; // If ImageView is still around, bitmap processed OK and this task is not canceled. if (imageView != null && bitmap != null && !isCancelled()) { // Ensure this task is still the same one assigned to this ImageView, if not the // view was likely recycled and a new task with a different icon is now running // on the view and we shouldn't proceed. if (this.equals(imageView.getTag())) { // On HC-MR1 run a quick fade-in animation. if (hasHoneycombMR1()) { imageView.setAlpha(0f); imageView.setImageBitmap(bitmap); imageView.animate() .alpha(1f) .setDuration(ANIMATION_FADE_IN_TIME) .setListener(null); } else { // Before HC-MR1 set the Bitmap directly. imageView.setImageBitmap(bitmap); } } } } } /** * Asynchronously load the track icon bitmap. To use, subclass and override * {@link #onPostExecute(android.graphics.Bitmap)} which passes in the generated track icon * bitmap. */ public static abstract class TrackIconAsyncTask extends AsyncTask<Context, Void, Bitmap> { private String mTrackName; private int mTrackColor; private BitmapCache mBitmapCache; public TrackIconAsyncTask(String trackName, int trackColor) { mTrackName = trackName; mTrackColor = trackColor; } public TrackIconAsyncTask(String trackName, int trackColor, BitmapCache bitmapCache) { mTrackName = trackName; mTrackColor = trackColor; mBitmapCache = bitmapCache; } @Override protected Bitmap doInBackground(Context... contexts) { Bitmap bitmap = getTrackIconSync(contexts[0], mTrackName, mTrackColor); // Store bitmap in memory cache for future use. if (bitmap != null && mBitmapCache != null) { mBitmapCache.addBitmapToCache(mTrackName, bitmap); } return bitmap; } protected abstract void onPostExecute(Bitmap bitmap); } public static boolean hasHoneycomb() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean hasHoneycombMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; } public static boolean hasICS() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; } public static boolean hasJellyBeanMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static boolean isHoneycombTablet(Context context) { return hasHoneycomb() && isTablet(context); } // Shows whether a notification was fired for a particular session time block. In the // event that notification has not been fired yet, return false and set the bit. public static boolean isNotificationFiredForBlock(Context context, String blockId) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); final String key = String.format("notification_fired_%s", blockId); boolean fired = sp.getBoolean(key, false); sp.edit().putBoolean(key, true).commit(); return fired; } private static final long sAppLoadTime = System.currentTimeMillis(); public static long getCurrentTime(final Context context) { if (BuildConfig.DEBUG) { return context.getSharedPreferences("mock_data", Context.MODE_PRIVATE) .getLong("mock_current_time", System.currentTimeMillis()) + System.currentTimeMillis() - sAppLoadTime; // return ParserUtils.parseTime("2012-06-27T09:44:45.000-07:00") // + System.currentTimeMillis() - sAppLoadTime; } else { return System.currentTimeMillis(); } } public static boolean shouldShowLiveSessionsOnly(final Context context) { return !PrefUtils.isAttendeeAtVenue(context) && getCurrentTime(context) < CONFERENCE_END_MILLIS; } /** * Enables and disables {@linkplain android.app.Activity activities} based on their * {@link #TARGET_FORM_FACTOR_ACTIVITY_METADATA}" meta-data and the current device. * Values should be either "handset", "tablet", or not present (meaning universal). * <p> * <a href="http://stackoverflow.com/questions/13202805">Original code</a> by Dandre Allison. * @param context the current context of the device * @see #isHoneycombTablet(android.content.Context) */ public static void enableDisableActivitiesByFormFactor(Context context) { final PackageManager pm = context.getPackageManager(); boolean isTablet = isHoneycombTablet(context); try { PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA); if (pi == null) { LOGE(TAG, "No package info found for our own package."); return; } final ActivityInfo[] activityInfos = pi.activities; for (ActivityInfo info : activityInfos) { String targetDevice = null; if (info.metaData != null) { targetDevice = info.metaData.getString(TARGET_FORM_FACTOR_ACTIVITY_METADATA); } boolean tabletActivity = TARGET_FORM_FACTOR_TABLET.equals(targetDevice); boolean handsetActivity = TARGET_FORM_FACTOR_HANDSET.equals(targetDevice); boolean enable = !(handsetActivity && isTablet) && !(tabletActivity && !isTablet); String className = info.name; pm.setComponentEnabledSetting( new ComponentName(context, Class.forName(className)), enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } catch (PackageManager.NameNotFoundException e) { LOGE(TAG, "No package info found for our own package.", e); } catch (ClassNotFoundException e) { LOGE(TAG, "Activity not found within package.", e); } } public static Class getMapActivityClass(Context context) { if (UIUtils.isHoneycombTablet(context)) { return MapMultiPaneActivity.class; } return MapActivity.class; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void setActivatedCompat(View view, boolean activated) { if (hasHoneycomb()) { view.setActivated(activated); } } /** * If an activity's intent is for a Google I/O web URL that the app can handle * natively, this method translates the intent to the equivalent native intent. */ public static void tryTranslateHttpIntent(Activity activity) { Intent intent = activity.getIntent(); if (intent == null) { return; } Uri uri = intent.getData(); if (uri == null || TextUtils.isEmpty(uri.getPath())) { return; } String prefixPath = SESSION_DETAIL_WEB_URL_PREFIX.getPath(); String path = uri.getPath(); if (SESSION_DETAIL_WEB_URL_PREFIX.getScheme().equals(uri.getScheme()) && SESSION_DETAIL_WEB_URL_PREFIX.getHost().equals(uri.getHost()) && path.startsWith(prefixPath)) { String sessionId = path.substring(prefixPath.length()); activity.setIntent(new Intent( Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); } } /** * The Conference API image URLs can be absolute or relative. In the case they are relative * we should prepend the main Conference URL. * @param imageUrl A Conference API image URL * @return An absolute image URL */ public static String getConferenceImageUrl(String imageUrl) { if (!TextUtils.isEmpty(imageUrl) && !imageUrl.startsWith("http")) { return Config.CONFERENCE_IMAGE_PREFIX_URL + imageUrl; } return imageUrl; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/UIUtils.java
Java
asf20
28,040
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import com.google.android.apps.iosched.gcm.ServerUtilities; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.AccountActivity; import com.google.android.gms.auth.*; import com.google.android.gms.common.Scopes; import java.io.IOException; import static com.google.android.apps.iosched.util.LogUtils.*; public class AccountUtils { private static final String TAG = makeLogTag(AccountUtils.class); private static final String PREF_CHOSEN_ACCOUNT = "chosen_account"; private static final String PREF_AUTH_TOKEN = "auth_token"; private static final String PREF_PLUS_PROFILE_ID = "plus_profile_id"; public static final String AUTH_SCOPES[] = { Scopes.PLUS_LOGIN, "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/developerssite" }; static final String AUTH_TOKEN_TYPE; static { StringBuilder sb = new StringBuilder(); sb.append("oauth2:"); for (String scope : AUTH_SCOPES) { sb.append(scope); sb.append(" "); } AUTH_TOKEN_TYPE = sb.toString(); } public static boolean isAuthenticated(final Context context) { return !TextUtils.isEmpty(getChosenAccountName(context)); } public static String getChosenAccountName(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(PREF_CHOSEN_ACCOUNT, null); } public static Account getChosenAccount(final Context context) { String account = getChosenAccountName(context); if (account != null) { return new Account(account, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); } else { return null; } } static void setChosenAccountName(final Context context, final String accountName) { LOGD(TAG, "Chose account " + accountName); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_CHOSEN_ACCOUNT, accountName).commit(); } public static String getAuthToken(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(PREF_AUTH_TOKEN, null); } private static void setAuthToken(final Context context, final String authToken) { LOGI(TAG, "Auth token of length " + (TextUtils.isEmpty(authToken) ? 0 : authToken.length())); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_AUTH_TOKEN, authToken).commit(); LOGD(TAG, "Auth Token: " + authToken); } static void invalidateAuthToken(final Context context) { GoogleAuthUtil.invalidateToken(context, getAuthToken(context)); setAuthToken(context, null); } public static void setPlusProfileId(final Context context, final String profileId) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_PLUS_PROFILE_ID, profileId).commit(); } public static String getPlusProfileId(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(PREF_PLUS_PROFILE_ID, null); } public static void refreshAuthToken(Context mContext) { invalidateAuthToken(mContext); tryAuthenticateWithErrorNotification(mContext, ScheduleContract.CONTENT_AUTHORITY, getChosenAccountName(mContext)); } public static interface AuthenticateCallback { public boolean shouldCancelAuthentication(); public void onAuthTokenAvailable(); public void onRecoverableException(final int code); public void onUnRecoverableException(final String errorMessage); } static void tryAuthenticateWithErrorNotification(Context context, String syncAuthority, String accountName) { try { LOGI(TAG, "Requesting new auth token (with notification)"); final String token = GoogleAuthUtil.getTokenWithNotification(context, accountName, AUTH_TOKEN_TYPE, null, syncAuthority, null); setAuthToken(context, token); setChosenAccountName(context, accountName); } catch (UserRecoverableNotifiedException e) { // Notification has already been pushed. LOGW(TAG, "User recoverable exception. Check notification.", e); } catch (GoogleAuthException e) { // This is likely unrecoverable. LOGE(TAG, "Unrecoverable authentication exception: " + e.getMessage(), e); } catch (IOException e) { LOGE(TAG, "transient error encountered: " + e.getMessage()); } } public static void tryAuthenticate(final Activity activity, final AuthenticateCallback callback, final String accountName, final int requestCode) { (new GetTokenTask(activity, callback, accountName, requestCode)).execute(); } private static class GetTokenTask extends AsyncTask <Void, Void, String> { private String mAccountName; private Activity mActivity; private AuthenticateCallback mCallback; private int mRequestCode; public GetTokenTask(Activity activity, AuthenticateCallback callback, String name, int requestCode) { mAccountName = name; mActivity = activity; mCallback = callback; mRequestCode = requestCode; } @Override protected String doInBackground(Void... params) { try { if (mCallback.shouldCancelAuthentication()) return null; final String token = GoogleAuthUtil.getToken(mActivity, mAccountName, AUTH_TOKEN_TYPE); // Persists auth token. setAuthToken(mActivity, token); setChosenAccountName(mActivity, mAccountName); return token; } catch (GooglePlayServicesAvailabilityException e) { mCallback.onRecoverableException(e.getConnectionStatusCode()); } catch (UserRecoverableAuthException e) { mActivity.startActivityForResult(e.getIntent(), mRequestCode); } catch (IOException e) { LOGE(TAG, "transient error encountered: " + e.getMessage()); mCallback.onUnRecoverableException(e.getMessage()); } catch (GoogleAuthException e) { LOGE(TAG, "transient error encountered: " + e.getMessage()); mCallback.onUnRecoverableException(e.getMessage()); } catch (RuntimeException e) { LOGE(TAG, "Error encountered: " + e.getMessage()); mCallback.onUnRecoverableException(e.getMessage()); } return null; } @Override protected void onPostExecute(String token) { super.onPostExecute(token); mCallback.onAuthTokenAvailable(); } } public static void signOut(final Context context) { // Sign out of GCM message router ServerUtilities.onSignOut(context); // Destroy auth tokens invalidateAuthToken(context); // Remove remaining application state SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().clear().commit(); context.getContentResolver().delete(ScheduleContract.BASE_CONTENT_URI, null, null); } public static void startAuthenticationFlow(final Context context, final Intent finishIntent) { Intent loginFlowIntent = new Intent(context, AccountActivity.class); loginFlowIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); loginFlowIntent.putExtra(AccountActivity.EXTRA_FINISH_INTENT, finishIntent); context.startActivity(loginFlowIntent); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/AccountUtils.java
Java
asf20
9,099
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.util.LruCache; import com.android.volley.toolbox.ImageLoader; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This class holds our bitmap caches (memory and disk). */ public class BitmapCache implements ImageLoader.ImageCache { private static final String TAG = makeLogTag(BitmapCache.class); // Default memory cache size as a percent of device memory class private static final float DEFAULT_MEM_CACHE_PERCENT = 0.15f; private LruCache<String, Bitmap> mMemoryCache; /** * Don't instantiate this class directly, use * {@link #getInstance(android.support.v4.app.FragmentManager, float)}. * @param memCacheSize Memory cache size in KB. */ private BitmapCache(int memCacheSize) { init(memCacheSize); } /** * Find and return an existing BitmapCache stored in a {@link RetainFragment}, if not found a * new one is created using the supplied params and saved to a {@link RetainFragment}. * * @param fragmentManager The fragment manager to use when dealing with the retained fragment. * @param fragmentTag The tag of the retained fragment (should be unique for each memory cache * that needs to be retained). * @param memCacheSize Memory cache size in KB. */ public static BitmapCache getInstance(FragmentManager fragmentManager, String fragmentTag, int memCacheSize) { BitmapCache bitmapCache = null; RetainFragment mRetainFragment = null; if (fragmentManager != null) { // Search for, or create an instance of the non-UI RetainFragment mRetainFragment = getRetainFragment(fragmentManager, fragmentTag); // See if we already have a BitmapCache stored in RetainFragment bitmapCache = (BitmapCache) mRetainFragment.getObject(); } // No existing BitmapCache, create one and store it in RetainFragment if (bitmapCache == null) { bitmapCache = new BitmapCache(memCacheSize); if (mRetainFragment != null) { mRetainFragment.setObject(bitmapCache); } } return bitmapCache; } public static BitmapCache getInstance(FragmentManager fragmentManager, int memCacheSize) { return getInstance(fragmentManager, TAG, memCacheSize); } public static BitmapCache getInstance(FragmentManager fragmentManager, float memCachePercent) { return getInstance(fragmentManager, calculateMemCacheSize(memCachePercent)); } public static BitmapCache getInstance(FragmentManager fragmentManger) { return getInstance(fragmentManger, DEFAULT_MEM_CACHE_PERCENT); } /** * Initialize the cache. */ private void init(int memCacheSize) { // Set up memory cache LOGD(TAG, "Memory cache created (size = " + memCacheSize + "KB)"); mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) { /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, Bitmap bitmap) { final int bitmapSize = getBitmapSize(bitmap) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } /** * Adds a bitmap to both memory and disk cache. * @param data Unique identifier for the bitmap to store * @param bitmap The bitmap to store */ public void addBitmapToCache(String data, Bitmap bitmap) { if (data == null || bitmap == null) { return; } synchronized (mMemoryCache) { // Add to memory cache if (mMemoryCache.get(data) == null) { LOGD(TAG, "Memory cache put - " + data); mMemoryCache.put(data, bitmap); } } } /** * Get from memory cache. * * @param data Unique identifier for which item to get * @return The bitmap if found in cache, null otherwise */ public Bitmap getBitmapFromMemCache(String data) { if (data != null) { synchronized (mMemoryCache) { final Bitmap memBitmap = mMemoryCache.get(data); if (memBitmap != null) { LOGD(TAG, "Memory cache hit - " + data); return memBitmap; } } LOGD(TAG, "Memory cache miss - " + data); } return null; } /** * Clears the memory cache. */ public void clearCache() { if (mMemoryCache != null) { mMemoryCache.evictAll(); LOGD(TAG, "Memory cache cleared"); } } /** * Sets the memory cache size based on a percentage of the max available VM memory. * Eg. setting percent to 0.2 would set the memory cache to one fifth of the available * memory. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8. * memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed * to construct a LruCache which takes an int in its constructor. * * This value should be chosen carefully based on a number of factors * Refer to the corresponding Android Training class for more discussion: * http://developer.android.com/training/displaying-bitmaps/ * * @param percent Percent of memory class to use to size memory cache * @return Memory cache size in KB */ public static int calculateMemCacheSize(float percent) { if (percent < 0.05f || percent > 0.8f) { throw new IllegalArgumentException("setMemCacheSizePercent - percent must be " + "between 0.05 and 0.8 (inclusive)"); } return Math.round(percent * Runtime.getRuntime().maxMemory() / 1024); } /** * Get the size in bytes of a bitmap. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) public static int getBitmapSize(Bitmap bitmap) { if (UIUtils.hasHoneycombMR1()) { return bitmap.getByteCount(); } // Pre HC-MR1 return bitmap.getRowBytes() * bitmap.getHeight(); } /** * Locate an existing instance of this Fragment or if not found, create and * add it using FragmentManager. * * @param fm The FragmentManager manager to use. * @param fragmentTag The tag of the retained fragment (should be unique for each memory * cache that needs to be retained). * @return The existing instance of the Fragment or the new instance if just * created. */ private static RetainFragment getRetainFragment(FragmentManager fm, String fragmentTag) { // Check to see if we have retained the worker fragment. RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(fragmentTag); // If not retained (or first time running), we need to create and add it. if (mRetainFragment == null) { mRetainFragment = new RetainFragment(); fm.beginTransaction().add(mRetainFragment, fragmentTag).commitAllowingStateLoss(); } return mRetainFragment; } @Override public Bitmap getBitmap(String key) { return getBitmapFromMemCache(key); } @Override public void putBitmap(String key, Bitmap bitmap) { addBitmapToCache(key, bitmap); } /** * A simple non-UI Fragment that stores a single Object and is retained over configuration * changes. It will be used to retain the BitmapCache object. */ public static class RetainFragment extends Fragment { private Object mObject; /** * Empty constructor as per the Fragment documentation */ public RetainFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Make sure this Fragment is retained over a configuration change setRetainInstance(true); } /** * Store a single object in this Fragment. * * @param object The object to store */ public void setObject(Object object) { mObject = object; } /** * Get the stored object. * * @return The stored object */ public Object getObject() { return mObject; } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/BitmapCache.java
Java
asf20
9,508
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.Context; public class TimeUtils { private static final int SECOND = 1000; private static final int MINUTE = 60 * SECOND; private static final int HOUR = 60 * MINUTE; private static final int DAY = 24 * HOUR; public static String getTimeAgo(long time, Context ctx) { // TODO: use DateUtils methods instead if (time < 1000000000000L) { // if timestamp given in seconds, convert to millis time *= 1000; } long now = UIUtils.getCurrentTime(ctx); if (time > now || time <= 0) { return null; } final long diff = now - time; if (diff < MINUTE) { return "just now"; } else if (diff < 2 * MINUTE) { return "a minute ago"; } else if (diff < 50 * MINUTE) { return diff / MINUTE + " minutes ago"; } else if (diff < 90 * MINUTE) { return "an hour ago"; } else if (diff < 24 * HOUR) { return diff / HOUR + " hours ago"; } else if (diff < 48 * HOUR) { return "yesterday"; } else { return diff / DAY + " days ago"; } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/TimeUtils.java
Java
asf20
1,842
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class WiFiUtils { // Preference key and values associated with WiFi AP configuration. public static final String PREF_WIFI_AP_CONFIG = "pref_wifi_ap_config"; public static final String WIFI_CONFIG_DONE = "done"; public static final String WIFI_CONFIG_REQUESTED = "requested"; private static final String TAG = makeLogTag(WiFiUtils.class); public static void installConferenceWiFi(final Context context) { // Create config WifiConfiguration config = new WifiConfiguration(); // Must be in double quotes to tell system this is an ASCII SSID and passphrase. config.SSID = String.format("\"%s\"", Config.WIFI_SSID); config.preSharedKey = String.format("\"%s\"", Config.WIFI_PASSPHRASE); // Store config final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int netId = wifiManager.addNetwork(config); if (netId != -1) { wifiManager.enableNetwork(netId, false); boolean result = wifiManager.saveConfiguration(); if (!result) { Log.e(TAG, "Unknown error while calling WiFiManager.saveConfiguration()"); Toast.makeText(context, context.getResources().getString(R.string.wifi_install_error_message), Toast.LENGTH_SHORT).show(); } } else { Log.e(TAG, "Unknown error while calling WiFiManager.addNetwork()"); Toast.makeText(context, context.getResources().getString(R.string.wifi_install_error_message), Toast.LENGTH_SHORT).show(); } } /** * Helper method to decide whether to bypass conference WiFi setup. Return true if * WiFi AP is already configured (WiFi adapter enabled) or WiFi configuration is complete * as per shared preference. */ public static boolean shouldBypassWiFiSetup(final Context context) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // Is WiFi on? if (wifiManager.isWifiEnabled()) { // Check for existing APs. final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID); for(WifiConfiguration config : configs) { if (conferenceSSID.equalsIgnoreCase(config.SSID)) return true; } } return WIFI_CONFIG_DONE.equals(getWiFiConfigStatus(context)); } public static boolean isWiFiEnabled(final Context context) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.isWifiEnabled(); } public static boolean isWiFiApConfigured(final Context context) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); if (configs == null) return false; // Check for existing APs. final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID); for(WifiConfiguration config : configs) { if (conferenceSSID.equalsIgnoreCase(config.SSID)) return true; } return false; } // Stored preferences associated with WiFi AP configuration. public static String getWiFiConfigStatus(final Context context) { final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(PREF_WIFI_AP_CONFIG, null); } public static void setWiFiConfigStatus(final Context context, final String status) { if (!WIFI_CONFIG_DONE.equals(status) && !WIFI_CONFIG_REQUESTED.equals(status)) throw new IllegalArgumentException("Invalid WiFi Config status: " + status); final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_WIFI_AP_CONFIG, status).commit(); } public static boolean installWiFiIfRequested(final Context context) { if (WIFI_CONFIG_REQUESTED.equals(getWiFiConfigStatus(context)) && isWiFiEnabled(context)) { installConferenceWiFi(context); if (isWiFiApConfigured(context)) { setWiFiConfigStatus(context, WiFiUtils.WIFI_CONFIG_DONE); return true; } } return false; } public static void showWiFiDialog(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_wifi"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new WiFiDialog(isWiFiEnabled(activity)).show(ft, "dialog_wifi"); } public static class WiFiDialog extends DialogFragment { private boolean mWiFiEnabled; public WiFiDialog() {} public WiFiDialog(boolean wifiEnabled) { super(); mWiFiEnabled = wifiEnabled; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal); final TextView wifiTextView = new TextView(getActivity()); int dialogCallToActionText; int dialogPositiveButtonText; if (mWiFiEnabled) { dialogCallToActionText = R.string.calltoaction_wifi_configure; dialogPositiveButtonText = R.string.wifi_dialog_button_configure; } else { dialogCallToActionText = R.string.calltoaction_wifi_settings; dialogPositiveButtonText = R.string.wifi_dialog_button_settings; } wifiTextView.setText(Html.fromHtml(getString(R.string.description_setup_wifi_body) + getString(dialogCallToActionText))); wifiTextView.setMovementMethod(LinkMovementMethod.getInstance()); wifiTextView.setPadding(padding, padding, padding, padding); final Context context = getActivity(); return new AlertDialog.Builder(context) .setTitle(R.string.description_configure_wifi) .setView(wifiTextView) .setPositiveButton(dialogPositiveButtonText, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Attempt to configure the Wi-Fi access point. if (mWiFiEnabled) { installConferenceWiFi(context); if (WiFiUtils.isWiFiApConfigured(context)) { WiFiUtils.setWiFiConfigStatus( context, WiFiUtils.WIFI_CONFIG_DONE); } // Launch Wi-Fi settings screen for user to enable Wi-Fi. } else { WiFiUtils.setWiFiConfigStatus(context, WiFiUtils.WIFI_CONFIG_REQUESTED); final Intent wifiIntent = new Intent(Settings.ACTION_WIFI_SETTINGS); wifiIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(wifiIntent); } dialog.dismiss(); } } ) .create(); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/WiFiUtils.java
Java
asf20
9,866
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.provider.ScheduleContract; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Build; import android.os.Parcelable; import android.preference.PreferenceManager; /** * Android Beam helper methods. */ public class BeamUtils { /** * Sets this activity's Android Beam message to one representing the given session. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void setBeamSessionUri(Activity activity, Uri sessionUri) { if (UIUtils.hasICS()) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter == null) { // No NFC :-( return; } nfcAdapter.setNdefPushMessage(new NdefMessage( new NdefRecord[]{ new NdefRecord(NdefRecord.TNF_MIME_MEDIA, ScheduleContract.Sessions.CONTENT_ITEM_TYPE.getBytes(), new byte[0], sessionUri.toString().getBytes()) }), activity); } } /** * Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is * an NFC intent that the app recognizes. If it is, then parse the NFC message and set the * activity's intent (using {@link Activity#setIntent(android.content.Intent)}) to something * the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent). */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void tryUpdateIntentFromBeam(Activity activity) { if (UIUtils.hasICS()) { Intent originalIntent = activity.getIntent(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) { Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; // Record 0 contains the MIME type, record 1 is the AAR, if present. // In iosched, AARs are not present. NdefRecord mimeRecord = msg.getRecords()[0]; if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals( new String(mimeRecord.getType()))) { // Re-set the activity's intent to one that represents session details. Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(new String(mimeRecord.getPayload()))); activity.setIntent(sessionDetailIntent); } } } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/BeamUtils.java
Java
asf20
3,617
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.net.http.AndroidHttpClient; import android.os.Build; import android.os.Environment; import android.support.v4.app.FragmentActivity; import android.widget.ImageView; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.VolleyError; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HttpClientStack; import com.android.volley.toolbox.HurlStack; import java.io.File; import java.util.ArrayList; /** * A class that wraps up remote image loading requests using the Volley library combined with a * memory cache. An single instance of this class should be created once when your Activity or * Fragment is created, then use {@link #get(String, android.widget.ImageView)} or one of * the variations to queue the image to be fetched and loaded from the network. Loading images * in a {@link android.widget.ListView} or {@link android.widget.GridView} is also supported but * you must store the {@link com.android.volley.Request} in your ViewHolder type class and pass it * into loadImage to ensure the request is canceled as views are recycled. */ public class ImageLoader extends com.android.volley.toolbox.ImageLoader { private static final ColorDrawable transparentDrawable = new ColorDrawable( android.R.color.transparent); private static final int HALF_FADE_IN_TIME = UIUtils.ANIMATION_FADE_IN_TIME / 2; private static final String CACHE_DIR = "images"; private Resources mResources; private ArrayList<Drawable> mPlaceHolderDrawables; private boolean mFadeInImage = true; private int mMaxImageHeight = 0; private int mMaxImageWidth = 0; /** * Creates an ImageLoader with Bitmap memory cache. No default placeholder image will be shown * while the image is being fetched and loaded. */ public ImageLoader(FragmentActivity activity) { super(newRequestQueue(activity), BitmapCache.getInstance(activity.getSupportFragmentManager())); mResources = activity.getResources(); } /** * Creates an ImageLoader with Bitmap memory cache and a default placeholder image while the * image is being fetched and loaded. */ public ImageLoader(FragmentActivity activity, int defaultPlaceHolderResId) { super(newRequestQueue(activity), BitmapCache.getInstance(activity.getSupportFragmentManager())); mResources = activity.getResources(); mPlaceHolderDrawables = new ArrayList<Drawable>(1); mPlaceHolderDrawables.add(defaultPlaceHolderResId == -1 ? null : mResources.getDrawable(defaultPlaceHolderResId)); } /** * Creates an ImageLoader with Bitmap memory cache and a list of default placeholder drawables. */ public ImageLoader(FragmentActivity activity, ArrayList<Drawable> placeHolderDrawables) { super(newRequestQueue(activity), BitmapCache.getInstance(activity.getSupportFragmentManager())); mResources = activity.getResources(); mPlaceHolderDrawables = placeHolderDrawables; } /** * Starts processing requests on the {@link RequestQueue}. */ public void startProcessingQueue() { getRequestQueue().start(); } /** * Stops processing requests on the {@link RequestQueue}. */ public void stopProcessingQueue() { getRequestQueue().stop(); } public ImageLoader setFadeInImage(boolean fadeInImage) { mFadeInImage = fadeInImage; return this; } public ImageLoader setMaxImageSize(int maxImageWidth, int maxImageHeight) { mMaxImageWidth = maxImageWidth; mMaxImageHeight = maxImageHeight; return this; } public ImageLoader setMaxImageSize(int maxImageSize) { return setMaxImageSize(maxImageSize, maxImageSize); } public ImageContainer get(String requestUrl, ImageView imageView) { return get(requestUrl, imageView, 0); } public ImageContainer get(String requestUrl, ImageView imageView, int placeHolderIndex) { return get(requestUrl, imageView, mPlaceHolderDrawables.get(placeHolderIndex), mMaxImageWidth, mMaxImageHeight); } public ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder) { return get(requestUrl, imageView, placeHolder, mMaxImageWidth, mMaxImageHeight); } public ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder, int maxWidth, int maxHeight) { // Find any old image load request pending on this ImageView (in case this view was // recycled) ImageContainer imageContainer = imageView.getTag() != null && imageView.getTag() instanceof ImageContainer ? (ImageContainer) imageView.getTag() : null; // Find image url from prior request String recycledImageUrl = imageContainer != null ? imageContainer.getRequestUrl() : null; // If the new requestUrl is null or the new requestUrl is different to the previous // recycled requestUrl if (requestUrl == null || !requestUrl.equals(recycledImageUrl)) { if (imageContainer != null) { // Cancel previous image request imageContainer.cancelRequest(); imageView.setTag(null); } if (requestUrl != null) { // Queue new request to fetch image imageContainer = get(requestUrl, getImageListener(mResources, imageView, placeHolder, mFadeInImage), maxWidth, maxHeight); // Store request in ImageView tag imageView.setTag(imageContainer); } else { imageView.setImageDrawable(placeHolder); imageView.setTag(null); } } return imageContainer; } private static ImageListener getImageListener(final Resources resources, final ImageView imageView, final Drawable placeHolder, final boolean fadeInImage) { return new ImageListener() { @Override public void onResponse(ImageContainer response, boolean isImmediate) { imageView.setTag(null); if (response.getBitmap() != null) { setImageBitmap(imageView, response.getBitmap(), resources, fadeInImage && !isImmediate); } else { imageView.setImageDrawable(placeHolder); } } @Override public void onErrorResponse(VolleyError volleyError) { } }; } private static RequestQueue newRequestQueue(Context context) { // On HC+ use HurlStack which is based on HttpURLConnection. Otherwise fall back on // AndroidHttpClient (based on Apache DefaultHttpClient) which should no longer be used // on newer platform versions where HttpURLConnection is simply better. Network network = new BasicNetwork( UIUtils.hasHoneycomb() ? new HurlStack() : new HttpClientStack(AndroidHttpClient.newInstance( NetUtils.getUserAgent(context)))); Cache cache = new DiskBasedCache(getDiskCacheDir(context, CACHE_DIR)); RequestQueue queue = new RequestQueue(cache, network); queue.start(); return queue; } /** * Sets a {@link android.graphics.Bitmap} to an {@link android.widget.ImageView} using a * fade-in animation. If there is a {@link android.graphics.drawable.Drawable} already set on * the ImageView then use that as the image to fade from. Otherwise fade in from a transparent * Drawable. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) private static void setImageBitmap(final ImageView imageView, final Bitmap bitmap, Resources resources, boolean fadeIn) { // If we're fading in and on HC MR1+ if (fadeIn && UIUtils.hasHoneycombMR1()) { // Use ViewPropertyAnimator to run a simple fade in + fade out animation to update the // ImageView imageView.animate() .scaleY(0.95f) .scaleX(0.95f) .alpha(0f) .setDuration(imageView.getDrawable() == null ? 0 : HALF_FADE_IN_TIME) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { imageView.setImageBitmap(bitmap); imageView.animate() .alpha(1f) .scaleY(1f) .scaleX(1f) .setDuration(HALF_FADE_IN_TIME) .setListener(null); } }); } else if (fadeIn) { // Otherwise use a TransitionDrawable to fade in Drawable initialDrawable; if (imageView.getDrawable() != null) { initialDrawable = imageView.getDrawable(); } else { initialDrawable = transparentDrawable; } BitmapDrawable bitmapDrawable = new BitmapDrawable(resources, bitmap); // Use TransitionDrawable to fade in final TransitionDrawable td = new TransitionDrawable(new Drawable[] { initialDrawable, bitmapDrawable }); imageView.setImageDrawable(td); td.startTransition(UIUtils.ANIMATION_FADE_IN_TIME); } else { // No fade in, just set bitmap directly imageView.setImageBitmap(bitmap); } } /** * Get a usable cache directory (external if available, internal otherwise). * * @param context The context to use * @param uniqueName A unique directory name to append to the cache dir * @return The cache dir */ public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir // TODO: getCacheDir() should be moved to a background thread as it attempts to create the // directory if it does not exist (no disk access should happen on the main/UI thread). final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() : context.getCacheDir().getPath(); return new File(cachePath + File.separator + uniqueName); } /** * Get the external app cache directory. * * @param context The context to use * @return The external cache dir */ private static File getExternalCacheDir(Context context) { // TODO: This needs to be moved to a background thread to ensure no disk access on the // main/UI thread as unfortunately getExternalCacheDir() calls mkdirs() for us (even // though the Volley library will later try and call mkdirs() as well from a background // thread). return context.getExternalCacheDir(); } /** * Interface an activity can implement to provide an ImageLoader to its children fragments. */ public interface ImageLoaderProvider { public ImageLoader getImageLoaderInstance(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/ImageLoader.java
Java
asf20
13,009
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.Context; import android.content.pm.PackageManager; import com.google.android.apps.iosched.Config; import static com.google.android.apps.iosched.util.LogUtils.*; public class NetUtils { private static final String TAG = makeLogTag(AccountUtils.class); private static String mUserAgent = null; public static String getUserAgent(Context mContext) { if (mUserAgent == null) { mUserAgent = Config.APP_NAME; try { String packageName = mContext.getPackageName(); String version = mContext.getPackageManager().getPackageInfo(packageName, 0).versionName; mUserAgent = mUserAgent + " (" + packageName + "/" + version + ")"; LOGD(TAG, "User agent set to: " + mUserAgent); } catch (PackageManager.NameNotFoundException e) { LOGE(TAG, "Unable to find self by package name", e); } } return mUserAgent; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/NetUtils.java
Java
asf20
1,631
package com.google.android.apps.iosched.util; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.preference.PreferenceManager; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class MapUtils { private static final String TILE_PATH = "maptiles"; private static final String PREF_MYLOCATION_ENABLED = "map_mylocation_enabled"; private static final String TAG = LogUtils.makeLogTag(MapUtils.class); private static float mDPI = -1.0f; private static int mLabelPadding; private static final float LABEL_OUTLINEWIDTH = 3.5f; private static final int LABEL_PADDING = 2; private static final int LABEL_TEXTSIZE = 14; private static Paint mLabelOutlinePaint = null; private static Paint mLabelTextPaint; private static void setupLabels() { float strokeWidth = LABEL_OUTLINEWIDTH * mDPI; mLabelTextPaint = new Paint(); mLabelTextPaint.setTextSize(LABEL_TEXTSIZE * mDPI); mLabelTextPaint.setColor(Color.WHITE); mLabelTextPaint.setAntiAlias(true); mLabelOutlinePaint = new Paint(mLabelTextPaint); mLabelOutlinePaint.setStyle(Paint.Style.STROKE); mLabelOutlinePaint.setColor(0x99000000); mLabelOutlinePaint.setStrokeWidth(strokeWidth); mLabelOutlinePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); mLabelOutlinePaint.setStrokeJoin(Paint.Join.ROUND); mLabelOutlinePaint.setStrokeCap(Paint.Cap.ROUND); mLabelPadding = (int) Math.ceil(LABEL_PADDING * mDPI + strokeWidth); } public static Bitmap createTextLabel(String label, float dpi) { if (dpi != mDPI) { mDPI = dpi; setupLabels(); } // calculate size Rect bounds = new Rect(); mLabelTextPaint.getTextBounds(label, 0, label.length(), bounds); // calculate text size int bitmapH = Math.abs(bounds.top) + 2 * mLabelPadding; int bitmapW = bounds.right + 2 * mLabelPadding; // Create bitmap and draw text Bitmap b = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); c.drawText(label, mLabelPadding, bitmapH - mLabelPadding, mLabelOutlinePaint); c.drawText(label, mLabelPadding, bitmapH - mLabelPadding, mLabelTextPaint); return b; } private static String[] mapTileAssets; /** * Returns true if the given tile file exists as a local asset. */ public static boolean hasTileAsset(Context context, String filename) { //cache the list of available files if (mapTileAssets == null) { try { mapTileAssets = context.getAssets().list("maptiles"); } catch (IOException e) { // no assets mapTileAssets = new String[0]; } } // search for given filename for (String s : mapTileAssets) { if (s.equals(filename)) { return true; } } return false; } /** * Copy the file from the assets to the map tiles directory if it was * shipped with the APK. */ public static boolean copyTileAsset(Context context, String filename) { if (!hasTileAsset(context, filename)) { // file does not exist as asset return false; } // copy file from asset to internal storage try { InputStream is = context.getAssets().open(TILE_PATH + File.separator + filename); File f = getTileFile(context, filename); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[1024]; int dataSize; while ((dataSize = is.read(buffer)) > 0) { os.write(buffer, 0, dataSize); } os.close(); } catch (IOException e) { return false; } return true; } /** * Return a {@link File} pointing to the storage location for map tiles. */ public static File getTileFile(Context context, String filename) { File folder = new File(context.getFilesDir(), TILE_PATH); if (!folder.exists()) { folder.mkdirs(); } return new File(folder, filename); } public static void removeUnusedTiles(Context mContext, final ArrayList<String> usedTiles) { // remove all files are stored in the tile path but are not used File folder = new File(mContext.getFilesDir(), TILE_PATH); File[] unused = folder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return !usedTiles.contains(filename); } }); for (File f : unused) { f.delete(); } } public static boolean hasTile(Context mContext, String filename) { return getTileFile(mContext, filename).exists(); } public static boolean getMyLocationEnabled(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean(PREF_MYLOCATION_ENABLED,false); } public static void setMyLocationEnabled(final Context context, final boolean enableMyLocation) { LogUtils.LOGD(TAG,"Set my location enabled: "+enableMyLocation); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean(PREF_MYLOCATION_ENABLED,enableMyLocation).commit(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/MapUtils.java
Java
asf20
5,952
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.lang.reflect.InvocationTargetException; public class ReflectionUtils { public static Object tryInvoke(Object target, String methodName, Object... args) { Class<?>[] argTypes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } return tryInvoke(target, methodName, argTypes, args); } public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes, Object... args) { try { return target.getClass().getMethod(methodName, argTypes).invoke(target, args); } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } return null; } public static <E> E callWithDefault(Object target, String methodName, E defaultValue) { try { //noinspection unchecked return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target); } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } return defaultValue; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/ReflectionUtils.java
Java
asf20
1,906
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.ContentProvider; import android.net.Uri; import android.text.format.Time; import java.util.regex.Pattern; /** * Various utility methods used by {@link com.google.android.apps.iosched.io.JSONHandler}. */ public class ParserUtils { /** Used to sanitize a string to be {@link Uri} safe. */ private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]"); private static final Time sTime = new Time(); /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input) { if (input == null) { return null; } return sSanitizePattern.matcher(input.replace("+", "plus").toLowerCase()).replaceAll(""); } /** * Parse the given string as a RFC 3339 timestamp, returning the value as * milliseconds since the epoch. */ public static long parseTime(String time) { sTime.parse3339(time); return sTime.toMillis(false); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/ParserUtils.java
Java
asf20
1,698
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; /** * Helper for Google Play services-related operations. */ public class PlayServicesUtils { public static boolean checkGooglePlaySevices(final Activity activity) { final int googlePlayServicesCheck = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity); switch (googlePlayServicesCheck) { case ConnectionResult.SUCCESS: return true; case ConnectionResult.SERVICE_DISABLED: case ConnectionResult.SERVICE_INVALID: case ConnectionResult.SERVICE_MISSING: case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: Dialog dialog = GooglePlayServicesUtil.getErrorDialog(googlePlayServicesCheck, activity, 0); dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { activity.finish(); } }); dialog.show(); } return false; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/util/PlayServicesUtils.java
Java
asf20
1,961
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.TaskStackBuilderProxyActivity; import com.google.android.apps.iosched.util.AccountUtils; import android.accounts.Account; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.widget.RemoteViews; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The app widget's AppWidgetProvider. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ScheduleWidgetProvider extends AppWidgetProvider { private static final String TAG = makeLogTag(ScheduleWidgetProvider.class); private static final String REFRESH_ACTION = "com.google.android.apps.iosched.appwidget.action.REFRESH"; private static final String EXTRA_PERFORM_SYNC = "com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC"; public static Intent getRefreshBroadcastIntent(Context context, boolean performSync) { return new Intent(REFRESH_ACTION) .setComponent(new ComponentName(context, ScheduleWidgetProvider.class)) .putExtra(EXTRA_PERFORM_SYNC, performSync); } @Override public void onReceive(final Context context, Intent widgetIntent) { final String action = widgetIntent.getAction(); if (REFRESH_ACTION.equals(action)) { final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false); // Trigger sync Account chosenAccount = AccountUtils.getChosenAccount(context); if (shouldSync && chosenAccount != null) { SyncHelper.requestManualSync(chosenAccount); } // Notify the widget that the list view needs to be updated. final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, ScheduleWidgetProvider.class); mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_schedule_list); } super.onReceive(context, widgetIntent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final boolean isAuthenticated = AccountUtils.isAuthenticated(context); for (int appWidgetId : appWidgetIds) { // Specify the service to provide data for the collection widget. Note that we need to // embed the appWidgetId via the data otherwise it will be ignored. final Intent intent = new Intent(context, ScheduleWidgetRemoteViewsService.class) .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget); rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent); // Set the empty view to be displayed if the collection is empty. It must be a sibling // view of the collection view. rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty); rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated ? R.string.empty_widget_text : R.string.empty_widget_text_signed_out)); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, getRefreshBroadcastIntent(context, true), PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent); final Intent onClickIntent = TaskStackBuilderProxyActivity.getTemplate(context); final PendingIntent onClickPendingIntent = PendingIntent.getActivity(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent); final Intent openAppIntent = new Intent(context, HomeActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/appwidget/ScheduleWidgetProvider.java
Java
asf20
5,766
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity; import com.google.android.apps.iosched.ui.SimpleSectionedListAdapter; import com.google.android.apps.iosched.ui.SimpleSectionedListAdapter.Section; import com.google.android.apps.iosched.ui.TaskStackBuilderProxyActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Locale; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This is the service that provides the factory to be bound to the collection service. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ScheduleWidgetRemoteViewsService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new WidgetRemoveViewsFactory(this.getApplicationContext()); } /** * This is the factory that will provide data to the collection widget. */ private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory { private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class); private Context mContext; private Cursor mCursor; private SparseIntArray mPMap; private List<SimpleSectionedListAdapter.Section> mSections; private SparseBooleanArray mHeaderPositionMap; StringBuilder mBuffer = new StringBuilder(); Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault()); public WidgetRemoveViewsFactory(Context context) { mContext = context; } public void onCreate() { // Since we reload the cursor in onDataSetChanged() which gets called immediately after // onCreate(), we do nothing here. } public void onDestroy() { if (mCursor != null) { mCursor.close(); } } public int getCount() { if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) { return 0; } int size = mCursor.getCount() + mSections.size(); if (size < 10) { init(); size = mCursor.getCount() + mSections.size(); } LOGV(TAG, "size returned:" + size); return size; } public RemoteViews getViewAt(int position) { RemoteViews rv; boolean isSectionHeader = mHeaderPositionMap.get(position); int offset = mPMap.get(position); Intent homeIntent = new Intent(mContext, HomeActivity.class); if (isSectionHeader) { rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header); Section section = mSections.get(offset - 1); rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle()); } else { int cursorPosition = position - offset; mCursor.moveToPosition(cursorPosition); rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_block_widget); final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE); final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META); final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = mCursor.getLong(BlocksQuery.BLOCK_END); final Resources res = mContext.getResources(); rv.setTextViewText(R.id.block_endtime, null); if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) { final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); if (numStarredSessions == 0) { // No sessions starred rv.setTextViewText(R.id.block_title, mContext.getString( R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1_positive)); rv.setTextViewText(R.id.block_subtitle, mContext.getString( R.string.schedule_empty_slot_subtitle)); rv.setViewVisibility(R.id.extra_button, View.GONE); Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); String starredSessionSubtitle = mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (starredSessionSubtitle == null) { starredSessionSubtitle = mContext.getString(R.string.unknown_room); } // Determine if the session is in the past long currentTimeMillis = UIUtils.getCurrentTime(mContext); boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS; boolean blockEnded = currentTimeMillis > blockEnd; if (blockEnded && !conferenceEnded) { starredSessionSubtitle = mContext.getString(R.string.session_finished); } rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, starredSessionSubtitle); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions .buildSessionUri(starredSessionId))); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.extra_button, fillIntent); } else { // 2 or more sessions starred rv.setTextViewText(R.id.block_title, mContext.getString(R.string.schedule_conflict_title, numStarredSessions)); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, mContext.getString(R.string.schedule_conflict_subtitle)); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildStarredSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.extra_button, fillIntent); } rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2)); } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) { long currentTimeMillis = UIUtils.getCurrentTime(mContext); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room)); rv.setTextColor(R.id.block_title, canViewStream ? res.getColor(R.color.body_text_1) : res.getColor(R.color.body_text_disabled)); rv.setTextColor(R.id.block_subtitle, canViewStream ? res.getColor(R.color.body_text_2) : res.getColor(R.color.body_text_disabled)); rv.setViewVisibility(R.id.extra_button, View.GONE); if (canViewStream) { Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions .buildSessionUri(starredSessionId)) .setClass(mContext, SessionLivestreamActivity.class)); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); } else { rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent()); } } else { rv.setTextViewText(R.id.block_title, blockTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled)); rv.setTextViewText(R.id.block_subtitle, blockMeta); rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled)); rv.setViewVisibility(R.id.extra_button, View.GONE); mBuffer.setLength(0); rv.setTextViewText(R.id.block_endtime, DateUtils.formatDateRange(mContext, mFormatter, blockEnd, blockEnd, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(mContext).getID()).toString()); rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent()); } mBuffer.setLength(0); rv.setTextViewText(R.id.block_time, DateUtils.formatDateRange(mContext, mFormatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(mContext).getID()).toString()); } return rv; } public RemoteViews getLoadingView() { return null; } public int getViewTypeCount() { return 2; } public long getItemId(int position) { return position; } public boolean hasStableIds() { return true; } public void onDataSetChanged() { init(); } private void init() { if (mCursor != null) { mCursor.close(); } String liveStreamedOnlyBlocksSelection = "(" + (UIUtils.shouldShowLiveSessionsOnly(mContext) ? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','" + ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')" + " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 " : "1==1") + ")"; String onlyStarredOfficeHoursSelection = "(" + ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "' OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)"; String excludeSandbox = "("+ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX +"')"; mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, ScheduleContract.Blocks.BLOCK_END + " >= ? AND " + liveStreamedOnlyBlocksSelection + " AND " + onlyStarredOfficeHoursSelection + " AND " + excludeSandbox, new String[]{ Long.toString(UIUtils.getCurrentTime(mContext)) }, ScheduleContract.Blocks.DEFAULT_SORT); String displayTimeZone = PrefUtils.getDisplayTimeZone(mContext).getID(); mSections = new ArrayList<SimpleSectionedListAdapter.Section>(); mCursor.moveToFirst(); long previousTime = -1; long time; mPMap = new SparseIntArray(); mHeaderPositionMap = new SparseBooleanArray(); int offset = 0; int globalPosition = 0; while (!mCursor.isAfterLast()) { time = mCursor.getLong(BlocksQuery.BLOCK_START); if (!UIUtils.isSameDayDisplay(previousTime, time, mContext)) { mBuffer.setLength(0); mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(), DateUtils.formatDateRange( mContext, mFormatter, time, time, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY, displayTimeZone).toString())); ++offset; mHeaderPositionMap.put(globalPosition, true); mPMap.put(globalPosition, offset); ++globalPosition; } mHeaderPositionMap.put(globalPosition, false); mPMap.put(globalPosition, offset); ++globalPosition; previousTime = time; mCursor.moveToNext(); } LOGV(TAG, "Leaving init()"); } } public interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int NUM_STARRED_SESSIONS = 7; int NUM_LIVESTREAMED_SESSIONS = 8; int STARRED_SESSION_ID = 9; int STARRED_SESSION_TITLE = 10; int STARRED_SESSION_ROOM_NAME = 11; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/appwidget/ScheduleWidgetRemoteViewsService.java
Java
asf20
19,203
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.gcm.command.AnnouncementCommand; import com.google.android.apps.iosched.gcm.command.SyncCommand; import com.google.android.apps.iosched.gcm.command.SyncUserCommand; import com.google.android.apps.iosched.gcm.command.TestCommand; import com.google.android.gcm.GCMBaseIntentService; import android.content.Context; import android.content.Intent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link android.app.IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = makeLogTag("GCM"); private static final Map<String, GCMCommand> MESSAGE_RECEIVERS; static { // Known messages and their GCM message receivers Map <String, GCMCommand> receivers = new HashMap<String, GCMCommand>(); receivers.put("test", new TestCommand()); receivers.put("announcement", new AnnouncementCommand()); receivers.put("sync_schedule", new SyncCommand()); receivers.put("sync_user", new SyncUserCommand()); MESSAGE_RECEIVERS = Collections.unmodifiableMap(receivers); } public GCMIntentService() { super(Config.GCM_SENDER_ID); } @Override protected void onRegistered(Context context, String regId) { LOGI(TAG, "Device registered: regId=" + regId); ServerUtilities.register(context, regId); } @Override protected void onUnregistered(Context context, String regId) { LOGI(TAG, "Device unregistered"); if (ServerUtilities.isRegisteredOnServer(context)) { ServerUtilities.unregister(context, regId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. LOGD(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { String action = intent.getStringExtra("action"); String extraData = intent.getStringExtra("extraData"); if (action == null) { LOGE(TAG, "Message received without command action"); return; } action = action.toLowerCase(); GCMCommand command = MESSAGE_RECEIVERS.get(action); if (command == null) { LOGE(TAG, "Unknown command received: " + action); } else { command.execute(this, action, extraData); } } @Override public void onError(Context context, String errorId) { LOGE(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message LOGW(TAG, "Received recoverable error: " + errorId); return super.onRecoverableError(context, errorId); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/GCMIntentService.java
Java
asf20
3,942
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.content.Context; import com.google.android.apps.iosched.gcm.GCMCommand; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class TestCommand extends GCMCommand { private static final String TAG = makeLogTag("TestCommand"); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/command/TestCommand.java
Java
asf20
1,137
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.gcm.GCMCommand; import com.google.android.apps.iosched.ui.HomeActivity; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class AnnouncementCommand extends GCMCommand { private static final String TAG = makeLogTag("AnnouncementCommand"); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); displayNotification(context, extraData); } private void displayNotification(Context context, String message) { LOGI(TAG, "Displaying notification: " + message); ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(0, new NotificationCompat.Builder(context) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_stat_notification) .setTicker(message) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setContentIntent( PendingIntent.getActivity(context, 0, new Intent(context, HomeActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)) .setAutoCancel(true) .build()); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/command/AnnouncementCommand.java
Java
asf20
2,549
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.google.android.apps.iosched.gcm.GCMCommand; import com.google.android.apps.iosched.sync.TriggerSyncReceiver; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class SyncUserCommand extends GCMCommand { private static final String TAG = makeLogTag("TestCommand"); private static final int DEFAULT_TRIGGER_SYNC_DELAY = 60 * 1000; // 60 seconds private static final Random RANDOM = new Random(); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); int syncJitter; SyncData syncData = null; if (extraData != null) { try { Gson gson = new Gson(); syncData = gson.fromJson(extraData, SyncData.class); } catch (JsonSyntaxException e) { LOGI(TAG, "Error while decoding extraData: " + e.toString()); } } // TODO(trevorjohns): Make this so there's a configurable sync and jitter. // TODO(trevorjohns): Also, use superclass to reduce duplcated code between this and SyncCommand if (syncData != null && syncData.sync_jitter != 0) { syncJitter = syncData.sync_jitter; } else { syncJitter = DEFAULT_TRIGGER_SYNC_DELAY; } scheduleSync(context, syncJitter); } private void scheduleSync(Context context, int syncDelay) { // Use delay instead of jitter, since we're trying to squelch messages int jitterMillis = syncDelay; final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms"; LOGI(TAG, debugMessage); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } class SyncData { private int sync_jitter; SyncData() {} } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/command/SyncUserCommand.java
Java
asf20
3,203
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.google.android.apps.iosched.gcm.GCMCommand; import com.google.android.apps.iosched.sync.TriggerSyncReceiver; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class SyncCommand extends GCMCommand { private static final String TAG = makeLogTag("SyncCommand"); private static final int DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS = 15 * 60 * 1000; // 15 minutes private static final Random RANDOM = new Random(); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); int syncJitter; SyncData syncData = null; if (extraData != null) { try { Gson gson = new Gson(); syncData = gson.fromJson(extraData, SyncData.class); } catch (JsonSyntaxException e) { LOGI(TAG, "Error while decoding extraData: " + e.toString()); } } if (syncData != null && syncData.sync_jitter != 0) { syncJitter = syncData.sync_jitter; } else { syncJitter = DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS; } scheduleSync(context, syncJitter); } private void scheduleSync(Context context, int syncJitter) { int jitterMillis = (int) (RANDOM.nextFloat() * syncJitter); final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms"; LOGI(TAG, debugMessage); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } class SyncData { private int sync_jitter; SyncData() {} } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/command/SyncCommand.java
Java
asf20
2,991
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import android.content.Context; public abstract class GCMCommand { public abstract void execute(Context context, String type, String extraData); }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/GCMCommand.java
Java
asf20
794
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import android.util.Log; import com.google.android.apps.iosched.Config; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.google.android.apps.iosched.util.AccountUtils; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.Map.Entry; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final String TAG = makeLogTag("GCMs"); private static final String PREFERENCES = "com.google.android.apps.iosched.gcm"; private static final String PROPERTY_REGISTERED_TS = "registered_ts"; private static final String PROPERTY_REG_ID = "reg_id"; private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random sRandom = new Random(); /** * Register this account/device pair within the server. * * @param context Current context * @param gcmId The GCM registration ID for this device * @return whether the registration succeeded or not. */ public static boolean register(final Context context, final String gcmId) { LOGI(TAG, "registering device (gcm_id = " + gcmId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/register"; String plusProfileId = AccountUtils.getPlusProfileId(context); if (plusProfileId == null) { LOGW(TAG, "Profile ID: null"); } else { LOGI(TAG, "Profile ID: " + plusProfileId); } Map<String, String> params = new HashMap<String, String>(); params.put("gcm_id", gcmId); params.put("gplus_id", plusProfileId); long backoff = BACKOFF_MILLI_SECONDS + sRandom.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { LOGV(TAG, "Attempt #" + i + " to register"); try { post(serverUrl, params); setRegisteredOnServer(context, true, gcmId); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). LOGE(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { LOGV(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. LOGD(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } return false; } /** * Unregister this account/device pair within the server. * * @param context Current context * @param gcmId The GCM registration ID for this device */ static void unregister(final Context context, final String gcmId) { LOGI(TAG, "unregistering device (gcmId = " + gcmId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("gcm_id", gcmId); try { post(serverUrl, params); setRegisteredOnServer(context, false, gcmId); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. LOGD(TAG, "Unable to unregister from application server", e); } finally { // Regardless of server success, clear local preferences setRegisteredOnServer(context, false, null); } } /** * Sets whether the device was successfully registered in the server side. * * @param context Current context * @param flag True if registration was successful, false otherwise * @param gcmId True if registration was successful, false otherwise */ private static void setRegisteredOnServer(Context context, boolean flag, String gcmId) { final SharedPreferences prefs = context.getSharedPreferences( PREFERENCES, Context.MODE_PRIVATE); LOGD(TAG, "Setting registered on server status as: " + flag); Editor editor = prefs.edit(); if (flag) { editor.putLong(PROPERTY_REGISTERED_TS, new Date().getTime()); editor.putString(PROPERTY_REG_ID, gcmId); } else { editor.remove(PROPERTY_REG_ID); } editor.commit(); } /** * Checks whether the device was successfully registered in the server side. * * @param context Current context * @return True if registration was successful, false otherwise */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = context.getSharedPreferences( PREFERENCES, Context.MODE_PRIVATE); // Find registration threshold Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); long yesterdayTS = cal.getTimeInMillis(); long regTS = prefs.getLong(PROPERTY_REGISTERED_TS, 0); if (regTS > yesterdayTS) { LOGV(TAG, "GCM registration current. regTS=" + regTS + " yesterdayTS=" + yesterdayTS); return true; } else { LOGV(TAG, "GCM registration expired. regTS=" + regTS + " yesterdayTS=" + yesterdayTS); return false; } } public static String getGcmId(Context context) { final SharedPreferences prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); return prefs.getString(PROPERTY_REG_ID, null); } /** * Unregister the current GCM ID when we sign-out * * @param context Current context */ public static void onSignOut(Context context) { String gcmId = getGcmId(context); if (gcmId != null) { unregister(context, gcmId); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); LOGV(TAG, "Posting '" + body + "' to " + url); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setChunkedStreamingMode(0); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(body.length())); // post the request OutputStream out = conn.getOutputStream(); out.write(body.getBytes()); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/ServerUtilities.java
Java
asf20
9,682
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.gcm.GCMBroadcastReceiver; import android.content.Context; /** * @author trevorjohns@google.com (Trevor Johns) */ public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver { /** * Gets the class name of the intent service that will handle GCM messages. * * Used to override class name, so that GCMIntentService can live in a * subpackage. */ @Override protected String getGCMIntentServiceClassName(Context context) { return GCMIntentService.class.getCanonicalName(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/gcm/GCMRedirectedBroadcastReceiver.java
Java
asf20
1,210
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.util.AccountUtils; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.SyncResult; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.widget.Toast; import java.io.IOException; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Sync adapter for Google I/O data */ public class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = makeLogTag(SyncAdapter.class); private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@"); private final Context mContext; private SyncHelper mSyncHelper; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mContext = context; //noinspection ConstantConditions,PointlessBooleanExpression if (!BuildConfig.DEBUG) { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.", throwable); } }); } } @Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); final String logSanitizedAccountName = sSanitizeAccountNamePattern .matcher(account.name).replaceAll("$1...$2@"); if (uploadOnly) { return; } LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," + " uploadOnly=" + uploadOnly + " manualSync=" + manualSync + " initialize=" + initialize); String chosenAccountName = AccountUtils.getChosenAccountName(mContext); boolean isAccountSet = !TextUtils.isEmpty(chosenAccountName); boolean isChosenAccount = isAccountSet && chosenAccountName.equals(account.name); if (isAccountSet) { ContentResolver.setIsSyncable(account, authority, isChosenAccount ? 1 : 0); } if (!isChosenAccount) { LOGW(TAG, "Tried to sync account " + logSanitizedAccountName + " but the chosen " + "account is actually " + chosenAccountName); ++syncResult.stats.numAuthExceptions; return; } // Perform a sync using SyncHelper if (mSyncHelper == null) { mSyncHelper = new SyncHelper(mContext); } try { mSyncHelper.performSync(syncResult, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE); } catch (IOException e) { ++syncResult.stats.numIoExceptions; LOGE(TAG, "Error syncing data for I/O 2013.", e); } } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/sync/SyncAdapter.java
Java
asf20
4,208
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import android.accounts.Account; import android.content.*; import android.database.Cursor; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.RemoteException; import android.preference.PreferenceManager; import com.google.analytics.tracking.android.GAServiceManager; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.*; import com.google.android.apps.iosched.io.map.model.Tile; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.*; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.services.googledevelopers.Googledevelopers; import java.io.*; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.larvalabs.svgandroid.SVG; import com.larvalabs.svgandroid.SVGParseException; import com.larvalabs.svgandroid.SVGParser; import com.turbomanage.httpclient.BasicHttpClient; import com.turbomanage.httpclient.ConsoleRequestLogger; import com.turbomanage.httpclient.HttpResponse; import com.turbomanage.httpclient.RequestLogger; import static com.google.android.apps.iosched.util.LogUtils.*; /** * A helper class for dealing with sync and other remote persistence operations. * All operations occur on the thread they're called from, so it's best to wrap * calls in an {@link android.os.AsyncTask}, or better yet, a * {@link android.app.Service}. */ public class SyncHelper { private static final String TAG = makeLogTag(SyncHelper.class); public static final int FLAG_SYNC_LOCAL = 0x1; public static final int FLAG_SYNC_REMOTE = 0x2; private static final int LOCAL_VERSION_CURRENT = 25; private static final String LOCAL_MAPVERSION_CURRENT = "\"vlh7Ig\""; private Context mContext; public SyncHelper(Context context) { mContext = context; } public static void requestManualSync(Account mChosenAccount) { Bundle b = new Bundle(); b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync( mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, b); } /** * Loads conference information (sessions, rooms, tracks, speakers, etc.) * from a local static cache data and then syncs down data from the * Conference API. * * @param syncResult Optional {@link SyncResult} object to populate. * @throws IOException */ public void performSync(SyncResult syncResult, int flags) throws IOException { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); final int localVersion = prefs.getInt("local_data_version", 0); // Bulk of sync work, performed by executing several fetches from // local and online sources. final ContentResolver resolver = mContext.getContentResolver(); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); LOGI(TAG, "Performing sync"); if ((flags & FLAG_SYNC_LOCAL) != 0) { final long startLocal = System.currentTimeMillis(); final boolean localParse = localVersion < LOCAL_VERSION_CURRENT; LOGD(TAG, "found localVersion=" + localVersion + " and LOCAL_VERSION_CURRENT=" + LOCAL_VERSION_CURRENT); // Only run local sync if there's a newer version of data available // than what was last locally-sync'd. if (localParse) { // Load static local data LOGI(TAG, "Local syncing rooms"); batch.addAll(new RoomsHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.rooms))); LOGI(TAG, "Local syncing blocks"); batch.addAll(new BlocksHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.common_slots))); LOGI(TAG, "Local syncing tracks"); batch.addAll(new TracksHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.tracks))); LOGI(TAG, "Local syncing speakers"); batch.addAll(new SpeakersHandler(mContext).parseString( JSONHandler.parseResource(mContext, R.raw.speakers))); LOGI(TAG, "Local syncing sessions"); batch.addAll(new SessionsHandler(mContext).parseString( JSONHandler.parseResource(mContext, R.raw.sessions), JSONHandler.parseResource(mContext, R.raw.session_tracks))); LOGI(TAG, "Local syncing search suggestions"); batch.addAll(new SearchSuggestHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.search_suggest))); LOGI(TAG, "Local syncing map"); MapPropertyHandler mapHandler = new MapPropertyHandler(mContext); batch.addAll(mapHandler.parse( JSONHandler.parseResource(mContext, R.raw.map))); //need to sync tile files before data is updated in content provider syncMapTiles(mapHandler.getTiles()); prefs.edit().putInt("local_data_version", LOCAL_VERSION_CURRENT).commit(); prefs.edit().putString("local_mapdata_version", LOCAL_MAPVERSION_CURRENT).commit(); if (syncResult != null) { ++syncResult.stats.numUpdates; // TODO: better way of indicating progress? ++syncResult.stats.numEntries; } } LOGD(TAG, "Local sync took " + (System.currentTimeMillis() - startLocal) + "ms"); try { // Apply all queued up batch operations for local data. resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } batch = new ArrayList<ContentProviderOperation>(); } if ((flags & FLAG_SYNC_REMOTE) != 0 && isOnline()) { try { Googledevelopers conferenceAPI = getConferenceAPIClient(); final long startRemote = System.currentTimeMillis(); LOGI(TAG, "Remote syncing announcements"); batch.addAll(new AnnouncementsFetcher(mContext).fetchAndParse()); LOGI(TAG, "Remote syncing speakers"); batch.addAll(new SpeakersHandler(mContext).fetchAndParse(conferenceAPI)); LOGI(TAG, "Remote syncing sessions"); batch.addAll(new SessionsHandler(mContext).fetchAndParse(conferenceAPI)); // Map sync batch.addAll(remoteSyncMapData(Config.GET_MAP_URL,prefs)); LOGD(TAG, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms"); if (syncResult != null) { ++syncResult.stats.numUpdates; // TODO: better way of indicating progress? ++syncResult.stats.numEntries; } GAServiceManager.getInstance().dispatch(); // Sync feedback stuff LOGI(TAG, "Syncing session feedback"); batch.addAll(new FeedbackHandler(mContext).uploadNew(conferenceAPI)); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 401) { LOGI(TAG, "Unauthorized; getting a new auth token.", e); if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } AccountUtils.refreshAuthToken(mContext); } } // all other IOExceptions are thrown LOGI(TAG, "Sync complete"); } try { // Apply all queued up remaining batch operations (only remote content at this point). resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); // Update search index resolver.update(ScheduleContract.SearchIndex.CONTENT_URI, new ContentValues(), null, null); // Delete empty blocks Cursor emptyBlocksCursor = resolver.query(ScheduleContract.Blocks.CONTENT_URI, new String[]{ScheduleContract.Blocks.BLOCK_ID,ScheduleContract.Blocks.SESSIONS_COUNT}, ScheduleContract.Blocks.EMPTY_SESSIONS_SELECTION, null, null); batch = new ArrayList<ContentProviderOperation>(); int numDeletedEmptyBlocks = 0; while (emptyBlocksCursor.moveToNext()) { batch.add(ContentProviderOperation .newDelete(ScheduleContract.Blocks.buildBlockUri( emptyBlocksCursor.getString(0))) .build()); ++numDeletedEmptyBlocks; } emptyBlocksCursor.close(); resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); LOGD(TAG, "Deleted " + numDeletedEmptyBlocks + " empty session blocks."); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } } public void addOrRemoveSessionFromSchedule(Context context, String sessionId, boolean inSchedule) throws IOException { LOGI(TAG, "Updating session on user schedule: " + sessionId); Googledevelopers conferenceAPI = getConferenceAPIClient(); try { sendScheduleUpdate(conferenceAPI, context, sessionId, inSchedule); } catch (GoogleJsonResponseException e) { if (e.getDetails().getCode() == 401) { LOGI(TAG, "Unauthorized; getting a new auth token.", e); AccountUtils.refreshAuthToken(mContext); // Try request one more time with new credentials before giving up conferenceAPI = getConferenceAPIClient(); sendScheduleUpdate(conferenceAPI, context, sessionId, inSchedule); } } } private void sendScheduleUpdate(Googledevelopers conferenceAPI, Context context, String sessionId, boolean inSchedule) throws IOException { if (inSchedule) { conferenceAPI.users().events().sessions().update(Config.EVENT_ID, sessionId, null).execute(); } else { conferenceAPI.users().events().sessions().delete(Config.EVENT_ID, sessionId).execute(); } } private ArrayList<ContentProviderOperation> remoteSyncMapData(String urlString, SharedPreferences preferences) throws IOException { final String localVersion = preferences.getString("local_mapdata_version", null); ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); BasicHttpClient httpClient = new BasicHttpClient(); httpClient.setRequestLogger(mQuietLogger); httpClient.addHeader("If-None-Match", localVersion); LOGD(TAG,"Local map version: "+localVersion); HttpResponse response = httpClient.get(urlString, null); final int status = response.getStatus(); if (status == HttpURLConnection.HTTP_OK) { // Data has been updated, otherwise would have received HTTP_NOT_MODIFIED LOGI(TAG, "Remote syncing map data"); final List<String> etag = response.getHeaders().get("ETag"); if (etag != null && etag.size() > 0) { MapPropertyHandler handler = new MapPropertyHandler(mContext); batch.addAll(handler.parse(response.getBodyAsString())); syncMapTiles(handler.getTiles()); // save new etag as version preferences.edit().putString("local_mapdata_version", etag.get(0)).commit(); } } //else: no update return batch; } private boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService( Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } /** * Synchronise the map overlay files either from the local assets (if available) or from a remote url. * * @param collection Set of tiles containing a local filename and remote url. * @throws IOException */ private void syncMapTiles(Collection<Tile> collection) throws IOException, SVGParseException { //keep track of used files, unused files are removed ArrayList<String> usedTiles = Lists.newArrayList(); for(Tile tile : collection){ final String filename = tile.filename; final String url = tile.url; usedTiles.add(filename); if (!MapUtils.hasTile(mContext, filename)) { // copy or download the tile if it is not stored yet if (MapUtils.hasTileAsset(mContext, filename)) { // file already exists as an asset, copy it MapUtils.copyTileAsset(mContext, filename); } else { // download the file File tileFile = MapUtils.getTileFile(mContext, filename); BasicHttpClient httpClient = new BasicHttpClient(); httpClient.setRequestLogger(mQuietLogger); HttpResponse httpResponse = httpClient.get(url, null); writeFile(httpResponse.getBody(), tileFile); // ensure the file is valid SVG InputStream is = new FileInputStream(tileFile); SVG svg = SVGParser.getSVGFromInputStream(is); is.close(); } } } MapUtils.removeUnusedTiles(mContext, usedTiles); } /** * Write the byte array directly to a file. * @throws IOException */ private void writeFile(byte[] data, File file) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, false)); bos.write(data); bos.close(); } /** * A type of ConsoleRequestLogger that does not log requests and responses. */ private RequestLogger mQuietLogger = new ConsoleRequestLogger(){ @Override public void logRequest(HttpURLConnection uc, Object content) throws IOException { } @Override public void logResponse(HttpResponse res) { } }; private Googledevelopers getConferenceAPIClient() { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new AndroidJsonFactory(); GoogleCredential credential = new GoogleCredential().setAccessToken(AccountUtils.getAuthToken(mContext)); // Note: The Googledevelopers API is unique, in that it requires an API key in addition to the client // ID normally embedded an an OAuth token. Most apps will use one or the other. return new Googledevelopers.Builder(httpTransport, jsonFactory, null) .setApplicationName(NetUtils.getUserAgent(mContext)) .setGoogleClientRequestInitializer(new CommonGoogleClientRequestInitializer(Config.API_KEY)) .setHttpRequestInitializer(credential) .build(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/sync/SyncHelper.java
Java
asf20
16,972
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.gms.auth.GoogleAuthUtil; import android.accounts.Account; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; /** * A simple {@link BroadcastReceiver} that triggers a sync. This is used by the GCM code to trigger * jittered syncs using {@link android.app.AlarmManager}. */ public class TriggerSyncReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String accountName = AccountUtils.getChosenAccountName(context); if (TextUtils.isEmpty(accountName)) { return; } ContentResolver.requestSync( AccountUtils.getChosenAccount(context), ScheduleContract.CONTENT_AUTHORITY, new Bundle()); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/sync/TriggerSyncReceiver.java
Java
asf20
1,676
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * Service that handles sync. It simply instantiates a SyncAdapter and returns its IBinder. */ public class SyncService extends Service { private static final Object sSyncAdapterLock = new Object(); private static SyncAdapter sSyncAdapter = null; @Override public void onCreate() { synchronized (sSyncAdapterLock) { if (sSyncAdapter == null) { sSyncAdapter = new SyncAdapter(getApplicationContext(), false); } } } @Override public IBinder onBind(Intent intent) { return sSyncAdapter.getSyncAdapterBinder(); } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/sync/SyncService.java
Java
asf20
1,345
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched; public class Config { // General configuration public static final int CONFERENCE_YEAR = 2013; // OAuth 2.0 related config public static final String APP_NAME = "GoogleIO-Android"; // TODO: Add your Google API key here. public static final String API_KEY = "YOUR_API_KEY_HERE"; // Conference API-specific config public static final String EVENT_ID = "googleio2013"; public static final String CONFERENCE_IMAGE_PREFIX_URL = "https://developers.google.com"; // Announcements public static final String ANNOUNCEMENTS_PLUS_ID = "111395306401981598462"; // Static file host for the map data public static final String GET_MAP_URL = "http://2013.ioschedmap.appspot.com/map.json"; // YouTube API config // TODO: Add your YouTube API key here. public static final String YOUTUBE_API_KEY = "YOUR_API_KEY_HERE"; // YouTube share URL public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/"; // Livestream captions config public static final String PRIMARY_LIVESTREAM_CAPTIONS_URL = "http://io-captions.appspot.com/?event=e1&android=t"; public static final String SECONDARY_LIVESTREAM_CAPTIONS_URL = "http://io-captions.appspot.com/?event=e2&android=t"; public static final String PRIMARY_LIVESTREAM_TRACK = "android"; public static final String SECONDARY_LIVESTREAM_TRACK = "chrome"; // Conference public WiFi AP parameters public static final String WIFI_SSID = "Google5G"; public static final String WIFI_PASSPHRASE = "gomobileio"; // GCM config // TODO: Add your GCM information here. public static final String GCM_SERVER_URL = "https://YOUR_GCM_APP_ID_HERE.appspot.com"; public static final String GCM_SENDER_ID = "YOUR_GCM_SENDER_ID_HERE"; public static final String GCM_API_KEY = "YOUR_GCM_API_KEY_HERE"; }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/Config.java
Java
asf20
2,515
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.content.res.Resources; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.MapFragment.MarkerModel; import com.google.android.apps.iosched.ui.widget.EllipsizedTextView; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import java.util.HashMap; class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { // Common parameters private String roomTitle; private Marker mMarker; //Session private String titleCurrent, titleNext, timeNext; private boolean inProgress; //Sandbox private int sandboxColor; private int companyIcon; private String companyList; // Inflated views private View mViewSandbox = null; private View mViewSession = null; private View mViewTitleOnly = null; private LayoutInflater mInflater; private Resources mResources; private HashMap<String, MarkerModel> mMarkers; public MapInfoWindowAdapter(LayoutInflater inflater, Resources resources, HashMap<String, MarkerModel> markers) { this.mInflater = inflater; this.mResources = resources; mMarkers = markers; } @Override public View getInfoContents(Marker marker) { // render fallback if incorrect data is set or any other type // except for session or sandbox are rendered if (mMarker != null && !mMarker.getTitle().equals(marker.getTitle()) && (MapFragment.TYPE_SESSION.equals(marker.getSnippet()) || MapFragment.TYPE_SANDBOX.equals(marker.getSnippet()))) { // View will be rendered in getInfoWindow, need to return null return null; } else { return renderTitleOnly(marker); } } @Override public View getInfoWindow(Marker marker) { if (mMarker != null && mMarker.getTitle().equals(marker.getTitle())) { final String snippet = marker.getSnippet(); if (MapFragment.TYPE_SESSION.equals(snippet)) { return renderSession(marker); } else if (MapFragment.TYPE_SANDBOX.equals(snippet)) { return renderSandbox(marker); } } return null; } private View renderTitleOnly(Marker marker) { if (mViewTitleOnly == null) { mViewTitleOnly = mInflater.inflate(R.layout.map_info_titleonly, null); } TextView title = (TextView) mViewTitleOnly.findViewById(R.id.map_info_title); title.setText(mMarkers.get(marker.getTitle()).label); return mViewTitleOnly; } private View renderSession(Marker marker) { if (mViewSession == null) { mViewSession = mInflater.inflate(R.layout.map_info_session, null); } TextView roomName = (TextView) mViewSession.findViewById(R.id.map_info_roomtitle); roomName.setText(roomTitle); TextView first = (TextView) mViewSession.findViewById(R.id.map_info_session_now); TextView second = (TextView) mViewSession.findViewById(R.id.map_info_session_next); View spacer = mViewSession.findViewById(R.id.map_info_session_spacer); // default visibility first.setVisibility(View.GONE); second.setVisibility(View.GONE); spacer.setVisibility(View.GONE); if (inProgress) { // A session is in progress, show its title first.setText(Html.fromHtml(mResources.getString(R.string.map_now_playing, titleCurrent))); first.setVisibility(View.VISIBLE); } // show the next session if there is one if (titleNext != null) { second.setText(Html.fromHtml(mResources.getString(R.string.map_at, timeNext, titleNext))); second.setVisibility(View.VISIBLE); } if(!inProgress && titleNext == null){ // No session in progress or coming up second.setText(Html.fromHtml(mResources.getString(R.string.map_now_playing, mResources.getString(R.string.map_infowindow_text_empty)))); second.setVisibility(View.VISIBLE); }else if(inProgress && titleNext != null){ // Both lines are displayed, add extra padding spacer.setVisibility(View.VISIBLE); } return mViewSession; } private View renderSandbox(Marker marker) { if (mViewSandbox == null) { mViewSandbox = mInflater.inflate(R.layout.map_info_sandbox, null); } TextView titleView = (TextView) mViewSandbox.findViewById(R.id.map_info_roomtitle); titleView.setText(roomTitle); ImageView iconView = (ImageView) mViewSandbox.findViewById(R.id.map_info_icon); iconView.setImageResource(companyIcon); View rootLayout = mViewSandbox.findViewById(R.id.map_info_top); rootLayout.setBackgroundColor(this.sandboxColor); // Views EllipsizedTextView companyListView = (EllipsizedTextView) mViewSandbox.findViewById(R.id.map_info_sandbox_now); if (this.companyList != null) { companyListView.setText(Html.fromHtml(mResources.getString(R.string.map_now_sandbox, companyList))); //TODO: fix missing ellipsize } else { // No active companies companyListView.setText(Html.fromHtml(mResources.getString(R.string.map_now_sandbox, mResources.getString(R.string.map_infowindow_text_empty)))); } return mViewSandbox; } public void clearData() { this.titleCurrent = null; this.titleNext = null; this.inProgress = false; this.mMarker = null; } public void setSessionData(Marker marker, String roomTitle, String titleCurrent, String titleNext, String timeNext, boolean inProgress) { clearData(); this.titleCurrent = titleCurrent; this.titleNext = titleNext; this.timeNext = timeNext; this.inProgress = inProgress; this.mMarker = marker; this.roomTitle = roomTitle; } public void setMarker(Marker marker, String roomTitle) { clearData(); this.mMarker = marker; this.roomTitle = roomTitle; } public void setSandbox(Marker marker, String label, int color, int iconId, String companies) { clearData(); mMarker = marker; this.companyList = companies; this.roomTitle = label; this.sandboxColor = color; this.companyIcon = iconId; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/MapInfoWindowAdapter.java
Java
asf20
7,499
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseArray; import android.view.*; import android.view.View.OnLongClickListener; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.SessionsSandboxMultiPaneActivity; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Locale; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class ScheduleFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, ActionMode.Callback { private static final String TAG = makeLogTag(ScheduleFragment.class); private static final String STATE_ACTION_MODE = "actionMode"; private SimpleSectionedListAdapter mAdapter; private MyScheduleAdapter mScheduleAdapter; private SparseArray<String> mSelectedItemData; private View mLongClickedView; private ActionMode mActionMode; private boolean mScrollToNow; private boolean mActionModeStarted = false; private Bundle mViewDestroyedInstanceState; private StringBuilder mBuffer = new StringBuilder(); private Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault()); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mScheduleAdapter = new MyScheduleAdapter(getActivity()); mAdapter = new SimpleSectionedListAdapter(getActivity(), R.layout.list_item_schedule_header, mScheduleAdapter); setListAdapter(mAdapter); if (savedInstanceState == null) { mScrollToNow = true; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); persistActionModeState(outState); } private void persistActionModeState(Bundle outState) { if (outState != null && mActionModeStarted && mSelectedItemData != null) { outState.putStringArray(STATE_ACTION_MODE, new String[]{ mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ID), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_TITLE), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_URL), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID), }); } } private void loadActionModeState(Bundle state) { if (state != null && state.containsKey(STATE_ACTION_MODE)) { mActionModeStarted = true; mActionMode = ((ActionBarActivity) getActivity()).startSupportActionMode(this); String[] data = state.getStringArray(STATE_ACTION_MODE); if (data != null) { mSelectedItemData = new SparseArray<String>(); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ID, data[0]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, data[1]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, data[2]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_URL, data[3]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, data[4]); } } } @Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); // Hide the action mode when the fragment becomes invisible if (!menuVisible) { if (mActionModeStarted && mActionMode != null && mSelectedItemData != null) { mViewDestroyedInstanceState = new Bundle(); persistActionModeState(mViewDestroyedInstanceState); mActionMode.finish(); } } else if (mViewDestroyedInstanceState != null) { loadActionModeState(mViewDestroyedInstanceState); mViewDestroyedInstanceState = null; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) root.findViewById(android.R.id.empty), true); root.setBackgroundColor(Color.WHITE); ListView listView = (ListView) root.findViewById(android.R.id.list); listView.setItemsCanFocus(true); listView.setCacheColorHint(Color.WHITE); listView.setSelector(android.R.color.transparent); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); loadActionModeState(savedInstanceState); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter in // the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(0, null, this); } private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sp, String key) { if (isAdded() && mAdapter != null) { if (PrefUtils.PREF_LOCAL_TIMES.equals(key)) { PrefUtils.isUsingLocalTime(getActivity(), true); // force update mAdapter.notifyDataSetInvalidated(); } else if (PrefUtils.PREF_ATTENDEE_AT_VENUE.equals(key)) { PrefUtils.isAttendeeAtVenue(getActivity(), true); // force update getLoaderManager().restartLoader(0, null, ScheduleFragment.this); } } } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (!isAdded()) { return; } getLoaderManager().restartLoader(0, null, ScheduleFragment.this); } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity); sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener); } // LoaderCallbacks @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { String liveStreamedOnlyBlocksSelection = "(" + (UIUtils.shouldShowLiveSessionsOnly(getActivity()) ? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','" + ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')" + " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 " : "1==1") + ")"; String onlyStarredOfficeHoursSelection = "(" + ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "' OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)"; String excludeSandbox = "("+ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX +"')"; return new CursorLoader(getActivity(), ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, liveStreamedOnlyBlocksSelection + " AND " + onlyStarredOfficeHoursSelection + " AND " + excludeSandbox, null, ScheduleContract.Blocks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (!isAdded()) { return; } Context context = getActivity(); long currentTime = UIUtils.getCurrentTime(getActivity()); int firstNowPosition = ListView.INVALID_POSITION; String displayTimeZone = PrefUtils.getDisplayTimeZone(context).getID(); List<SimpleSectionedListAdapter.Section> sections = new ArrayList<SimpleSectionedListAdapter.Section>(); cursor.moveToFirst(); long previousBlockStart = -1; long blockStart, blockEnd; while (!cursor.isAfterLast()) { blockStart = cursor.getLong(BlocksQuery.BLOCK_START); blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); if (!UIUtils.isSameDayDisplay(previousBlockStart, blockStart, context)) { mBuffer.setLength(0); sections.add(new SimpleSectionedListAdapter.Section(cursor.getPosition(), DateUtils.formatDateRange( context, mFormatter, blockStart, blockStart, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY, displayTimeZone).toString())); } if (mScrollToNow && firstNowPosition == ListView.INVALID_POSITION // if we're currently in this block, or we're not in a block // and this block is in the future, then this is the scroll position && ((blockStart < currentTime && currentTime < blockEnd) || blockStart > currentTime)) { firstNowPosition = cursor.getPosition(); } previousBlockStart = blockStart; cursor.moveToNext(); } mScheduleAdapter.swapCursor(cursor); SimpleSectionedListAdapter.Section[] dummy = new SimpleSectionedListAdapter.Section[sections.size()]; mAdapter.setSections(sections.toArray(dummy)); if (mScrollToNow && firstNowPosition != ListView.INVALID_POSITION) { firstNowPosition = mAdapter.positionToSectionedPosition(firstNowPosition); getListView().setSelectionFromTop(firstNowPosition, getResources().getDimensionPixelSize(R.dimen.list_scroll_top_offset)); mScrollToNow = false; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private class MyScheduleAdapter extends CursorAdapter { public MyScheduleAdapter(Context context) { super(context, null, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.list_item_schedule_block, parent, false); } @Override public void bindView(View view, Context context, final Cursor cursor) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); final String blockMeta = cursor.getString(BlocksQuery.BLOCK_META); final String blockTimeString = UIUtils.formatBlockTimeString(blockStart, blockEnd, mBuffer, context); final TextView timeView = (TextView) view.findViewById(R.id.block_time); final TextView endtimeView = (TextView) view.findViewById(R.id.block_endtime); final TextView titleView = (TextView) view.findViewById(R.id.block_title); final TextView subtitleView = (TextView) view.findViewById(R.id.block_subtitle); final ImageButton extraButton = (ImageButton) view.findViewById(R.id.extra_button); final View primaryTouchTargetView = view.findViewById(R.id.list_item_middle_container); final Resources res = getResources(); String subtitle; boolean isLiveStreamed = false; primaryTouchTargetView.setOnLongClickListener(null); primaryTouchTargetView.setSelected(false); endtimeView.setText(null); titleView.setTextColor(res.getColorStateList(R.color.body_text_1_stateful)); subtitleView.setTextColor(res.getColorStateList(R.color.body_text_2_stateful)); if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(type)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); View.OnClickListener allSessionsListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { return; } final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }; if (numStarredSessions == 0) { // 0 sessions starred titleView.setText(getString(R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); titleView.setTextColor(res.getColorStateList( R.color.body_text_1_positive_stateful)); subtitle = getString(R.string.schedule_empty_slot_subtitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setOnClickListener(allSessionsListener); primaryTouchTargetView.setEnabled(!mActionModeStarted); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); final String starredSessionHashtags = cursor.getString(BlocksQuery.STARRED_SESSION_HASHTAGS); final String starredSessionUrl = cursor.getString(BlocksQuery.STARRED_SESSION_URL); final String starredSessionRoomId = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_ID); titleView.setText(starredSessionTitle); subtitle = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (subtitle == null) { subtitle = getString(R.string.unknown_room); } // Determine if the session is in the past long currentTimeMillis = UIUtils.getCurrentTime(context); boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS; boolean blockEnded = currentTimeMillis > blockEnd; if (blockEnded && !conferenceEnded) { subtitle = getString(R.string.session_finished); } isLiveStreamed = !TextUtils.isEmpty( cursor.getString(BlocksQuery.STARRED_SESSION_LIVESTREAM_URL)); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); extraButton.setEnabled(!mActionModeStarted); if (mSelectedItemData != null && mActionModeStarted && mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ID, "").equals( starredSessionId)) { primaryTouchTargetView.setSelected(true); mLongClickedView = primaryTouchTargetView; } final Runnable restartActionMode = new Runnable() { @Override public void run() { boolean currentlySelected = false; if (mActionModeStarted && mSelectedItemData != null && starredSessionId.equals(mSelectedItemData.get( BlocksQuery.STARRED_SESSION_ID))) { currentlySelected = true; } if (mActionMode != null) { mActionMode.finish(); if (currentlySelected) { return; } } mLongClickedView = primaryTouchTargetView; mSelectedItemData = new SparseArray<String>(); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ID, starredSessionId); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, starredSessionTitle); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, starredSessionHashtags); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_URL, starredSessionUrl); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, starredSessionRoomId); mActionMode = ((ActionBarActivity) getActivity()) .startSupportActionMode(ScheduleFragment.this); primaryTouchTargetView.setSelected(true); } }; primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { restartActionMode.run(); return; } final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionsSandboxMultiPaneActivity.EXTRA_MASTER_URI, ScheduleContract.Blocks.buildSessionsUri(blockId)); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { restartActionMode.run(); return true; } }); primaryTouchTargetView.setEnabled(true); } else { // 2 or more sessions starred titleView.setText(getString(R.string.schedule_conflict_title, numStarredSessions)); subtitle = getString(R.string.schedule_conflict_subtitle); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); extraButton.setEnabled(!mActionModeStarted); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { return; } final Uri sessionsUri = ScheduleContract.Blocks .buildStarredSessionsUri( blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setEnabled(!mActionModeStarted); } } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); long currentTimeMillis = UIUtils.getCurrentTime(context); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); boolean enabled = canViewStream && !mActionModeStarted; isLiveStreamed = true; subtitle = getString(R.string.keynote_room); titleView.setText(starredSessionTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(enabled); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { return; } final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, sessionUri); livestreamIntent.setClass(getActivity(), SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); } else { subtitle = blockMeta; titleView.setText(blockTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(false); primaryTouchTargetView.setOnClickListener(null); mBuffer.setLength(0); endtimeView.setText(DateUtils.formatDateRange(context, mFormatter, blockEnd, blockEnd, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(context).getID()).toString()); } mBuffer.setLength(0); timeView.setText(DateUtils.formatDateRange(context, mFormatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(context).getID()).toString()); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, isLiveStreamed, titleView, subtitleView, subtitle); } } private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.STARRED_SESSION_ROOM_ID, ScheduleContract.Blocks.STARRED_SESSION_HASHTAGS, ScheduleContract.Blocks.STARRED_SESSION_URL, ScheduleContract.Blocks.STARRED_SESSION_LIVESTREAM_URL, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int SESSIONS_COUNT = 7; int NUM_STARRED_SESSIONS = 8; int NUM_LIVESTREAMED_SESSIONS = 9; int STARRED_SESSION_ID = 10; int STARRED_SESSION_TITLE = 11; int STARRED_SESSION_ROOM_NAME = 12; int STARRED_SESSION_ROOM_ID = 13; int STARRED_SESSION_HASHTAGS = 14; int STARRED_SESSION_URL = 15; int STARRED_SESSION_LIVESTREAM_URL = 16; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); String title = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_TITLE); String hashtags = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_URL); boolean handled = false; switch (item.getItemId()) { case R.id.menu_map: String roomId = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID); helper.startMapActivity(roomId); handled = true; break; case R.id.menu_star: String sessionId = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); helper.setSessionStarred(sessionUri, false, title); handled = true; break; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, title, hashtags, url); handled = true; break; case R.id.menu_social_stream: helper.startSocialStream(hashtags); handled = true; break; default: LOGW(TAG, "Unknown action taken"); } mActionMode.finish(); return handled; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); MenuItem starMenuItem = menu.findItem(R.id.menu_star); starMenuItem.setTitle(R.string.description_remove_schedule); starMenuItem.setIcon(R.drawable.ic_action_remove_schedule); mAdapter.notifyDataSetChanged(); mActionModeStarted = true; return true; } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; if (mLongClickedView != null) { mLongClickedView.setSelected(false); } mActionModeStarted = false; mAdapter.notifyDataSetChanged(); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } }
zzc88915-iosched
android/src/main/java/com/google/android/apps/iosched/ui/ScheduleFragment.java
Java
asf20
30,806