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
<?php /* Template Name: iTMS Template */ define("IMAGEFLOW_ABSOLUTE_URL", get_bloginfo('template_directory') . "/custom_itunes.php-ext/ImageFlow_1.3.0"); define("IMAGEFLOW_ABSOLUTE_DIR", dirname(__FILE__) . "/custom_itunes.php-ext/ImageFlow_1.3.0"); define("LINKSHARE_PARTNER_ID", "0"); define("LINKSHARE_AFFILIATE_ID", "0"); define("ITUNES_WIDGET_TAG", '<iframe src="http://widgets.itunes.apple.com/itunes.html?wtype=2&app_id=::::id::::&country=jp&partnerId=' . LINKSHARE_PARTNER_ID . '&affiliate_id=' . LINKSHARE_AFFILIATE_ID . '&cul=000000&cur=000000&cll=000000&clr=000000&ww=325" frameborder=0 style="overflow-x:hidden;overflow-y:hidden;width:335px;height:300px;border:0px;" ></iframe>'); ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php echo get_global_menu(); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="itunes_title"> <h2>iTunes</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- iTunes START --> <div id="itunes_box"> <div class="i_player"> <link rel="stylesheet" href="<?php echo IMAGEFLOW_ABSOLUTE_URL; ?>/imageflow.css" type="text/css" /> <script type="text/javascript" src="<?php echo IMAGEFLOW_ABSOLUTE_DIR; ?>/loadjs.php"></script> <?php //============================= //iTunesWidgetを表示 //============================= if(!isset($_GET["ititem"])){$_GET["ititem"] = 0;} $q = get_posts('post_type=itunes&posts_per_page=1&offset=' . $_GET["ititem"]); $customValue = get_post_custom_values('iTunesItemID', $q[0]->ID); echo str_replace("::::id::::", $customValue[0], ITUNES_WIDGET_TAG); ?> </div> </div> <div class="album_archive"> <?php //============================= //iTunesアルバムのImageFlowを表示 //============================= echo '<div id="myImageFlow" class="imageflow">'; $q = get_posts('post_type=itunes&post_per_page=-1'); foreach($q as $key => $value){ //WordpressカスタムフィールドiTunesItemIDを取得 $customValue = get_post_custom_values('iTunesItemID', $value->ID); //iTunesItemIDをiTunesAPIで検索して取得 $itmsLookup = json_decode(file_get_contents("http://itunes.apple.com/lookup?country=JP&id=" . $customValue[0])); //取得したiTunesItemから100pxアルバムアートワークのURLを取得 $itmsArtworkUrl = $itmsLookup->results[0]->artworkUrl100; //ローカルの保存用にアルバムアートワークのファイル名を取得 $itmsArtworkFilename = basename( parse_url($itmsArtworkUrl, PHP_URL_PATH) ); //ローカル保存用のファイルネームを生成(iTunesItemID + AlbumArtworkFilename) $localArtworkFilename = $customValue[0]."_".$itmsArtworkFilename; //ImageFlowのアルバムをクリックした時のリンク先URLを生成 $artworkLinkUrl = get_permalink()."?ititem=".$key; //ローカルに保存してなければ、画像を保存 if(!file_exists(IMAGEFLOW_ABSOLUTE_DIR . "/img/" . $localArtworkFilename)){ file_put_contents(IMAGEFLOW_ABSOLUTE_DIR . "/img/" . $localArtworkFilename, file_get_contents($itmsArtworkUrl)); } //imgタグ用の画像URLを生成 $imgPath = 'img/' . $localArtworkFilename; //ImageFlow用のimgタグを表示 echo '<img src="' . $imgPath . '" longdesc="' . $artworkLinkUrl . '" width="100" height="100" alt="' . $itmsLookup->results[0]->collectionName . '">'; } echo '</div>'; ?> </div> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
custom_itunes.php
PHP
oos
4,005
<?php $template_type = get_post_type(get_the_ID()); include 'custom_' . $template_type . '.php'; ?>
014miharu-hirayama
single.php
PHP
oos
102
<?php /* Template Name: Event */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダー START --> <div id="header"> <h1><a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="平山美春 " title="平山美春 " /></a></h1> </div> <!-- //ヘッダー END// --> <!-- グローバルナビ START --> <div id="gnav" class="floatClear"> <ul class="navi"> <li class="gnav_01"><a href="<?php bloginfo('template_url'); ?>/single/profile/46/" title="Profile">Profile</a></li> <li class="gnav_02"><a href="<?php bloginfo('template_url'); ?>/event" title="Information" class="current">Information</a></li> <li class="gnav_03"><a href="#" title="Favorites!">Favorites!</a></li> <li class="gnav_04"><a href="<?php bloginfo('template_url'); ?>/blog" title="Blog">Blog</a></li> <li class="gnav_05"><a href="<?php bloginfo('template_url'); ?>/twitter" title="Twitter">Twitter</a></li> </ul> </div> <!-- //グローバルナビ END// --> <!-- コンテンツ START --> <div class="info_main clearfix"> <div id="main" class="clearfix"> <h2 class="info">Information</h2> <!-- //コンテンツタイトルEND// --> <!-- 検索条件START --> <?php if(!is_single()): ?> <div id="search_box"> <div class="category"> <p><img src="<?php bloginfo('template_url'); ?>/images/front/stitle_cat.png"></p> <?php echo get_selectbox_category(); ?> </div> <div class="monthly"> <p><img src="<?php bloginfo('template_url'); ?>/images/front/stitle_month.png"></p> <?php echo get_selectbox_monthly(); ?> </div> </div> <?php endif; ?> <!-- //検索条件END// --> <!-- ブログSTART --> <!-- ##シングルページへのアクセスだった場合(single.phpからのincludeの場合)は表示させるPostIDを取得 --> <?php if(is_single()){ $displayablePostID = get_the_ID();}else{$displayablePostID = "";} ?> <!-- ##Eventポスト取得のループ開始 --> <?php wp_reset_query();query_posts('post_type=event&meta_key=eventstart&orderby=meta_value&order=ASC'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <?php $event = get_event_meta(); ?> <!-- ##イベントの非表示条件を判定 --> <?php if(is_event_disable($event)){continue;} ?> <!-- ##シングルページの場合は、指定されたPostID以外は表示させない --> <?php if($displayablePostID !== "" && $displayablePostID !== get_the_ID()){ continue; } ?> <div class="info_box"> <div class="info_top"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <span class="date"><?php echo $event["startdate"]; ?></span> </div> <div class="info_body"> <p><img src="<?php bloginfo('template_url'); ?>/images/front/ico_<?php echo $event["category"]; ?>.png"></p> <div class="detail"><?php the_content(); ?></div> </div> </div> <div class="info_bottom"> <?php echo getLikeBottun(); ?> </div> <!-- //インフォ詳細END// --> <?php endwhile; ?> <?php endif; ?> <!-- //ブログEND// --> <!-- Pagetop START --> <div class="pagetop"> <p><a href="#">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> <!-- フッター START --> <div id="footer"> <p>Copyright&copy; LesPros Entertainment Co., Ltd. All rights reserved.</p> </div> <!-- //フッター END// --> </div> <?php function get_event_meta(){ $c = get_post_custom_values('eventstart', get_the_ID()); $event["startdate"] = $c[0]; $c = get_post_custom_values('eventend' , get_the_ID()); $event["enddate"] = $c[0]; $c = get_post_custom_values('opendate' , get_the_ID()); $event["opendate"] = $c[0]; $c = get_post_custom_values('closedate' , get_the_ID()); $event["closedate"] = $c[0]; $c = get_post_custom_values('category' , get_the_ID()); $event["category"] = $c[0]; if($event["enddate"] == "" || $event["enddate"] === $event["startdate"]){$event["datelabel"] = $event["startdate"];} if($event["enddate"] != "" && $event["enddate"] != $event["startdate"]){$event["datelabel"] = $event["startdate"] . " - " . $event["enddate"];} return $event; } function is_event_disable($event){ $filtered = false; // ##opendate <- -> closedate 以外であれば非表示 if( $event["opendate"] != ""){ if(strtotime( $event["opendate"] ) > time() ){ $filtered = true; }} if( $event["closedate"] != ""){ if(strtotime( $event["closedate"] ) < time() ){ $filtered = true; }} //##月指定があれば絞り込み if(isset($_REQUEST["mon"])){ $filter = date("Y", $_REQUEST["mon"]) . date("m", $_REQUEST["mon"]); $current = date("Y", strtotime($event["startdate"])) . date("m", strtotime($event["startdate"])); if($filter != $current){$filtered = true;} } //##カテゴリ指定があれば絞り込み if(isset($_REQUEST["cat"])){ if($_REQUEST["cat"] != $event["category"]){$filtered = true;} } return $filtered; } function get_selectbox_category(){ wp_reset_query(); query_posts('post_type=event'); if(have_posts()){ while(have_posts()){ the_post(); $e = get_event_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $cat = get_post_custom_values('category', get_the_ID()); $catList[$e["category"]] = ""; } } $catListKeys = array_keys($catList); $selectbox_html = "<select name='cat' id='cat' class='postform' >"; $selectbox_html .= "<option value=''>カテゴリーを選択</option>"; foreach($catListKeys as $k=>$v){ if($_REQUEST["cat"] === $v){$selected = "selected";}else{$selected = "";} $selectbox_html .= '<option class="level-0" value="' . $v . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var catdropdown = document.getElementById('cat');"; $selectbox_html .= " function onCatChange() {"; $selectbox_html .= " location.href = './?cat='+catdropdown.options[catdropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "catdropdown.onchange = onCatChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } function get_selectbox_monthly(){ wp_reset_query(); query_posts('post_type=event'); if(have_posts()){ while(have_posts()){ the_post(); $e = get_event_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $monthList[date("Y", strtotime($e["startdate"])) . "/" . date("n", strtotime($e["startdate"]))] = ""; } } $monthListKeys = array_keys($monthList); $selectbox_html = "<select name='mon' id='mon' class='postform' >"; $selectbox_html .= "<option value=''>月を選択</option>"; foreach($monthListKeys as $k=>$v){ if($_REQUEST["mon"] === strtotime($v."/1")){$selected = "selected";}else{$selected = "";} $selectbox_html .= '<option class="level-0" value="' . strtotime($v."/1") . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var mondropdown = document.getElementById('mon');"; $selectbox_html .= "function onMonChange() {"; $selectbox_html .= " location.href = './?mon='+mondropdown.options[mondropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "mondropdown.onchange = onMonChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } ?> <?php get_footer(); ?>
014miharu-hirayama
custom_event.php
PHP
oos
8,094
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="content-style-type" content="text/css"> <meta http-equiv="content-script-type" content="text/javascript"> <title>Blog</title> <link rel="stylesheet" type="text/css" href="base.css" media="all" /> <link rel="stylesheet" type="text/css" href="layout.css" media="all" /> <link rel="stylesheet" type="text/css" href="style.css" media="all" /> </head> <body><a name="pagetop" id="pagetop"></a> <div id="wrapper"> <!-- ヘッダー START --> <div id="header"> <h1><a href="index.html"><img src="images/front/img_h1.png" alt="Vivian Eastwood" title="Vivian Eastwood" /></a></h1> </div> <!-- //ヘッダー END// --> <!-- グローバルナビ START --> <div id="gnav" class="floatClear"> <ul class="navi"> <li class="gnav_01"><a href="prof.html" title="Profile">Profile</a></li> <li class="gnav_02"><a href="info.html" title="Information">Information</a></li> <li class="gnav_03"><a href="favorite.html" title="Favorites!">Favorites!</a></li> <li class="gnav_04"><a href="blog.html" title="Blog" class="current">Blog</a></li> <li class="gnav_05"><a href="twitter.html" title="Twitter">Twitter</a></li> </ul> </div> <!-- //グローバルナビ END// --> <!-- コンテンツWrapper START --> <div class="blog_main clearfix"> <!-- コンテンツ START --> <div id="main" class="clearfix"> <h2 class="blog">Blog</h2> <!-- ページネーションSTART --> <div class="pager clearfix"> <ul> <li class="now">1</li>| <li><a href="#">2</a></li>| <li><a href="#">3</a></li>| <li><a href="#">4</a></li>| <li><a href="#">5</a></li>| <li>...<a href="#">10</a></li> <li><a href="#">>></a></li> </ul> </div> <!-- //ページネーションEND// --> <!-- ブログ本文START --> <div class="blog_box"> <div class="blog_top"> <h3><a href="#">ブログタイトル</a></h3> <span class="date">2011年8月31日 24:59</span> </div> <div class="blog_body"> <p><img src="./images/front/img_blog01.jpg" /></p> <p class="detail">ここにブログ本文が入ります。</p> </div> </div> <div class="blog_bottom"> <iframe src="http://www.facebook.com/plugins/like.php?app_id=142967542457847&amp;href&amp;send=false&amp;layout=button_count&amp;width=72&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="none; overflow:hidden; width:72px; height:21px;" allowTransparency="true"></iframe> </div> <div class="blog_box"> <div class="blog_top"> <h3><a href="#">ブログタイトル</a></h3> <span class="date">2011年8月31日 24:59</span> </div> <div class="blog_body"> <p><img src="./images/front/img_blog01.jpg" /></p> <p class="detail">ここにブログ本文が入ります。</p> </div> </div> <div class="blog_bottom"> <iframe src="http://www.facebook.com/plugins/like.php?app_id=142967542457847&amp;href&amp;send=false&amp;layout=button_count&amp;width=72&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="none; overflow:hidden; width:72px; height:21px;" allowTransparency="true"></iframe> </div> <!-- //ブログ本文END// --> </div> <!-- //コンテンツ END// --> <!-- Pagetop START --> <div class="pagetop"> <p><a href="#pagetop">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> </div> <!-- コンテンツWrapper END// --> <!-- フッター START --> <div id="footer"> <p>Copyright&copy; LesPros Entertainment Co., Ltd. All rights reserved.</p> </div> <!-- //フッター END// --> </div> </body> </html>
014miharu-hirayama
blog.html
HTML
oos
4,547
<?php /* Template Name: PhotoGallary */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php echo get_global_menu(); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="photo_title"> <h2>Photo Gallery</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- フォトギャラリーSTART --> <?php query_posts('post_type=photogallery'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <div id="gallery_box"> <div class="photobox"> <p><a href="<?php the_permalink(); ?>"><img src="<?php get_featured_image_url(); ?>"></a></p> <p><?php the_title(); ?></p> <p><div class="btn_like"><?php echo getLikeBottun(); ?></div></p> </div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //フォトギャラリーEND// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
custom_photogallary.php
PHP
oos
1,361
<?php /* Template Name: Goods */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php echo get_global_menu(); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="photo_title"> <h2>Goods</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- グッズSTART --> <?php if(is_single()){ $displayablePostID = get_the_ID();}else{$displayablePostID = "";} ?> <?php query_posts('post_type=goods'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <?php if($displayablePostID !== "" && $displayablePostID !== get_the_ID()){ continue; } ?> <div id="goods_box"> <div class="goods_detail_box"> <p><a href="<?php echo get_post_meta($post->ID, 'リンク先', true); ?>" target="_blank"><img src="<?php get_featured_image_url(); ?>"></a></p> <p><?php echo get_post_meta($post->ID, '商品', true); ?></p> <p><?php echo get_post_meta($post->ID, '価格', true); ?>円(税込)</p> <p><a href="<?php echo get_post_meta($post->ID, 'リンク先', true); ?>" target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/front/btn_shop.gif"></a></p> <p><div class="btn_like"><?php echo getLikeBottun(); ?></div></p> </div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //グッズEND// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
custom_goods.php
PHP
oos
1,842
<?php /* Template Name: Blog */ get_header(); ?> <div id="wrapper"> <a name="pagetop" id="pagetop"></a> <?php run_layout(); ?> <?php get_footer(); ?>
014miharu-hirayama
custom_blog.php
PHP
oos
155
<?php /* Template Name: YouTube */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php echo do_shortcode("[gnavi]"); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="youtube_title"> <h2>YouTube</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- YouTube START --> <?php if(is_single()){ $displayablePostID = get_the_ID();}else{$displayablePostID = "";} ?> <?php query_posts('post_type=youtube'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <?php if($displayablePostID !== "" && $displayablePostID !== get_the_ID()){ continue; } ?> <div id="youtube_box"> <h3><?php echo get_post_meta($post->ID, 'タイトル', true); ?></h3> <object width="480" height="274"><param name="movie" value="http://www.youtube.com/v/<?php echo get_post_meta($post->ID, 'URL', true); ?>"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/<?php echo get_post_meta($post->ID, 'URL', true); ?>" type="application/x-shockwave-flash" width="480" height="274" allowscriptaccess="always" allowfullscreen="true"></embed></object> <p class="video_txt"><?php echo get_post_meta($post->ID, '説明文', true); ?></p> <div class="btn_area"><div class="btn_like"> <!-- <iframe src="http://www.facebook.com/plugins/like.php?href=http://www.youtube.com/watch?v=<?php echo get_post_meta($post->ID, 'URL', true); ?>&amp;send=false&amp;layout=button_count&amp;width=200&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:20px;" allowTransparency="true"></iframe> --> <?php echo getLikeBottun(); ?> </div></div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //You Tube END// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
custom_youtube.php
PHP
oos
2,423
<?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php wp_nav_menu(array('theme_location' => 'navbar', 'container_id' => 'navigation', 'menu_id' => 'gnav')); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="photo_title"> <h2>Photo Gallery</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- フォトギャラリーSTART --> <?php query_posts('post_type=photogallery'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> <?php endif; ?> <!-- //フォトギャラリーEND// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
single-photogallery.php
PHP
oos
1,155
<?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1>紗羅マリーfacebook page</h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php wp_nav_menu(array('theme_location' => 'navbar', 'container_id' => 'navigation', 'menu_id' => 'gnav')); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="photo_title"> <h2>Photo Gallery</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- インフォ詳細START --> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <div id="gallery_box"> <h3 class="floatClear"></h3> <?php $url_large = wp_get_attachment_image_src($id, $size='large'); ?> <p class="photo_detail"><img src="<?php echo $url_large[0] ?>"></p> <div class="like_box"> <div class="btn_like"> <?php echo getLikeBottun($app_id); ?> </div> </div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //インフォ詳細END// --> <!-- フッターSTART --> <div id="footer"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
attachment.php
PHP
oos
1,378
html .mceContentBody {max-width: 800px;} h3 {font-size: 16px; border-left: solid 12px #8bc124; padding-left: 10px;} p {font-size: 14px; line-height: 1.5; margin: 0 0 20px;} /* 画像 */ .alignleft {float: left; margin-right: 20px; margin-bottom: 20px;} .alignright {float: right; margin-left: 20px; margin-bottom: 20px;} .aligncenter {clear: both; display: block; margin: 25px auto;} a img {border: none;}
014miharu-hirayama
editor-style.css
CSS
oos
425
<?php if ($handle = opendir('.')) { $style_def = array(); $style_hover = array(); while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && findexts($file) === 'png') { list($width_image) = @getimagesize($file); $file_uname = split("_", str_replace(".png", "", $file)); if ( isset( $file_uname[1] ) ){ $style_name = sprintf("%-17s", '.menu_' . ucwords($file_uname[1])); $style_width = sprintf("width:%9s", $width_image .'px; '); $style_image = sprintf("%-55s", 'background:url("../images/menu/'.$file.'")' ); $style_pos = "0px 0px no-repeat;"; array_push($style_def , sprintf("%s{ %s}\n", $style_name, $style_width . $style_image . $style_pos ) ); $style_pos = "0px -35px no-repeat;"; array_push($style_hover, sprintf("%s a:hover, %s a.current { %s}\n", $style_name, $style_name, $style_width . $style_image . $style_pos )); } } } closedir($handle); print implode( '', $style_def ); echo "\n"; print implode( '', $style_hover ); echo "\n"; /* .menu_Profile { width: 96px; background:url("../images/menu/gnav_profile.png") 0px 0px no-repeat;} .menu_Profile a:hover, .menu_Profile a.current { width: 96px; background:url("../images/menu/gnav_profile.png") 0px -35px no-repeat;} .menu_Info a:hover, .menu_Info a.current { width: 132px; background:url("../images/menu/gnav_info.png") 0px -35px no-repeat;} .menu_Favorites a:hover, .menu_Favorites a.current { width: 117px; background:url("../images/menu/gnav_favorites.png") 0px -35px no-repeat;} .menu_iTunes a:hover, .menu_iTunes a.current { width: 0px; background:url("../images/menu/gnav_itunes.png") 0px -35px no-repeat;} .menu_YouTube a:hover, .menu_TouTube a.current { width: 0px; background:url("../images/menu/gnav_youtube.png") 0px -35px no-repeat;} .menu_PhotoGraph a:hover, .menu_PhotoGraph a.current { width: 0px; background:url("../images/menu/gnav_photograph.png") 0px -35px no-repeat;} .menu_Blog a:hover, .menu_Blog a.current { width: 77px; background:url("../images/menu/gnav_blog.png") 0px -35px no-repeat;} .menu_Twitter a:hover, .menu_Twitter a.current { width: 98px; background:url("../images/menu/gnav_twitter.png") 0px -35px no-repeat;} */ } function findexts($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //$buf_image = @getimagesize($image); ?>
014miharu-hirayama
images/menu/create_style.php
PHP
oos
2,552
@charset "utf-8"; /*------------------------------Base Setting */ h1, h2, h3, h4, h5, h6, p, ul, ol, dl, dt, dd, li, table, th, td, form, select, option, address, pre, strong, em, p { padding: 0; margin: 0; } body{ padding: 0; margin: 0; width:100%; font-size:13px; font-family:Verdana,Arial,sans-serif; line-height:1; } * html body { font-family: 'MS Pゴシック',sans-serif; } *:first-child+html body { font-family: 'メイリオ','MS Pゴシック',sans-serif; } select,input,button,textarea,button { font:99% arial,helvetica,clean,sans-serif; } #wrapper { width:520px; margin:0 auto; background-color:#ffffff; color:#000; } a img { border:none; } .floatClear { clear: both; } .clearfix { overflow: visible; } .clearfix:after { content:"."; display:block; height:1px; clear:both; visibility:hidden; } table { font-size:inherit; font:100%; border-collapse:collapse; border-spacing:0; } ol, ul { list-style: none; } /*------------------------------FONT-SIZE */ /* 10px = 77% 11px = 85% 12px = 93% 13px = 100% 14px = 108% 15px = 116% 16px = 123.1% 17px = 131% 18px = 138.5% 19px = 146.5% 20px = 153.9% 21px = 161.6% 22px = 167% 23px = 174% 24px = 182% 25px = 189% 26px = 197% */ .txt_bold { font-weight:bold; } .txt_11 { font-size:85%; } .txt_12 { font-size:93%; } .txt_13 { font-size:100%; } .txt_14 { font-size:108%; } .txt_15 { font-size:116%; } .txt_16 { font-size:123.1%; } .wb_fb_comment { background-color: transparent; } #twimg { margin-top: 15px; } #bread { margin-left: 20px; }
014miharu-hirayama
base.css
CSS
oos
1,565
<?php /* Template Name: osusume */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php echo get_global_menu(); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="osusume_title"> <h2><?php the_title(); ?></h2> </div> <!-- //コンテンツタイトルEND// --> <!-- おすすめコーデSTART --> <?php if(is_single()){ $displayablePostID = get_the_ID();}else{$displayablePostID = "";} ?> <?php query_posts('post_type=osusume'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <?php if($displayablePostID !== "" && $displayablePostID !== get_the_ID()){ continue; } ?> <!-- コメントSTART --> <?php the_content(); ?> <!-- コメントEND --> <div id="osusume_box"> <table class="codelist"> <?php $image = "<img src='/wp-admin/images/none120x120.jpg'>"; $title = "サンプルタイトル"; $price = ' \15,000 ( \20,000 ) '; $comment = "サンプルコメント"; $color = <<<SELECT_COLOR <dl> <dt style="float:left;">カラー</dt> <dd> <select name="classcategory_id1" style=""> <option value="">選択してください</option> </select> </dd> </dl> SELECT_COLOR; $size = <<<SELECT_SIZE <dl> <dt style="float:left;">サイズ</dt> <dd> <select name="classcategory_id2" style=""> <option value="">選択してください</option> </select> </dd> </dl> SELECT_SIZE; $buynow = <<<BUYNOW <input type="checkbox" name="" value="">この商品を購入する BUYNOW; $code_item = <<<CODE_ITEM <tr><td rowspan="6"> $image <!-- イメージ --> </td> <td class=" "> <!-- タイトル --> $title </td></tr> <tr> <td class=" "> <!-- 価格 --> $price </td></tr> <tr> <td class=" "> <!-- 一覧コメント --> $comment </td></tr> <tr> <td class=" "> <!-- カラー --> $color</td></tr> <tr> <td class=" "> <!-- サイズ --> $size </td></tr> <tr> <td class=" "> <!-- 購入する --> $buynow </td></tr> CODE_ITEM; echo $code_item; // デザインサンプル出力 $products = get_post_meta($post->ID, sprintf("products", $c), true); eval( file_get_contents( PACKAGE_ROOT."/lib/osusume_code.php") ); ?> </table> </div> <?php endwhile; ?> <?php endif; ?> <!-- //おすすめコーデEND// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
custom_osusume.php
PHP
oos
3,202
<?php get_header(); ?> <?php get_footer(); ?>
014miharu-hirayama
index.php
PHP
oos
47
<?php function parse_signed_request($signed_request, $secret) { list($encoded_sig, $payload) = explode('.', $signed_request, 2); // decode the data $sig = base64_url_decode($encoded_sig); $data = json_decode(base64_url_decode($payload), true); if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') { error_log('Unknown algorithm. Expected HMAC-SHA256'); return null; } // check sig $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true); if ($sig !== $expected_sig) { // error_log('Bad Signed JSON signature!'); return null; } return $data; } function base64_url_decode($input) { return base64_decode(strtr($input, '-_', '+/')); } ?>
014miharu-hirayama
signed_request.php
PHP
oos
668
<?php get_header(); ?> <?php get_footer(); ?>
014miharu-hirayama
page.php
PHP
oos
47
<?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php wp_nav_menu(array('theme_location' => 'navbar', 'container_id' => 'navigation', 'menu_id' => 'gnav')); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="goods_title"> <h2>Goods</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- グッズ詳細START --> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <div id="gallery_box"> <h3 class="floatClear"></h3> <p><img src="<?php get_featured_image_url(); ?>"></a></p> <p><?php echo get_post_meta($post->ID, '商品', true); ?></p> <p><?php echo get_post_meta($post->ID, '価格', true); ?>円(税込)</p> <p><a href="<?php echo get_post_meta($post->ID, 'リンク先', true); ?>" target="_blank"><img src="<?php bloginfo('template_url'); ?>/images/front/btn_shop.gif"></a></p> <div class="like_box"> <div class="btn_like"> <?php echo getLikeBottun(); ?> </div> </div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //グッズ詳細END// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
single-goods.php
PHP
oos
1,615
<?php /* Template Name: Info */ get_header(); ?> <div id="wrapper"> <a name="pagetop" id="pagetop"></a> <?php run_layout(); ?> <?php get_footer(); ?>
014miharu-hirayama
custom_info.php
PHP
oos
155
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="content-style-type" content="text/css"> <meta http-equiv="content-script-type" content="text/javascript"> <title>Information</title> <link rel="stylesheet" type="text/css" href="base.css" media="all" /> <link rel="stylesheet" type="text/css" href="layout.css" media="all" /> <link rel="stylesheet" type="text/css" href="style.css" media="all" /> </head> <body><a name="pagetop" id="pagetop"></a> <div id="wrapper"> <!-- ヘッダー START --> <div id="header"> <h1><a href="index.html"><img src="images/front/img_h1.png" alt="平山美春" title="平山美春" /></a></h1> </div> <!-- //ヘッダー END// --> <!-- グローバルナビ START --> <div id="gnav" class="floatClear"> <ul class="navi"> <li class="gnav_01"><a href="prof.html" title="Profile">Profile</a></li> <li class="gnav_02"><a href="info.html" title="Information">Information</a></li> <li class="gnav_03"><a href="favorite.html" title="Favorites!" class="current">Favorites!</a></li> <li class="gnav_04"><a href="blog.html" title="Blog">Blog</a></li> <li class="gnav_05"><a href="twitter.html" title="Twitter">Twitter</a></li> </ul> </div> <!-- //グローバルナビ END// --> <!-- コンテンツ START --> <div class="info_main clearfix"> <div id="main" class="clearfix"> <h2 class="favorites">Favorites!</h2> <form method="" action=""> <!-- アイテム詳細START --> <div class="fav_box clearfix"> <p class="fav_img"><img src="./images/front/img_item01.jpg" width="148" /></p> <div class="fav_item"> <h3 class="fav_title txt_16"><a href="#">ファーベレーボウ</a></h3> <p class="fav_price txt_16">¥1,990<span class="txt_12">本体価格(¥1,896)</span></p> <p class="fav_detail txt_12">ふわふわの素材感が魅力のトレンド小物で甘さをアピール。</p> <label class="txt_12">カラー <select> <option value="">選択</option> <option value="">BLACK</option> <option value="">WHITE</option> <option value="">BLUE</option> <option value="">RED</option> </select> </label> <label class="txt_12">サイズ <select> <option value="">選択</option> <option value="">S</option> <option value="">M</option> <option value="">L</option> </select> </label> <label class="txt_12"> <input type="checkbox" />この商品を購入する </label> </div> </div> <!-- //アイテム詳細END// --> <!-- アイテム詳細START --> <div class="fav_box clearfix"> <p class="fav_img"><img src="./images/front/img_item01.jpg" width="148" /></p> <div class="fav_item"> <h3 class="fav_title txt_16"><a href="#">ファーベレーボウ</a></h3> <p class="fav_price txt_16">¥1,990<span class="txt_12">本体価格(¥1,896)</span></p> <p class="fav_detail txt_12">ふわふわの素材感が魅力のトレンド小物で甘さをアピール。</p> <label class="txt_12">カラー <select> <option value="">選択</option> <option value="">BLACK</option> <option value="">WHITE</option> <option value="">BLUE</option> <option value="">RED</option> </select> </label> <label class="txt_12">サイズ <select> <option value="">選択</option> <option value="">S</option> <option value="">M</option> <option value="">L</option> </select> </label> <label class="txt_12"> <input type="checkbox" />この商品を購入する </label> </div> </div> <!-- //アイテム詳細END// --> <!-- アイテム詳細START --> <div class="fav_box clearfix"> <p class="fav_img"><img src="./images/front/img_item01.jpg" width="148" /></p> <div class="fav_item"> <h3 class="fav_title txt_16"><a href="#">ファーベレーボウ</a></h3> <p class="fav_price txt_16">¥1,990<span class="txt_12">本体価格(¥1,896)</span></p> <p class="fav_detail txt_12">ふわふわの素材感が魅力のトレンド小物で甘さをアピール。</p> <label class="txt_12">カラー <select> <option value="">選択</option> <option value="">BLACK</option> <option value="">WHITE</option> <option value="">BLUE</option> <option value="">RED</option> </select> </label> <label class="txt_12">サイズ <select> <option value="">選択</option> <option value="">S</option> <option value="">M</option> <option value="">L</option> </select> </label> <label class="txt_12"> <input type="checkbox" />この商品を購入する </label> </div> </div> <!-- //アイテム詳細END// --> <!-- //ボデル着用ボタンSTART --> <p class="fav_model clearfix"> <a href="#">モデル着用PHOTO</a> </p> <!-- //購入ボタンEND// --> <!-- //購入ボタンSTART --> <div class="fav_button"> <input type="submit" value="" id="fav_buy" /> </div> <!-- //購入ボタンEND// --> </form> </div> <!-- //コンテンツ END// --> <!-- Pagetop START --> <div class="pagetop"> <p><a href="#pagetop">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> </div> <!-- フッター START --> <div id="footer"> <p>Copyright&copy; LesPros Entertainment Co., Ltd. All rights reserved.</p> </div> <!-- //フッター END// --> </div> </body> </html>
014miharu-hirayama
favorite.html
HTML
oos
7,625
<!-- Footer START --> <div id="footer"> <p>Copyright&copy; LesPros Entertainment Co., Ltd. All rights reserved.</p> </div> <!-- //Footer END// --> <div> <?php wp_footer(); ?> </body> </html>
014miharu-hirayama
footer.php
PHP
oos
217
<?php $q = get_posts('post_type=mastercontrol&posts_per_page=1'); $qq = get_post_custom_values('appid', $q[0]->ID); if($qq[0] == ""){$APP_ID = "";}else{$APP_ID = $qq[0];} define("APP_ID", $APP_ID); $qq = get_post_custom_values('appsecret', $q[0]->ID); if($qq[0] == ""){$SECRET_KEY = "";}else{$SECRET_KEY = $qq[0];} define("SECRET_KEY", $SECRET_KEY); $qq = get_post_custom_values('facebookurl', $q[0]->ID); if($qq[0] == ""){$FB_URL = "";}else{$FB_URL = $qq[0];} define("FB_URL", $FB_URL); $qq = get_post_custom_values('page_id', $q[0]->ID); if($qq[0] == ""){$PAGE_ID = "";}else{$PAGE_ID = $qq[0];} define("PAGE_ID", $PAGE_ID); $qq = get_post_custom_values('access_token', $q[0]->ID); if($qq[0] == ""){$ACCESS_TOKEN = "";}else{$ACCESS_TOKEN = $qq[0];} define("ACCESS_TOKEN", $ACCESS_TOKEN); $qq = get_post_custom_values('enable_site', $q[0]->ID); if($qq[0] == ""){$ENABLE_SITE = "";}else{$ENABLE_SITE = $qq[0];} define("ENABLE_SITE", $ENABLE_SITE); $qq = get_post_custom_values('fbpage_only', $q[0]->ID); if($qq[0] == ""){$FBPAGE_ONLY = false;}else{$FBPAGE_ONLY = true;} define("FBPAGE_ONLY", $FBPAGE_ONLY); ?>
014miharu-hirayama
conf/facebook_const.php
PHP
oos
1,146
<?php loadIframeFB(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xml:lang="ja" lang="ja"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-style-type" content="text/css"> <meta http-equiv="content-script-type" content="text/javascript"> <title><?php bloginfo('name'); ?> facebook page</title> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" /> <link rel="stylesheet" href="<?php echo get_custom_templateurl(); ?>/base.css" type="text/css" /> <link rel="stylesheet" href="<?php echo get_custom_templateurl(); ?>/rayout.css" type="text/css" /> <?php echo do_shortcode('[ogp_meta]'); redirectFB(); wp_head(); ?> </head> <body>
014miharu-hirayama
header.php
PHP
oos
870
<?php /* Template Name: Profile */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダー START --> <div id="header"> <h1><a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="平山美春 " title="平山美春 " /></a></h1> </div> <!-- //ヘッダー END// --> <!-- グローバルナビ START --> <?php echo do_shortcode("[gnavi]"); ?> <!-- //グローバルナビ END// --> <div id="main" class="prof_main clearfix"> <h2 class="prof">Profile</h2> <!-- コンテンツ START --> <?php query_posts('post_type=profile'); ?> <?php if(have_posts()): ?> <?php the_post(); ?> <?php the_content(); ?> <?php endif; ?> <!-- //コンテンツ END// --> <?php get_footer(); ?>
014miharu-hirayama
custom_profile.php
PHP
oos
832
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="content-style-type" content="text/css"> <meta http-equiv="content-script-type" content="text/javascript"> <title>平山美春 facebook page</title> <link rel="stylesheet" type="text/css" href="base.css" media="all" /> <link rel="stylesheet" type="text/css" href="layout.css" media="all" /> <link rel="stylesheet" type="text/css" href="style.css" media="all" /> </head> <body><a name="pagetop" id="pagetop"></a> <div id="wrapper"> <!-- ヘッダー START --> <div id="header"> <h1><a href="index.html"><img src="images/front/img_h1.png" alt="Vivian Eastwood" title="Vivian Eastwood" /></a></h1> </div> <!-- //ヘッダー END// --> <!-- グローバルナビ START --> <div id="gnav" class="floatClear"> <ul class="navi"> <li class="gnav_01"><a href="prof.html" title="Profile" class="current">Profile</a></li> <li class="gnav_02"><a href="info.html" title="Information">Information</a></li> <li class="gnav_03"><a href="favorite.html" title="Favorites!">Favorites!</a></li> <li class="gnav_04"><a href="blog.html" title="Blog">Blog</a></li> <li class="gnav_05"><a href="twitter.html" title="Twitter">Twitter</a></li> </ul> </div> <!-- //グローバルナビ END// --> <!-- コンテンツ START --> <div id="main" class="prof_main clearfix"> <h2 class="prof">Profile</h2> <div class="prof_img"> <img src="./images/front/img_prof.jpg" alt="平山美春" title="平山美春" /> </div> <div class="prof_msg clearfix"> <h3>平山美春</h3> <p class="bd">1987年2月18日 生まれ</p> <p class="p_data">星座 : みずがめ座<br /> 血液型 : A型<br /> 出身地 : 大阪府<br /> 特技 : フランス語、乗馬<br /> 趣味 : ゴルフ、料理、スポーツ観戦 </p> <p class="p_data">上記ベーシックなプロフィール情報のほか、一言メッセージなどの掲載も可能です。</p> </div> </div> <!-- //コンテンツ END// --> <!-- フッター START --> <div id="footer"> <p>Copyright&copy; LesPros Entertainment Co., Ltd. All rights reserved.</p> </div> <!-- //フッター END// --> </div> </body> </html>
014miharu-hirayama
prof.html
HTML
oos
2,369
<?php /* Template Name: multiblog */ ?> <?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php echo get_global_menu(); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <a title="TOP" href="<?php bloginfo('url'); ?>">TOP</a>&nbsp;&gt;&nbsp;&nbsp;Blog </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="blog_title"> <h2>Blog</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- ブログSTART --> <?php query_posts('post_type=multiblog'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <div id="blog_box"> <div class="blog_txt"> <h4><?php the_title(); ?></h3> <p class="logdate"><?php echo get_the_date('Y年m月d日'); ?></p> <p><?php echo str_replace("img src=", "img width=320 src=", get_the_content()); ?></p> <p class="readmore">&gt;&gt;<a href="<?php echo get_post_meta($post->ID,'syndication_permalink',true); ?>" target="_blank">続きをみる</a></p> </div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //ブログEND// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
custom_multiblog.php
PHP
oos
1,476
<?php get_header(); ?> <a name="pagetop" id="pagetop"></a> <div id="wrapper"> <!-- ヘッダー START --> <div id="header"> <h1><a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="平山美春 " title="平山美春 " /></a></h1> </div> <!-- //ヘッダー END// --> <!-- グローバルナビ START --> <?php echo do_shortcode("[gnavi]"); ?> <!-- //グローバルナビ END// --> <!-- コンテンツ START --> <div id="main" class="top_main clearfix"> <div class="top_img"> <img src="<?php bloginfo('template_url'); ?>/images/front/img_top.jpg" alt="kozue akimoto" title="kozue akimoto" /> </div> <div class="top_msg clearfix"> <em>Welcome !!</em> <p>平山 美春(ひらやま みはる)は、レプロエンタテインメント所属のファッションモデルとして活躍中です!</p> <p>女性ファッション雑誌「CanCam」(小学館)の専属モデル。</p> <p>趣味はスポーツ観戦、芸術鑑賞、ショッピング。</p> </div> </div> <!-- //コンテンツ END// --> <?php get_footer(); ?>
014miharu-hirayama
home.php
PHP
oos
1,137
@charset "utf-8"; /*------------------------------Gloval Navi */ #gnav { width:520px; height:35px; } .navi { width:520px; height:35px; margin: 0; padding: 0; //background:url("../images/menu/bg_gnav.png") 0 0 repeat-x; } .navi li, .navi a { height: 35px; display: block; } .navi li { float: left; list-style: none; display: inline; text-indent: -9999em; } .menu_Twitter { width: 90px; background:url("../images/menu/gnav_twitter.png") 0px 0px no-repeat;} .menu_Blog { width: 90px; background:url("../images/menu/gnav_blog.png") 0px 0px no-repeat;} .menu_Info { width: 125px; background:url("../images/menu/gnav_info.png") 0px 0px no-repeat;} .menu_Favorites { width: 125px; background:url("../images/menu/gnav_favorites.png") 0px 0px no-repeat;} .menu_Profile { width: 90px; background:url("../images/menu/gnav_profile.png") 0px 0px no-repeat;} .menu_Twitter a:hover, .menu_Twitter a.current { width: 90px; background:url("../images/menu/gnav_twitter.png") 0px -35px no-repeat;} .menu_Blog a:hover, .menu_Blog a.current { width: 90px; background:url("../images/menu/gnav_blog.png") 0px -35px no-repeat;} .menu_Info a:hover, .menu_Info a.current { width: 125px; background:url("../images/menu/gnav_info.png") 0px -35px no-repeat;} .menu_Favorites a:hover, .menu_Favorites a.current { width: 125px; background:url("../images/menu/gnav_favorites.png") 0px -35px no-repeat;} .menu_Profile a:hover, .menu_Profile a.current { width: 90px; background:url("../images/menu/gnav_profile.png") 0px -35px no-repeat;}
014miharu-hirayama
css/gnavi-type01-07.css
CSS
oos
1,680
@charset "utf-8"; /*------------------------------Gloval Navi */ #gnav { width:520px; height:35px; } .navi { width:520px; height:35px; margin: 0; padding: 0; //background:url("../images/menu/bg_gnav.png") 0 0 repeat-x; } .navi li, .navi a { height: 35px; display: block; } .navi li { float: left; list-style: none; display: inline; text-indent: -9999em; } .menu_Twitter { width: 90px; background:url("../images/menu/gnav_twitter.png") 0px 0px no-repeat;} .menu_Blog { width: 90px; background:url("../images/menu/gnav_blog.png") 0px 0px no-repeat;} .menu_Info { width: 125px; background:url("../images/menu/gnav_info.png") 0px 0px no-repeat;} .menu_Favorites { width: 125px; background:url("../images/menu/gnav_favorites.png") 0px 0px no-repeat;} .menu_Profile { width: 90px; background:url("../images/menu/gnav_profile.png") 0px 0px no-repeat;} .menu_Twitter a:hover, .menu_Twitter a.current { width: 90px; background:url("../images/menu/gnav_twitter.png") 0px -35px no-repeat;} .menu_Blog a:hover, .menu_Blog a.current { width: 90px; background:url("../images/menu/gnav_blog.png") 0px -35px no-repeat;} .menu_Info a:hover, .menu_Info a.current { width: 125px; background:url("../images/menu/gnav_info.png") 0px -35px no-repeat;} .menu_Favorites a:hover, .menu_Favorites a.current { width: 125px; background:url("../images/menu/gnav_favorites.png") 0px -35px no-repeat;} .menu_Profile a:hover, .menu_Profile a.current { width: 90px; background:url("../images/menu/gnav_profile.png") 0px -35px no-repeat;}
014miharu-hirayama
css/gnavi05.css
CSS
oos
1,680
@charset "utf-8"; /*------------------------------Gloval Navi */ #gnav { width:520px; height:35px; } .navi { width:520px; height:35px; margin: 0; padding: 0; //background:url("../images/menu/bg_gnav.png") 0 0 repeat-x; } .navi li, .navi a { height: 35px; display: block; } .navi li { float: left; list-style: none; display: inline; text-indent: -9999em; } .menu_Twitter { width: 90px; background:url("../images/menu/gnav_twitter.png") 0px 0px no-repeat;} .menu_Blog { width: 90px; background:url("../images/menu/gnav_blog.png") 0px 0px no-repeat;} .menu_Info { width: 125px; background:url("../images/menu/gnav_info.png") 0px 0px no-repeat;} .menu_Favorites { width: 125px; background:url("../images/menu/gnav_favorites.png") 0px 0px no-repeat;} .menu_Profile { width: 90px; background:url("../images/menu/gnav_profile.png") 0px 0px no-repeat;} .menu_Twitter a:hover, .menu_Twitter a.current { width: 90px; background:url("../images/menu/gnav_twitter.png") 0px -35px no-repeat;} .menu_Blog a:hover, .menu_Blog a.current { width: 90px; background:url("../images/menu/gnav_blog.png") 0px -35px no-repeat;} .menu_Info a:hover, .menu_Info a.current { width: 125px; background:url("../images/menu/gnav_info.png") 0px -35px no-repeat;} .menu_Favorites a:hover, .menu_Favorites a.current { width: 125px; background:url("../images/menu/gnav_favorites.png") 0px -35px no-repeat;} .menu_Profile a:hover, .menu_Profile a.current { width: 90px; background:url("../images/menu/gnav_profile.png") 0px -35px no-repeat;}
014miharu-hirayama
css/gnavi.css
CSS
oos
1,680
@charset "utf-8"; /*------------------------------Link */ a:link,a:visited { color:#595959; text-decoration:none; } a:hover { color:#595959; text-decoration:underline; } /*------------------------------Header */ #header { width:520px; height:115px; margin:0; background:url(./images/front/bg_header.jpg) no-repeat 0 0; } #header h1 { width:485px; height:66px; margin:0; position:relative; top:27px; left:20px; } /*------------------------------Gloval Navi */ #gnav { width:520px; height:35px; } .navi { width:520px; height:35px; margin: 0; padding: 0; } .navi li, .navi a { height: 35px; display: block; } .navi li { float: left; list-style: none; display: inline; text-indent: -9999em; } .gnav_01 { width: 90px; background:url("./images/front/gnav_prof.png") 0 0 no-repeat; } .gnav_02 { width: 125px; background:url("./images/front/gnav_info.png") 0 0 no-repeat;} .gnav_03 { width: 125px; background:url("./images/front/gnav_favorites.png") 0 0 no-repeat;} .gnav_04 { width: 90px; background:url("./images/front/gnav_blog.png") 0 0 no-repeat;} .gnav_05 { width: 90px; background:url("./images/front/gnav_twitter.png") 0 0 no-repeat;} .gnav_01 a:hover { background:url("./images/front/gnav_prof.png") 0px -35px no-repeat; } .gnav_02 a:hover { background:url("./images/front/gnav_info.png") 0px -35px no-repeat; } .gnav_03 a:hover { background:url("./images/front/gnav_favorites.png") 0px -35px no-repeat; } .gnav_04 a:hover { background:url("./images/front/gnav_blog.png") 0px -35px no-repeat; } .gnav_05 a:hover { background:url("./images/front/gnav_twitter.png") 0px -35px no-repeat; } .gnav_01 a.current { background:url("./images/front/gnav_prof.png") 0px -35px no-repeat; } .gnav_02 a.current { background:url("./images/front/gnav_info.png") 0px -35px no-repeat; } .gnav_03 a.current { background:url("./images/front/gnav_favorites.png") 0px -35px no-repeat; } .gnav_04 a.current { background:url("./images/front/gnav_blog.png") 0px -35px no-repeat; } .gnav_05 a.current { background:url("./images/front/gnav_twitter.png") 0px -35px no-repeat; } /*------------------------------Main Content */ #main { width:520px; } /*------------------------------Content H2 */ h2.prof { width:520px; height:85px; margin:0 auto 29px; background:url("./images/front/h2_prof.png") 0 0 no-repeat; text-indent:-9999px; } h2.info { width:520px; height:85px; margin:0 auto 11px; background:url("./images/front/h2_info.png") 0 0 no-repeat; text-indent:-9999px; } h2.favorites { width:520px; height:85px; margin:0 auto 29px; background:url("./images/front/h2_fav.png") 0 0 no-repeat; text-indent:-9999px; } h2.blog { width:520px; height:85px; margin:0 auto 29px; background:url("./images/front/h2_blog.png") 0 0 no-repeat; text-indent:-9999px; } h2.twitter { width:520px; height:94px; margin:0 auto; background:url("./images/front/h2_twitter.png") 0 0 no-repeat; text-indent:-9999px; } /*------------------------------Page Nation */ .pager { width:500px; margin:0 auto 20px; font-size:93%; text-align:center; } .pager ul { width:410px; height:20px; float:right; color:#595959; } .pager ul li { margin:0 5px; display:inline-block; } .pager .now { font-weight:bold; text-decoration:underline; } /*------------------------------Page Top */ .pagetop { width:510px; text-align:right; font-size:85%; padding-right:10px; margin:10px 0; } /*------------------------------Powerd */ #powerd { width:520px; height:25px; margin:5px auto 0; text-align:right; font-size:10px; } #powerd a { color:#3b5998; text-decoration:none; } #powerd a:hover { color:#3b5998; text-decoration:underline; } .likeCountArrow { background:url("./images/front/ico_likethum.png") left center no-repeat; padding-left:15px; margin-left:10px; } /*------------------------------Footer */ #footer { width:520px; height:25px; margin:0; background:url(./images/front/bg_footer.jpg) repeat-x 0 0 #000; text-align:center; } #footer p { color:#fff; padding-top:10px; font-size:77%; }
014miharu-hirayama
rayout.css
CSS
oos
4,042
<?php function wall_post( $og_image, $og_url, $og_title, $message ){ $fanpage = PAGE_ID; $page_token = ACCESS_TOKEN; if ( $page_token !== "" ): $ch = curl_init(); $params = 'access_token=' . urlencode($page_token); $params .= '&picture=' . urlencode($og_image); $params .= '&link=' . urlencode($og_url); $params .= '&name=' . urlencode($og_title); $params .= '&message=' .urlencode(''); curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$fanpage.'/feed'); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $resp = curl_exec($ch); curl_close($ch); endif; } $wppostfix = new WpPostFix(); add_action('save_post', array($wppostfix, 'postfix'), 99); class WpPostFix { function postfix($postID) { global $wpdb; list($result) = $wpdb->get_results("SELECT post_status,post_title,post_type,post_content FROM {$wpdb->posts} WHERE ID = '{$postID}' LIMIT 1"); $post_status = $result->post_status; $content = $result->post_content; $post_type = $result->post_type; $og_title = $result->post_title; // 誤動作防止 if ( get_bloginfo("siteurl") !== ENABLE_SITE ) { return $postID; } $single_page_url = '/single/' . $post_type . '/' . $postID; $og_url = get_bloginfo("siteurl") . $single_page_url . '?app_data=' . urlencode(base64_encode($single_page_url)); // 画像 content 内 $default_img = get_bloginfo("template_url") . "/screenshot.png"; $all_images = (preg_match_all('~img.+?src="([^"]+?)"~', $content, $matches)) ? array_unique($matches[1]) : array($default_img); $maxwidth = 0; foreach ( $all_images as $image ) : $buf_image = @getimagesize($image); if ( $buf_image[0] > $maxwidth ){ $maxwidth = $buf_image[0]; $og_image = $image; } endforeach; if ( empty($og_image) ) { $og_image = $default_img; } // 画像 ここまで if ( $post_type === "blog" ): /* // コンテンツ書き換え $content = $this->blogcontent($post_status, $content); // DB をなおした内容でアップデートする $wpdb->query("UPDATE {$wpdb->posts} SET post_content = '{$content}' WHERE ID = '{$postID}'"); */ // 公開の投稿をウォールへポスト if ( $post_status === 'publish' ){ // ウォールへポスト wall_post( $og_image, $og_url, $og_title, $message ); } endif; // 次の人のために post_id 戻しておく return $postID; } function blogcontent($post_type, $content) { // 書き換えたい内容を記載 $before = 'hogehoge'; $after = 'mogemoge'; $after = $post_type; $content = preg_replace("/$before/i", $after, $content); // 戻す return $content; } } ?>
014miharu-hirayama
lib/wallpost.php
PHP
oos
3,015
<?php function footer_html(){ $likeCount = facebook_likeCount("http://www.facebook.com/stockstyle"); print <<<FOOTER_STYLE <div id="powerd"> Powerd by&nbsp;<a href="https://www.facebook.com/stockstyle">STOCK STYLE</a> <span class="likeCountArrow"><span>$likeCount</span></span> </div> FOOTER_STYLE; } add_action( 'wp_footer', 'footer_html' ); ?>
014miharu-hirayama
lib/func_footer.php
PHP
oos
356
<?php // プラグイン //remove_action( 'wp_head', 'wordbooker_header' ); remove_action( 'wp_head', 'wpogp_auto_include' ); remove_action( 'wp_head', 'wp_page_numbers_stylesheet' ); remove_action( 'wp_head', 'widget_akismet_style' ); remove_action( 'wp_head', 'feed_links' ); // システム remove_action( 'wp_head', 'feed_links'); remove_action( 'wp_head', 'feed_links_extra'); remove_action( 'wp_head', 'rsd_link'); remove_action( 'wp_head', 'wlwmanifest_link'); remove_action( 'wp_head', 'index_rel_link'); remove_action( 'wp_head', 'parent_post_rel_link'); remove_action( 'wp_head', 'start_post_rel_link'); remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head'); remove_action( 'wp_head', 'wp_generator' ); remove_action( 'wp_head', 'rel_canonical' ); remove_action( 'wp_head', 'wp_enqueue_scripts' ); remove_action( 'wp_head', 'locale_stylesheet' ); remove_action( 'wp_head', 'noindex' ); remove_action( 'wp_head', 'wp_print_styles' ); remove_action( 'wp_head', 'wp_print_head_scripts' ); remove_action( 'wp_head', '_custom_background_cb' ); // ヘッダースタイル add_action( 'wp_head', 'header_style' ); //+++++++++++++++++++++++++++++++++++++++++ //カスタムヘッダー add_custom_image_header('','admin_header_style'); function admin_header_style() {} //標準のヘッダー画像を指定 define('HEADER_IMAGE','%s/images/front/bg_header.jpg'); register_default_headers( array( 'default' => array( 'url' => '%s/images/front/bg_header.jpg', 'thumbnail_url' => '%s/images/front/bg_header.jpg', 'description' => __( 'default', 'default_header' ) ) ) ); //ヘッダー画像の横幅と高さを指定 define('HEADER_IMAGE_WIDTH','520'); define('HEADER_IMAGE_HEIGHT','115'); //ヘッダーの文字を隠す define('NO_HEADER_TEXT',true); function get_custom_css($design_type){ list($conf_designs) = get_posts( array('post_type'=>'design', 'meta_query' => array( array( 'key'=>'design_type', 'value'=>"$design_type", ), ), 'order'=>'ASC' ) ); $style_sheet = ""; if( isset($conf_designs) ): list($get_style) = get_post_meta($conf_designs->ID, 'stylesheet'); $style_sheet = $get_style; endif; return $style_sheet; } function get_ogp_meta(){ $template_type = get_template_type(); $app_ogp = "ogp_" . PAGE_TYPE . "_" . $template_type; if(function_exists($app_ogp)) { return do_shortcode("[" . $app_ogp ."]"); } else { return ""; } } add_shortcode('ogp_meta', 'get_ogp_meta'); function get_template_type(){ global $posts; $app_type = "home"; if ( $posts[0]->{"post_type"} === 'page' ){ $app_type = $posts[0]->{"post_name"}; define( 'PAGE_TYPE', 'page' ); } else { $app_type = $posts[0]->{"post_type"}; $single_id = $posts[0]->{"ID"}; define( 'PAGE_TYPE', 'single' ); define( 'POST_ID', $single_id ); } return $app_type; } function header_style(){ $header_image = get_header_image(); $background_style = get_custom_background(); $custom_style = get_custom_css(get_template_type()); print <<<HEADER_STYLE <style> #header { background: url($header_image); } #wrapper { $background_style } body { overflow-x : hidden ;} $custom_style </style> <script> function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'ja', includedLanguages: 'en,ko,ja', layout: google.translate.TranslateElement.InlineLayout.SIMPLE }, 'google_translate_element'); } </script> <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> jQuery.event.add(window, "load", function(){ var footer_height = jQuery("#footer").position().top + 200; FB.Canvas.setSize({ height: footer_height }); }); </script> HEADER_STYLE; } if ( is_admin() ){ require_once( ABSPATH . 'wp-admin/custom-background.php' ); $GLOBALS['custom_background'] =& new Custom_Background( $admin_header_callback, $admin_image_div_callback ); add_action( 'admin_menu', array( &$GLOBALS['custom_background'], 'init' ) ); } /** * Default custom background callback. * * @since 3.0.0 * @see add_custom_background() * @access protected */ function get_custom_background() { $background = get_background_image(); $color = get_background_color(); if ( ! $background && ! $color ) return; $style = $color ? "background-color: #$color;" : ''; if ( $background ) { $image = " background-image: url('$background');"; $repeat = get_theme_mod( 'background_repeat', 'repeat' ); if ( ! in_array( $repeat, array( 'no-repeat', 'repeat-x', 'repeat-y', 'repeat' ) ) ) $repeat = 'repeat'; $repeat = " background-repeat: $repeat;"; $position = get_theme_mod( 'background_position_x', 'left' ); if ( ! in_array( $position, array( 'center', 'right', 'left' ) ) ) $position = 'left'; $position = " background-position: top $position;"; $attachment = get_theme_mod( 'background_attachment', 'scroll' ); if ( ! in_array( $attachment, array( 'fixed', 'scroll' ) ) ) $attachment = 'scroll'; $attachment = " background-attachment: $attachment;"; $style .= $image . $repeat . $position . $attachment; } return trim( $style ); } ?>
014miharu-hirayama
lib/func_header.php
PHP
oos
5,663
<?php // FacebookPageにリダイレクト function redirectFB() { if($_GET["app_data"] != "" && !ereg("facebook",$_SERVER['HTTP_USER_AGENT'])){ echo '<meta http-equiv="refresh" CONTENT="0;URL=' . FB_URL . "&app_data=" . $_GET["app_data"] . '" />'; exit; } } function loadIframeFB(){ if ( isset($_REQUEST["signed_request"]) ){ $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); } // Fan Gate if ( isset($data["page"]["liked"]) ){ if ( $data["page"]["liked"] === true ){ } else { echo '<html><head><style>body{overflow-x : hidden ;overflow-y : hidden ;}</style></head><body><img src="'. get_bloginfo('template_url'). '/images/front/fangate.jpg" alt="' . get_bloginfo('name') . '" title="' . get_bloginfo('name') . '" /></body></html>'; exit; } } // like page if ( isset($data["app_data"]) ){ echo '<meta http-equiv="refresh" CONTENT="0;URL=' . get_bloginfo("siteurl") . base64_decode($data["app_data"]) . '" />'; exit; } } // FacebookLikeボタンを取得 function getLikeBottun() { $permalink = get_permalink(); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $like_link = $permalink . '?app_data=' . base64_encode( $appdata ); $like_bottun = '<iframe src="https://www.facebook.com/plugins/like.php?app_id=' . APP_ID . '&href='; $like_bottun .= urlencode($like_link); $like_bottun .= '&amp;send=false&amp;layout=button_count&amp;width=150&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:20px" allowTransparency="true"></iframe>'; return '<!--' . $like_link . '-->' . $like_bottun; //return $like_bottun; } add_shortcode('facebook_like', 'getLikeBottun'); // OGPタグを取得 function getOGPMeta() { global $post, $id; setup_postdata($post); if (is_page_template('custom_photogallary.php')) { $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="Photo Gallary' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:url" content="' . get_permalink() . '?app_data=' . base64_encode(get_permalink()) . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . get_the_post_thumbnail($id) . '" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; }else if (is_single()) { $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="「' . get_the_title() . '」" />'; $OGP_meta .= '<meta property="og:url" content="' . get_permalink() . '?app_data=' . base64_encode(get_permalink()) . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . get_bloginfo('template_url') . '/images/front/img_head.jpg" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; }else if (is_attachment()) { $url_large = wp_get_attachment_image_src($id, $size='large'); $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="「' . get_the_title() . '」" />'; $OGP_meta .= '<meta property="og:url" content="' . get_bloginfo('home') . '/?attachment_id=' . $id . '&app_data=' . base64_encode(get_bloginfo('home')) . '/?attachment_id=' . $id . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . $url_large[0] . '" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; }else{ $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="「' . get_the_title() . '」" />'; $OGP_meta .= '<meta property="og:url" content="' . get_permalink() . '?app_data=' . base64_encode(get_permalink()) . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . get_bloginfo('template_url') . '/images/front/img_head.jpg" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; } return $OGP_meta; } ?>
014miharu-hirayama
lib/mastercontrol.php
PHP
oos
4,997
<?php function header_googleplus(){ print <<<GOOGLE_PLUS <script type="text/javascript"> window.___gcfg = {lang: 'ja'}; (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> GOOGLE_PLUS; } add_action( 'wp_head', 'header_googleplus' ); function header_facebook(){ $appId = APP_ID; print <<<HEADER_FACEBOOK <script type="text/javascript" src="https://connect.facebook.net/ja_JP/all.js"></script> <div id="fb-root"></div> <script type="text/javascript"> FB.init({ appId : '$appId', status : true, // check login status cookie : true, // enable cookies xfbml : true, // parse XFBML logging : true }); </script> HEADER_FACEBOOK; } add_action( 'wp_head', 'header_facebook' ); /* * いいね用 デフォルト */ function get_base_like(){ global $custom_post; if ( isset($custom_post) ){ $ID = $custom_post->ID; $like_title = $custom_post->post_title; } else { $ID = get_the_ID(); $like_title = get_the_title(); } $single_page = '/single/' . get_template_type() . '/' . $ID . '/'; $permalink = get_bloginfo('siteurl') . $single_page; $like_link = $permalink . '?app_data=' . base64_encode( $single_page ); $like_bottun = '<iframe src="https://www.facebook.com/plugins/like.php?app_id=' . APP_ID . '&href='; $like_bottun .= urlencode($like_link); $like_bottun .= '&amp;send=false&amp;layout=button_count&amp;width=68&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:68px; height:20px" allowTransparency="true"></iframe>'; $google_plus = '<div class="g-plusone" data-size="medium" data-annotation="none"></div>'; //$google_plus = ''; $twitter = <<<TWITTER_BUTTON <a href="https://twitter.com/share" class="twitter-share-button" data-url="$like_link" data-text="$like_title" data-lang="ja" data-count="none">ツイート</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> TWITTER_BUTTON; //$twitter = ''; return "\n" . $google_plus . "\n" . $twitter . "\n" . $like_bottun . "\n" . '<!-- facebook_like: ' . $like_link . ' // -->'; } add_shortcode('base_like', 'get_base_like'); add_shortcode('facebook_like', 'get_base_like'); /* * OpenGraphProtocol デフォルト * * Usage: * */ function ogp_single_base_content(){ $ogp_meta = ""; global $wp_query; $og_site = get_bloginfo('name'); $permalink = get_permalink(); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $text_excerpt = strip_tags(htmlspecialchars_decode(get_the_excerpt())); $text_content = $wp_query->{"queried_object"}->{"post_content"}; $default_img = get_bloginfo("template_url") . "/screenshot.png"; $all_images = (preg_match_all('~img.+?src="([^"]+?)"~', $text_content, $matches)) ? array_unique($matches[1]) : array($default_img); $og_title = get_the_title(); $og_content = $text_excerpt; $refresh = FB_URL . "&app_data=" . urlencode(base64_encode( get_permalink() )); $maxwidth = 0; foreach ( $all_images as $image ) : $buf_image = @getimagesize($image); if ( $buf_image[0] > $maxwidth ){ $maxwidth = $buf_image[0]; $og_image = $image; } endforeach; if ( empty($og_image) ) { $og_image = $default_img; } if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && ('https' === $_SERVER['HTTP_X_FORWARDED_PROTO']) ){ $og_url = str_replace( "http:", "https:", $og_url ); } $ogp_meta = <<<META_OGP <meta property="og:title" content="$og_title" /> <meta property="og:type" content="article" /> <meta property="og:url" content="$og_url" /> <meta property="og:image" content="$og_image" /> <meta property="og:site_name" content="$og_site" /> <meta property="fb:app_id" content="$og_appId" /> <meta property="og:description" content="$og_content"> <meta property="og:locale" content="ja_JP" /> <meta itemprop="name" content="$og_title"> <meta itemprop="description" content="$og_content"> <meta itemprop="image" content="$og_image"> META_OGP; return $ogp_meta; } add_shortcode('ogp_single_content', 'ogp_single_base_content'); /* * WallPost用 * * @prams og_image 画像 (無くてもよい) * @prams og_url いいね用 URL * @prams title タイトル * @prams message メッセージ * */ function wall_post( $og_image, $og_url, $og_title, $message ){ $fanpage = PAGE_ID; $page_token = ACCESS_TOKEN; if ( $page_token !== "" ): $ch = curl_init(); $params = 'access_token=' . urlencode($page_token); if ( !empty($og_image) ) $params .= '&picture=' . urlencode($og_image); $params .= '&link=' . urlencode($og_url); $params .= '&name=' . urlencode($og_title); $params .= '&message=' . $message; curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$fanpage.'/feed'); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $resp = curl_exec($ch); curl_close($ch); endif; } $wppostfix = new WpPostFix(); // 記事が保存されたときに起動する add_action('save_post', array($wppostfix, 'postfix'), 99); //add_action('edit_post', array($wppostfix, 'postfix'), 99); //add_action('publish_post', array($wppostfix, 'postfix'), 99); class WpPostFix { function postfix($postID) { // ウォール投稿多重チェック $wall_posted = get_option( 'wall_posted' ); if ( empty($wall_posted) ){ // 未投稿 add_option( 'wall_posted', $postID, '', 'yes' ); } else { if ( $wall_posted < $postID ){ // 投稿許可 } else { // 投稿済みの為 ここで終了 return $postID; } } global $wpdb; list($result) = $wpdb->get_results("SELECT post_status,post_title,post_type,post_content FROM {$wpdb->posts} WHERE ID = '{$postID}' LIMIT 1"); $post_status = $result->post_status; $content = $result->post_content; $post_type = $result->post_type; $og_title = $result->post_title; $message = br2nl( strip_tags(htmlspecialchars_decode( $content ), '<br>') ); // 誤動作防止 if ( get_bloginfo("siteurl") !== ENABLE_SITE ) { return $postID; } $single_page_url = '/single/' . $post_type . '/' . $postID; $og_url = get_bloginfo("siteurl") . $single_page_url . '?app_data=' . urlencode(base64_encode($single_page_url)); //$og_url = htmlspecialchars_decode(get_post_meta($postID ,'syndication_permalink',true)); // 画像 content 内 // デフォルト画像が必要な時 $default_img = get_bloginfo("template_url") . "/screenshot.png"; // $default_img = null; $all_images = (preg_match_all('~img.+?src="([^"]+?)"~', $content, $matches)) ? array_unique($matches[1]) : array($default_img); $maxwidth = 0; foreach ( $all_images as $image ) : $buf_image = @getimagesize($image); if ( $buf_image[0] > $maxwidth ){ $maxwidth = $buf_image[0]; $og_image = $image; } endforeach; if ( empty($og_image) ) { $og_image = $default_img; } // 画像 ここまで // ウォール投稿を許可するカスタムポストタイプ $enable_type = array( 'blog' ); if ( in_array( $post_type , $enable_type ) ): /* * 動作チェック用 * // コンテンツ書き換え */ // $content = $this->blogcontent($post_status, $content); // * // DB をなおした内容でアップデートする // $wpdb->query("UPDATE {$wpdb->posts} SET post_content = '{$content}' WHERE ID = '{$postID}'"); // */ // 公開の投稿をウォールへポスト if ( $post_status === 'publish' ){ // ウォールへポスト wall_post( $og_image, $og_url, $og_title, $message ); update_option( 'wall_posted', $postID ); } endif; // 次の人のために post_id 戻しておく return $postID; } function blogcontent($post_type, $content) { // 書き換えたい内容を記載 $before = 'hogehoge'; $after = 'mogemoge'; $after = $post_type; $content = preg_replace("/$before/i", $after, $content); // 戻す return $content; } } function br2nl($string){ //改行コードのリスト $aBreakTags = array( '/&lt;br&gt;/', '/&lt;br \/&gt;/', '/&lt;BR&gt;/', '/<br>/', '/<BR>/', '/<br \/>/', '/<BR \/>/' ); return preg_replace($aBreakTags ,"\n" , $string ); } function facebook_likeCount($str = null) { if($str) $url = $str; else $url = ((!empty($_SERVER['HTTPS']))? "https://" : "http://").$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $json = file_get_contents('http://graph.facebook.com/' . $url ,true); $data = json_decode($json, true); return ($data['shares'])? $data['shares'] : 0; } ?>
014miharu-hirayama
lib/social.php
PHP
oos
9,425
<?php //+++++++++++++++++++++++++++++++++++++++++ //カスタムメニュー register_nav_menus(array( 'navbar' => 'ナビゲーションバー', 'sidebar' => 'サイドバー' )); function facebook_js(){ print <<<FACEBOOK_HEADER <script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script> <script type="text/javascript"> FB.Canvas.setSize({ width: 520, height: 800 }); </script> FACEBOOK_HEADER; } //add_action( 'wp_head', 'facebook_js' ); function header_gnav_script(){ $template_url = get_custom_templateurl(); $local_time = time(); define( CUSTOM_TYPE , get_template_type() ); print <<<HEADER_GNAV <link rel="stylesheet" href="$template_url/css/gnavi.css?$local_time" type="text/css" /> HEADER_GNAV; } add_action( 'wp_head', 'header_gnav_script' ); function get_navi(){ $nav_opt = array( 'menu' => 'gnav', // menu '' カスタムメニューのIDを指定 'container' => 'div', // container 'div' ナビゲーションメニューを囲むタグ名を指定 'container_class' => 'floatClear', // container_class '' ナビゲーションメニューを囲むタグのクラス名を指定 'container_id' => 'gnav', // container_id '' ナビゲーションメニューを囲むタグのIDを指定 'menu_class' => 'navi', // menu_class 'menu' ナビゲーションメニューを囲むタグのクラス名を指定 'echo' => false, // echo true ナビゲーションメニューを表示する場合はtrue、文字列として取得する場合はfalseを指定 'depth' => 0, // depth 0 階層数を指定(0はすべてを表示、1ならばメニューバーのみ)。 'walker' => new MasterControl_Global_Navi(), // walker '' コールバック関数名を指定 'theme_location' => 'navbar', // theme_location '' テーマ内のロケーションIDを指定。 ); return wp_nav_menu($nav_opt); } function print_navi(){ $nav_opt = array( 'menu' => 'gnav', // menu '' カスタムメニューのIDを指定 'container' => 'div', // container 'div' ナビゲーションメニューを囲むタグ名を指定 'container_class' => 'floatClear', // container_class '' ナビゲーションメニューを囲むタグのクラス名を指定 'container_id' => 'gnav', // container_id '' ナビゲーションメニューを囲むタグのIDを指定 'menu_class' => 'navi', // menu_class 'menu' ナビゲーションメニューを囲むタグのクラス名を指定 'echo' => false, // echo true ナビゲーションメニューを表示する場合はtrue、文字列として取得する場合はfalseを指定 'depth' => 0, // depth 0 階層数を指定(0はすべてを表示、1ならばメニューバーのみ)。 'walker' => new MasterControl_Global_Navi(), // walker '' コールバック関数名を指定 'theme_location' => 'navbar', // theme_location '' テーマ内のロケーションIDを指定。 ); print wp_nav_menu($nav_opt); } add_shortcode('gnavi', 'get_navi'); /** * Navigation Menu template functions * * @package WordPress * @subpackage Nav_Menus * @since 3.0.0 */ /** * Create HTML list of nav menu items. * * @package WordPress * @since 3.0.0 * @uses Walker */ class MasterControl_Global_Navi extends Walker_Nav_Menu { /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param int $current_page Menu item ID. * @param object $args */ function start_el(&$output, $item, $depth, $args) { global $gnavi_Class; global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $LF = "\n"; $class_names = $value = ''; $gnavi_Class = 'menu_' . $item->title; $class_names = ' class="' . esc_attr( 'menu_' . $item->title ) . '" '; $id = ' id="' . esc_attr( 'gnav_' . $item->title ) . '"'; $output .= $indent . '<li' . $id . $value . $class_names .'>' . $LF; $attributes = ' title="' . esc_attr( $item->title ) . '"'; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= strtolower(CUSTOM_TYPE) === strtolower($item->title) ? ' class="current"' : ''; if ( preg_match("/favorites/", $item->url)) { $url = parse_url($item->url); $stockstyle = $url['host'] === "dev.mastercontrol.jp" ? "stage.stockstyle.net" : "stockstyle.net"; $attributes .= 'href="//' . $stockstyle . '/products/facebook.php?osusume_url=' . $url['path'] . '"'; } else { $lang_url = ( isset($_GET["lang"]) ) ? '?lang=' . $_GET["lang"] : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) . $lang_url . '"' : ''; } $item_output = $args->before; $item_output .= '<a'. str_replace( "http:", "", $attributes ) .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ?>
014miharu-hirayama
lib/func_gnavi.php
PHP
oos
5,774
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Info 情報 register_post_type( 'Info', array( 'label' => 'Infomation', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/event.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); function get_info_meta(){ $c = get_post_custom_values('infostart', get_the_ID()); $info["startdate"] = $c[0]; $c = get_post_custom_values('infoend' , get_the_ID()); $info["enddate"] = $c[0]; $c = get_post_custom_values('opendate' , get_the_ID()); $info["opendate"] = $c[0]; $c = get_post_custom_values('closedate' , get_the_ID()); $info["closedate"] = $c[0]; $c = get_post_custom_values('category' , get_the_ID()); $info["category"] = $c[0]; if($info["enddate"] == "" || $info["enddate"] === $info["startdate"]){$info["datelabel"] = $info["startdate"];} if($info["enddate"] != "" && $info["enddate"] != $info["startdate"]){$info["datelabel"] = $info["startdate"] . " - " . $info["enddate"];} return $info; } /* function is_info_disable($info){ $filtered = false; // ##opendate <- -> closedate 以外であれば非表示 if( $info["opendate"] != ""){ if(strtotime( $info["opendate"] ) > time() ){ $filtered = true; }} if( $info["closedate"] != ""){ if(strtotime( $info["closedate"] ) < time() ){ $filtered = true; }} //##月指定があれば絞り込み if(isset($_REQUEST["mon"])){ $filter = date("Y", $_REQUEST["mon"]) . date("m", $_REQUEST["mon"]); $current = date("Y", strtotime($info["startdate"])) . date("m", strtotime($info["startdate"])); if($filter != $current){$filtered = true;} } //##カテゴリ指定があれば絞り込み if(isset($_REQUEST["cat"])){ if($_REQUEST["cat"] != $info["category"]){$filtered = true;} } return $filtered; } */ function get_selectbox_category(){ wp_reset_query(); query_posts('post_type=info'); $catList = array(); if(have_posts()){ while(have_posts()){ the_post(); $e = get_info_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $cat = get_post_custom_values('category', get_the_ID()); $catList[$e["category"]] = ""; } } $catListKeys = array_keys($catList); $selectbox_html = "<select name='cat' id='cat' class='postform' >"; $selectbox_html .= "<option value=''>カテゴリーを選択</option>"; foreach($catListKeys as $k=>$v){ if($_REQUEST["cat"] === $v){$selected = "selected";}else{$selected = "";} $selectbox_html .= '<option class="level-0" value="' . $v . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var catdropdown = document.getElementById('cat');"; $selectbox_html .= " function onCatChange() {"; $selectbox_html .= " location.href = './?cat='+catdropdown.options[catdropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "catdropdown.onchange = onCatChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } add_shortcode('select_category', 'get_selectbox_category'); function get_selectbox_monthly(){ wp_reset_query(); query_posts('post_type=info'); $monthList = array(); if(have_posts()){ while(have_posts()){ the_post(); $e = get_info_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $monthList[date("Y", strtotime($e["startdate"])) . "/" . date("n", strtotime($e["startdate"]))] = ""; } } $monthListKeys = array_keys($monthList); $selectbox_html = "<select name='mon' id='mon' class='postform' >"; $selectbox_html .= "<option value=''>月を選択</option>"; foreach($monthListKeys as $k=>$v){ if(intval( $_REQUEST["mon"] ) === strtotime($v."/1")){ $selected = "selected"; }else{ $selected = ""; } $selectbox_html .= '<option class="level-0" value="' . strtotime($v."/1") . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var mondropdown = document.getElementById('mon');"; $selectbox_html .= "function onMonChange() {"; $selectbox_html .= " location.href = './?mon='+mondropdown.options[mondropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "mondropdown.onchange = onMonChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } add_shortcode('select_monthly', 'get_selectbox_monthly'); function get_info_the_title(){ return get_custom_the_title(); } add_shortcode('info_title', 'get_info_the_title'); function get_info_the_content(){ return get_custom_the_content(); } add_shortcode('info_content', 'get_info_the_content'); function get_info_category(){ return get_custom_category(); } add_shortcode('info_category', 'get_info_category'); function get_page_info(){ if ( PAGE_TYPE === 'page' ) { global $custom_post; global $custom_query_posts; $item_content = ""; $items = get_posts($custom_query_posts); if( isset($items) ): for( $i = 0; $i < count( $items ) && $custom_post = $items[$i]; $i++ ) : $item_content .= apply_filters('the_content', constant('INFO_HTML_PAGE')); endfor; endif; return $item_content; } return; } add_shortcode('info_page' , 'get_page_info'); function get_single_info(){ $item_content = ""; if ( PAGE_TYPE === 'single' ) { global $custom_post; $custom_post = wp_get_single_post( POST_ID, 'OBJECT' ); $item_content = apply_filters('the_content', constant('INFO_HTML_PAGE')); } return $item_content; } add_shortcode('info_single' , 'get_single_info'); function exec_info(){ //echo $_GET["cat"] . "<BR>\n"; global $custom_query_posts; $custom_query_posts = ""; if ( isset($_GET["cat"]) ){ $category = $_GET["cat"]; $custom_query_posts = array( 'post_type'=>'info', 'meta_query' => array( array( 'key'=>'category', 'value'=>"$category", ), array( 'key' => 'opendate', 'value' => date("Y-m-d"), 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'closedate', 'value' => date("Y-m-d"), 'compare'=> '>=', 'type' => 'DATE' ), 'relation'=>'AND' ), 'posts_per_page'=>10, 'meta_key'=>'infostart', 'orderby'=>'meta_value', 'order'=>'ASC' ); } elseif ( isset($_GET["mon"]) ){ $select_mon = $_GET["mon"]; $startDay = date("Y-m-d", $select_mon); $lastDay = date("Y-m-d", mktime(0, 0, 0, date("m",$select_mon)+1, 0, date("Y",$select_mon))); $custom_query_posts = array( 'meta_query' => array( array( 'key' => 'infostart', 'value' => $startDay, 'compare'=> '>=', 'type' => 'DATE' ), array( 'key' => 'infostart', 'value' => $lastDay, 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'opendate', 'value' => date("Y-m-d"), 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'closedate', 'value' => date("Y-m-d"), 'compare'=> '>=', 'type' => 'DATE' ), 'relation'=>'AND' ), 'meta_key' => 'infostart', 'orderby' => 'meta_value', 'post_type' => 'info', 'posts_per_page' => 20, 'order' => 'DSC' ); } else { $custom_query_posts = array( 'meta_query' => array( array( 'key' => 'opendate', 'value' => date("Y-m-d"), 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'closedate', 'value' => date("Y-m-d"), 'compare'=> '>=', 'type' => 'DATE' ), 'relation'=>'AND' ), 'meta_key' => 'infostart', 'orderby' => 'meta_value', 'post_type' => 'info', 'posts_per_page' => 20, 'order' => 'DSC' ); } get_import_design("info"); return apply_filters('the_content', INFO_HTML_FRAME); } add_shortcode('run_info', 'exec_info'); ?>
014miharu-hirayama
lib/module/info/func.php
PHP
oos
8,779
<script> var menu_Tag = "Info"; </script> <link rel="stylesheet" href="/008akiakane/wp-content/themes/008akiakane/css/infomation.css" type="text/css" />
014miharu-hirayama
lib/module/info/header.php
Hack
oos
154
<?php /* //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト photogallery register_post_type( 'photogallery', array( 'label' => 'フォトギャラリー', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト DISCOGRAPHY register_post_type( 'discography', array( 'label' => 'ディスコグラフィー', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/discography.png', 'supports' => array( 'title', ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MEDIA register_post_type( 'media', array( 'label' => 'メディア/出演情報', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MULTI-BLOG register_post_type( 'multiblog', array( 'label' => 'マルチブログ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/blog.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); */ ?>
014miharu-hirayama
lib/module/other/func.php
PHP
oos
1,842
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Profile register_post_type( 'profile', array( 'label' => 'Profile', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/profile.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function get_prof_detail(){ return get_custom_textarea(PROF_ID, 'prof_detail'); } add_shortcode('prof_detail', 'get_prof_detail'); function get_prof_comment(){ return get_custom_textarea(PROF_ID, 'prof_comment'); } add_shortcode('prof_comment', 'get_prof_comment'); function get_prof_image(){ return get_custom_image(PROF_ID, ('prof_image')); } add_shortcode('prof_image', 'get_prof_image'); function exec_profile(){ get_import_design("profile"); list($conf_profile) = get_posts('post_type=profile&order=DSC'); if ( isset( $conf_profile ) ): define('PROF_ID' , $conf_profile->ID); endif; return apply_filters('the_content', PROFILE_HTML_FRAME); } add_shortcode('run_profile', 'exec_profile'); ?>
014miharu-hirayama
lib/module/profile/func.php
PHP
oos
1,135
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト ITUNES register_post_type( 'itunes', array( 'label' => 'iTunes', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/itune.png', 'supports' => array( 'title', 'editor' ) ) ); function exec_itunes(){ print <<<START_ITUNES <div id="main" class="clearfix"> <h2 class="itunes">itunes</h2> START_ITUNES; $itunes_url = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=%E7%A7%8B%E8%B5%A4%E9%9F%B3&country=JP&limit=10&entity=album&offset=0"; $itunes_res = json_decode(file_get_contents($itunes_url)); foreach ( $itunes_res->{"results"} as $album ) : $collectionId = $album->{"collectionId"}; echo <<<VIEW_ITUNE_IFRAME <iframe src="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewAlbumSocialPreview?id=$collectionId&s=143462&uo=4&wdId=32800" frameborder="0" scrolling="no" width="500px" height="280px"></iframe> VIEW_ITUNE_IFRAME; endforeach; print <<<END_ITUNES </div> END_ITUNES; } add_shortcode('run_itunes', 'exec_itunes'); ?>
014miharu-hirayama
lib/module/itunes/func.php
PHP
oos
1,227
<script> var menu_Tag = "iTunes"; </script> <link rel="stylesheet" href="/008akiakane/wp-content/themes/008akiakane/css/itunes.css" type="text/css" />
014miharu-hirayama
lib/module/itunes/header.php
Hack
oos
153
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト BLOG register_post_type( 'blog', array( 'label' => 'ブログ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/blog.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); function get_blog_the_title(){ return get_custom_the_title(); } add_shortcode('blog_title', 'get_blog_the_title'); function get_blog_the_content(){ $content = str_replace('img src="', 'img src="/img.php?imgurl=', get_custom_the_content()); $content = str_replace('a href="', 'a target="_blank" href="', $content); $content = strip_tags( $content , '<img><br>'); return $content; } add_shortcode('blog_content', 'get_blog_the_content'); function get_blog_date(){ return date('Y年m月d日', SimplePie_Parse_Date::get()->parse(get_custom_date())); } add_shortcode('blog_date', 'get_blog_date'); function get_blog_url(){ global $custom_post; return get_post_meta($custom_post->ID ,'syndication_permalink',true); } add_shortcode('blog_url', 'get_blog_url'); function get_pagenavi(){ $navi_html = ""; $navi_html = '<div class="tablenav">'; $paged = get_query_var('paged'); $paginate_base = get_pagenum_link(1); global $wp_rewrite; global $max_pages; if (strpos($paginate_base, '?') || ! $wp_rewrite->using_permalinks()) { $paginate_format = ''; $paginate_base = add_query_arg('paged', '%#%'); } else { $paginate_format = (substr($paginate_base, -1 ,1) == '/' ? '' : '/') . user_trailingslashit('page/%#%/', 'paged');; $paginate_base .= '%_%'; } $navi_html .= paginate_links( array( 'base' => $paginate_base, 'format' => $paginate_format, 'total' => $max_pages, 'mid_size' => 3, 'current' => ($paged ? $paged : 1), 'prev_text' => '&laquo;', 'next_text' => '&raquo;', )); $navi_html .= '</div>'; return str_replace('http:', '', $navi_html); } add_shortcode('pagenavi', 'get_pagenavi'); function get_page_blog(){ if ( PAGE_TYPE === 'page' ) { global $custom_post; global $custom_query_posts; $item_content = ""; wp_reset_query(); query_posts($custom_query_posts); global $wp_query; global $max_pages; $max_pages = $wp_query->{"max_num_pages"}; $item_content .= do_shortcode('[pagenavi]'); if( isset($wp_query) ): $items = $wp_query->{"posts"}; for( $i = 0; $i < count( $items ) && $custom_post = $items[$i]; $i++ ) : $item_content .= do_shortcode( constant('BLOG_HTML_PAGE') ); endfor; endif; return $item_content; } return; } add_shortcode('blog_page' , 'get_page_blog'); function get_single_blog(){ $item_content = ""; if ( PAGE_TYPE === 'single' ) { global $custom_post; $custom_post = wp_get_single_post( POST_ID, 'OBJECT' ); if(have_posts()): while(have_posts()): the_post(); $item_content = do_shortcode( constant('BLOG_HTML_SINGLE') ); endwhile; endif; } return $item_content; } add_shortcode('blog_single' , 'get_single_blog'); function exec_blog(){ global $custom_query_posts; $blog_content = ""; $paged = get_query_var('paged'); $custom_query_posts = "post_type=blog&posts_per_page=2&paged=$paged&order=DSC"; get_import_design("blog"); //return apply_filters('the_content', BLOG_HTML_FRAME); return do_shortcode( constant('BLOG_HTML_FRAME') ); } add_shortcode('run_blog', 'exec_blog');
014miharu-hirayama
lib/module/blog/func.php
PHP
oos
3,656
<?php register_post_type( 'gallery', array( 'label' => 'Gallery', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail' ) ) ); function exec_gallery(){ $gallery_content = ""; wp_reset_query();query_posts('post_type=gallery&order=ASC'); if(have_posts()): while(have_posts()): the_post(); echo the_title() . "<br>\n"; echo the_content(); echo the_permalink() . "<br>\n"; endwhile; endif; //get_import_design("gallery"); //return apply_filters('the_content', GALLERY_HTML_FRAME); } add_shortcode('run_gallery', 'exec_gallery'); //+++++++++++++++++++++++++++++++++++++++++ // ギャラリー用facebookいいねボタン追加 /* デフォルトのショートコードを削除 */ remove_shortcode('gallery', 'gallery_shortcode'); /* 新しい関数を定義 */ add_shortcode('gallery', 'my_gallery_shortcode'); function my_gallery_shortcode($attr) { global $post, $wp_locale; static $instpe = 0; $instpe++; // Allow plugins/themes to override the default gallery template. $output = apply_filters('post_gallery', '', $attr); if ( $output != '' ) return $output; // We're trusting author input, so let's at least make sure it looks like a valid orderby statement if ( isset( $attr['orderby'] ) ) { $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] ); if ( !$attr['orderby'] ) unset( $attr['orderby'] ); } extract(shortcode_atts(array( 'order' => 'ASC', 'orderby' => 'menu_order ID', 'id' => $post->ID, 'itemtag' => 'dl', 'icontag' => 'dt', 'captiontag' => 'dd', 'columns' => 3, 'size' => 'thumbnail', 'include' => '', 'exclude' => '' ), $attr)); $id = intval($id); if ( 'RAND' == $order ) $orderby = 'none'; if ( !empty($include) ) { $include = preg_replace( '/[^0-9,]+/', '', $include ); $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); $attachments = array(); foreach ( $_attachments as $key => $val ) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( !empty($exclude) ) { $exclude = preg_replace( '/[^0-9,]+/', '', $exclude ); $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } else { $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } if ( empty($attachments) ) return ''; if ( is_feed() ) { $output = "¥n"; foreach ( $attachments as $att_id => $attachment ) $output .= wp_get_attachment_link($att_id, $size, true) . "¥n"; return $output; } $itemtag = tag_escape($itemtag); $captiontag = tag_escape($captiontag); $columns = intval($columns); $itemwidth = $columns > 0 ? floor(100/$columns) : 100; $float = is_rtl() ? 'right' : 'left'; $selector = "gallery-{$instpe}"; $output = apply_filters('gallery_style', " <style type='text/css'> #{$selector} { margin: auto; } #{$selector} .gallery-item { float: {$float}; margin-top: 10px; text-align: center; width: {$itemwidth}%; } #{$selector} img { border: 2px solid #cfcfcf; } #{$selector} .gallery-caption { margin-left: 0; } </style> <!-- see gallery_shortcode() in wp-includes/media.php --> <div id='$selector' class='gallery galleryid-{$id}'>"); $i = 0; foreach ( $attachments as $id => $attachment ) { echo "<!--" . var_dump($attachment) . "-->\n"; $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false); echo "\n<!-- link: " . $link . " /link -->"; $output .= "<{$itemtag} class='gallery-item'>"; $output .= " <{$icontag} class='gallery-icon'> $link </{$icontag}>"; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= " <{$captiontag} class='gallery-caption'> " . wptexturize($attachment->post_excerpt) . " </{$captiontag}>"; } $url_thumbnail = wp_get_attachment_image_src($id, $size='thumbnail'); $url = urlencode(get_bloginfo('home') . '/?attachment_id=' . $id); $url .= urlencode('&app_data=' . get_bloginfo('home') . '/?attachment_id=' . $id); $output .= '<p><div class="btn_like"><iframe src="http://www.facebook.com/plugins/like.php?href='; $output .= $url; $output .= '&amp;id=fb&amp;send=false&amp;layout=button_count&amp;show_faces=false&amp;width=120&amp;action=like&amp;colorscheme=light$amp;locale=ja_JA&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:120px; height:21px;" allowTransparency="true"></iframe></div></p>'; $output .= "</{$itemtag}>"; if ( $columns > 0 && ++$i % $columns == 0 ) $output .= '<br style="clear: both" />'; } $output .= "</div>"; return $output; } function remove_gallery_css() { return "<div id='gallery_box'>"; } add_filter('gallery_style', 'remove_gallery_css'); function fix_gallery_output( $output ){ /* $output = preg_replace("%<br style=.*clear: both.* />%", "", $output); $output = preg_replace("%<dl class='gallery-item'>%", "<div class='photobox'>", $output); $output = preg_replace("%<dt class='gallery-icon'>%", "", $output); $output = preg_replace("%</dl>%", "</div>", $output); $output = preg_replace("%</dt>%", "", $output); */ return $output; } add_filter('the_content', 'fix_gallery_output',11, 1); //+++++++++++++++++++++++++++++++++++++++++ ?>
014miharu-hirayama
lib/module/gallery/func.php
PHP
oos
6,174
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト PV (YouTube) register_post_type( 'pv', array( 'label' => 'PV', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/youtube.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function ogp_page_pv(){ $ogp_meta = ""; list($ogp_post) = get_posts("post_type=pv&order=DSC"); if(have_posts()): the_post(); //$ogp_meta = ogp_single_pv(); setup_postdata($ogp_post); $og_site = get_bloginfo('name'); $permalink = get_permalink(); $youtube_url = get_post_meta($ogp_post->ID, 'URL', true); $contents = file_get_contents("https://youtu.be/" . $youtube_url); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $htmls = split ( "\n" , $contents ); foreach ( $htmls as $linehtml ){ if ( preg_match('/"og:([^"]+)"/', $linehtml, $matchline) ){ if ( $matchline[1] === "url" ) { $ogp_meta .= '<meta property="og:url" content="'.$og_url.'" />' . "\n"; } elseif ( $matchline[1] === "site_name" ){ $ogp_meta .= '<meta property="og:site_name" content="'.$og_site.'" />' . "\n"; } else { $ogp_meta .= $linehtml . "\n"; } } } endif; $ogp_meta .= '<meta property="og:locale" content="ja_JP" />' . "\n"; return $ogp_meta; } add_shortcode('ogp_page_pv', 'ogp_page_pv'); function ogp_single_pv(){ $ogp_meta = ""; $og_site = get_bloginfo('name'); $permalink = get_permalink(); $youtube_url = get_post_meta(get_the_ID(), 'URL', true); $contents = file_get_contents("https://youtu.be/" . $youtube_url); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $htmls = split ( "\n" , $contents ); foreach ( $htmls as $linehtml ){ if ( preg_match('/"og:([^"]+)"/', $linehtml, $matchline) ){ if ( $matchline[1] === "url" ) { $ogp_meta .= '<meta property="og:url" content="'.$og_url.'" />' . "\n"; } elseif ( $matchline[1] === "site_name" ){ $ogp_meta .= '<meta property="og:site_name" content="'.$og_site.'" />' . "\n"; } else { $ogp_meta .= $linehtml . "\n"; } } } $ogp_meta .= '<meta property="og:locale" content="ja_JP" />'; return $ogp_meta; } add_shortcode('ogp_single_pv', 'ogp_single_pv'); function get_custom_title(){ return get_custom_text(get_the_ID(), 'タイトル'); } add_shortcode('pv_title', 'get_custom_title'); function get_custom_url(){ return get_custom_text(get_the_ID(), 'URL'); } add_shortcode('youtubeID', 'get_custom_url'); function get_custom_detail(){ return get_custom_text(get_the_ID(), '説明文'); } add_shortcode('pv_detail', 'get_custom_detail'); function get_page_pv(){ if ( PAGE_TYPE === 'page' ) { global $custom_query_posts; $item_content = ""; query_posts($custom_query_posts); if(have_posts()): while(have_posts()): the_post(); $item_content .= apply_filters('the_content', constant('PV_HTML_PAGE')); endwhile; endif; return $item_content; } return; } add_shortcode('pv_page' , 'get_page_pv'); function get_single_pv(){ $item_content = ""; if ( PAGE_TYPE === 'single' ) { global $custom_post; $custom_post = wp_get_single_post( POST_ID, 'OBJECT' ); if(have_posts()): while(have_posts()): the_post(); $item_content = apply_filters('the_content', constant('PV_HTML_SINGLE')); endwhile; endif; } return $item_content; } add_shortcode('pv_single' , 'get_single_pv'); function exec_pv(){ global $custom_query_posts; $custom_query_posts = "post_type=pv&order=DSC"; get_import_design("pv"); return apply_filters('the_content', PV_HTML_FRAME); } add_shortcode('run_pv', 'exec_pv'); ?>
014miharu-hirayama
lib/module/pv/func.php
PHP
oos
4,045
<?php register_post_type( 'goods_book', array( 'label' => 'Goods_BOOK', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/goods.png', 'supports' => array( 'title', 'custom-fields' ) ) ); register_post_type( 'goods_cd', array( 'label' => 'Goods_CD', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/goods.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function get_item_detail(){ global $goods_id; return get_custom_textarea($goods_id, 'item_detail'); } add_shortcode('item_detail', 'get_item_detail'); function get_item_title(){ global $goods_id; return get_custom_textarea($goods_id, 'item_title'); } add_shortcode('item_title', 'get_item_title'); function get_item_image(){ global $goods_id; return get_custom_image($goods_id, 'item_image'); } add_shortcode('item_image', 'get_item_image'); function get_page_book(){ if ( PAGE_TYPE === 'page' ) { global $goods_id; get_import_design("goods_book"); $item_content = ""; $items = get_posts("post_type=goods_book&order=DSC"); if( isset($items) ): for( $i = 0; $i < count( $items ) && $item = $items[$i]; $i++ ) : $goods_id = $item->ID; $item_content .= apply_filters('the_content', constant('GOODS_BOOK_HTML_PAGE')); endfor; endif; return $item_content; } return; } add_shortcode('book_page' , 'get_page_book'); function get_page_cd(){ if ( PAGE_TYPE === 'page' ) { global $goods_id; get_import_design("goods_cd"); $item_content = ""; $items = get_posts('post_type=goods_cd&order=DSC'); if( isset($items) ): for( $i = 0; $i < count( $items ) && $item = $items[$i]; $i++ ) : $goods_id = $item->ID; $item_content .= apply_filters('the_content', constant('GOODS_CD_HTML_PAGE')); endfor; endif; return $item_content; } return; } add_shortcode('cd_page' , 'get_page_cd'); function get_single_cd(){ if ( PAGE_TYPE === 'single' ) { global $goods_id; get_import_design("goods_cd"); $goods_id = POST_ID; $item_content .= apply_filters('the_content', constant('GOODS_CD_HTML_SINGLE')); return $item_content; } return; } add_shortcode('cd_single' , 'get_single_cd'); function get_single_book(){ if ( PAGE_TYPE === 'single' ) { global $goods_id; get_import_design("goods_book"); //$items = wp_get_single_post(POST_ID, 'ARRAY_A'); $goods_id = POST_ID; $item_content .= apply_filters('the_content', constant('GOODS_BOOK_HTML_SINGLE')); return $item_content; } return; } add_shortcode('book_single' , 'get_single_book'); function exec_goods_book(){ get_import_design('goods_book'); return apply_filters('the_content', constant('GOODS_BOOK_HTML_FRAME')); } add_shortcode('run_goods_book', 'exec_goods_book'); function exec_goods_cd(){ get_import_design('goods_cd'); return apply_filters('the_content', constant('GOODS_CD_HTML_FRAME')); } add_shortcode('run_goods_cd', 'exec_goods_cd'); function exec_goods(){ get_import_design("goods"); return apply_filters('the_content', GOODS_HTML_FRAME); } add_shortcode('run_goods', 'exec_goods'); ?>
014miharu-hirayama
lib/module/goods/func.php
PHP
oos
3,400
<script> var menu_Tag = "Goods"; </script> <link rel="stylesheet" href="/008akiakane/wp-content/themes/008akiakane/css/goods.css" type="text/css" />
014miharu-hirayama
lib/module/goods/header.php
Hack
oos
151
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Twitter register_post_type( 'twitter', array( 'label' => 'Twitter', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/twitter.png', 'supports' => array( 'title' ) ) ); function get_twitter_account(){ return get_custom_text(TWITTER_ID, ('Twitter')); } add_shortcode('twitter_account', 'get_twitter_account'); function exec_twitter(){ get_import_design("twitter"); list($conf_twitter) = get_posts('post_type=twitter&order=DSC'); if ( isset( $conf_twitter ) ): define('TWITTER_ID' , $conf_twitter->ID); endif; return apply_filters('the_content', TWITTER_HTML_FRAME); } add_shortcode('run_twitter', 'exec_twitter'); ?>
014miharu-hirayama
lib/module/twitter/func.php
PHP
oos
884
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト デザイン register_post_type( 'design', array( 'label' => 'デザイン', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/master_control_logo.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function get_css_design($design_type){ list($conf_designs) = get_posts( array('post_type'=>'design', 'meta_query' => array( array( 'key'=>'design_type', 'value'=>"$design_type", ), ), 'order'=>'ASC' ) ); $style_sheet = ""; if( isset($conf_designs) ): list($get_style) = get_post_meta($conf_designs->ID, 'stylesheet'); $style_sheet = $get_style; endif; return $style_sheet; } function get_import_design($design_type){ // Design Template OUTPUT  $design = array(); list($conf_designs) = get_posts(array('post_type'=>'design','meta_key'=>'design_type','meta_value'=>"$design_type",'order'=>'ASC')); if( isset($conf_designs) ): // $title = $conf_designs->post_title; list($conf_design_type) = get_post_meta($conf_designs->ID, 'design_type'); list($design["html_frame"]) = get_post_meta($conf_designs->ID, 'html_frame'); list($design["html_page"]) = get_post_meta($conf_designs->ID, 'html_page'); list($design["html_single"]) = get_post_meta($conf_designs->ID, 'html_single'); $frame_name = strtoupper($design_type) . '_HTML_FRAME'; define($frame_name, $design["html_frame"] ); $frame_name = strtoupper($design_type) . '_HTML_SINGLE'; define($frame_name, $design["html_single"] ); $frame_name = strtoupper($design_type) . '_HTML_PAGE'; define($frame_name, $design["html_page"] ); endif; return $design; } ?>
014miharu-hirayama
lib/design/func.php
PHP
oos
1,892
<?php get_header(); ?> <a name="top"></a> <div id="wrapper"> <div id="google_translate_element"></div> <!-- ヘッダーSTART --> <div id="header"> <h1><?php bloginfo('name'); ?></h1> </div> <!-- //ヘッダーEND// --> <!-- グローバルナビSTART --> <?php wp_nav_menu(array('theme_location' => 'navbar', 'container_id' => 'navigation', 'menu_id' => 'gnav')); ?> <!-- //グローバルナビEND// --> <!-- パン屑START --> <div id="bread"> <?php if(function_exists('bcn_display')){ bcn_display(); } ?> </div> <!-- //パン屑END// --> <!-- コンテンツタイトルSTART --> <div id="youtube_title"> <h2>YouTube</h2> </div> <!-- //コンテンツタイトルEND// --> <!-- YouTube START --> <?php query_posts('post_type=youtube'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <div id="youtube_box"> <h3><?php echo get_post_meta($post->ID, 'タイトル', true); ?></h3> <object width="480" height="274"><param name="movie" value="http://www.youtube.com/v/<?php echo get_post_meta($post->ID, 'URL', true); ?>"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/<?php echo get_post_meta($post->ID, 'URL', true); ?>" type="application/x-shockwave-flash" width="480" height="274" allowscriptaccess="always" allowfullscreen="true"></embed></object> <p class="video_txt"><?php echo get_post_meta($post->ID, '説明文', true); ?></p> <div class="btn_area"><div class="btn_like"><?php echo getLikeBottun(); ?></div></div> </div> <?php endwhile; ?> <?php endif; ?> <!-- //You Tube END// --> <!-- フッターSTART --> <div id="footer" class="floatClear"> <p><a href="#top">Page Top</a></p> </div> <!-- //フッターEND// --> </div> <?php get_footer(); ?>
014miharu-hirayama
single-youtube.php
PHP
oos
1,845
@charset "utf-8"; /* These are just the general site styles. It has nothing to do with ImageFlow ========================================== */ @media screen, projection, print { * { font-family:verdana, arial, helvetica, sans-serif; font-size:100.01%; } html { height:100%; width:100%; } body { color:#fff; background-color:#000; font-size:0.8em; line-height:1.4em; padding:1em 0; margin:0; } a { color:#fff; } h1 { font-size:2.2em; text-align:center; margin:0.4em 0 1.3em 0; } }
014miharu-hirayama
custom_itunes.php-ext/ImageFlow_1.3.0/style.css
CSS
oos
523
@charset "utf-8"; /* ImageFlow Settings ==================================== */ @media screen, projection { .imageflow { overflow:hidden; position:relative; text-align:left; visibility:hidden; width:100%; } .imageflow img { border:none; position:absolute; top:0px; visibility:hidden; -ms-interpolation-mode:bicubic; /* Enables bicubic image resampling for the IE7 */ } .imageflow p { margin:0 auto; text-align:center; } .imageflow .loading { border:1px solid white; height:15px; left:50%; margin-left:-106px; padding:5px; position:relative; visibility:visible; width:200px; } .imageflow .loading_bar { background:#fff; height:15px; visibility:visible; width:1%; } .imageflow .navigation{ z-index:10000; } .imageflow .caption { font-weight:bold; position:relative; text-align:center; z-index:10001; } .imageflow .scrollbar { border-bottom:1px solid #b3b3b3; position:relative; visibility:hidden; z-index:10002; height:1px; } .imageflow .slider { background:url(slider_dark.png) no-repeat; height:14px; margin:-6px 0 0 -7px; position:absolute; width:14px; z-index:10003; } .imageflow .slideshow { cursor:pointer; height:14px; margin:20px 0 0 20px; position:absolute; width:14px; z-index:10003; } .imageflow .slideshow.pause { background:url(button_pause.png) no-repeat; } .imageflow .slideshow.play { background:url(button_play.png) no-repeat; } .imageflow .images { overflow:hidden; white-space:nowrap; } .imageflow .button { cursor:pointer; height:17px; position:relative; width:17px; } .imageflow .previous { background: url(button_left.png) top left no-repeat; float:left; margin: -7px 0 0 -30px; } .imageflow .next { background: url(button_right.png) top left no-repeat; float:right; margin:-7px -30px 0 30px; } }
014miharu-hirayama
custom_itunes.php-ext/ImageFlow_1.3.0/imageflow.css
CSS
oos
1,873
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>ImageFlow</title> <meta name="robots" content="index, follow, noarchive" /> <link rel="stylesheet" href="style.css" type="text/css" /> <!-- This includes the ImageFlow CSS and JavaScript --> <link rel="stylesheet" href="imageflow.packed.css" type="text/css" /> <script type="text/javascript" src="imageflow.packed.js"></script> </head> <body> <h1>ImageFlow</h1> <!-- This is all the XHTML ImageFlow needs --> <div id="myImageFlow" class="imageflow"> <img src="img/img1.png" longdesc="img/img1.png" width="400" height="300" alt="Image 1" /> <img src="img/img2.png" longdesc="img/img2.png" width="300" height="400" alt="Image 2" /> <img src="img/img3.png" longdesc="img/img3.png" width="400" height="400" alt="Image 3" /> <img src="img/img1.png" longdesc="img/img1.png" width="400" height="300" alt="Image 4" /> <img src="img/img2.png" longdesc="img/img2.png" width="300" height="400" alt="Image 5" /> <img src="img/img1.png" longdesc="img/img1.png" width="400" height="300" alt="Image 6" /> <img src="img/img2.png" longdesc="img/img2.png" width="300" height="400" alt="Image 7" /> <img src="img/img3.png" longdesc="img/img3.png" width="400" height="400" alt="Image 8" /> <img src="img/img1.png" longdesc="img/img1.png" width="400" height="300" alt="Image 9" /> <img src="img/img1.png" longdesc="img/img1.png" width="400" height="300" alt="Image 10" /> <img src="img/img2.png" longdesc="img/img2.png" width="300" height="400" alt="Image 11" /> <img src="img/img3.png" longdesc="img/img3.png" width="400" height="400" alt="Image 12" /> <img src="img/img2.png" longdesc="img/img2.png" width="300" height="400" alt="Image 13" /> <img src="img/img3.png" longdesc="img/img3.png" width="400" height="400" alt="Image 14" /> <img src="img/img3.png" longdesc="img/img3.png" width="400" height="400" alt="Image 15" /> </div> </body> </html>
014miharu-hirayama
custom_itunes.php-ext/ImageFlow_1.3.0/index.html
HTML
oos
1,975
<?php $reflectPath = str_replace($_SERVER['DOCUMENT_ROOT'], "", dirname(__FILE__)); $js = file_get_contents("imageflow.js"); echo str_replace("%%reflectPath%%", $reflectPath, $js); ?>
014miharu-hirayama
custom_itunes.php-ext/ImageFlow_1.3.0/loadjs.php
PHP
oos
187
/* Name: ImageFlow Version: 1.3.0 (March 9 2010) Author: Finn Rudolph Support: http://finnrudolph.de/ImageFlow License: ImageFlow is licensed under a Creative Commons Attribution-Noncommercial 3.0 Unported License (http://creativecommons.org/licenses/by-nc/3.0/). You are free: + to Share - to copy, distribute and transmit the work + to Remix - to adapt the work Under the following conditions: + Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). + Noncommercial. You may not use this work for commercial purposes. + For any reuse or distribution, you must make clear to others the license terms of this work. + Any of the above conditions can be waived if you get permission from the copyright holder. + Nothing in this license impairs or restricts the author's moral rights. Credits: This script is based on Michael L. Perrys Cover flow in Javascript [1]. The reflections are generated server-sided by a slightly hacked version of Richard Daveys easyreflections [2] written in PHP. The mouse wheel support is an implementation of Adomas Paltanavicius JavaScript mouse wheel code [3]. It also uses the domReadyEvent from Tanny O'Haley [4]. [1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981 [2] http://reflection.corephp.co.uk/v2.php [3] http://adomas.org/javascript-mouse-wheel/ [4] http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-v */ /* ImageFlow constructor */ function ImageFlow () { /* Setting option defaults */ this.defaults = { animationSpeed: 50, /* Animation speed in ms */ aspectRatio: 1.0, /* Aspect ratio of the ImageFlow container (width divided by height) */ buttons: false, /* Toggle navigation buttons */ captions: true, /* Toggle captions */ circular: true, /* Toggle circular rotation */ imageCursor: 'default', /* Cursor type for all images - default is 'default' */ ImageFlowID: 'imageflow', /* Default id of the ImageFlow container */ imageFocusM: 1.0, /* Multiplicator for the focussed image size in percent */ imageFocusMax: 3, /* Max number of images on each side of the focussed one */ imagePath: '', /* Path to the images relative to the reflect_.php script */ imageScaling: true, /* Toggle image scaling */ imagesHeight: 0.3, /* Height of the images div container in percent */ imagesM: 1.3, /* Multiplicator for all images in percent */ onClick: function() { document.location = this.url; }, /* Onclick behaviour */ opacity: false, /* Toggle image opacity */ opacityArray: [10,8,6,4,2], /* Image opacity (range: 0 to 10) first value is for the focussed image */ percentLandscape: 100, /* Scale landscape format */ percentOther: 100, /* Scale portrait and square format */ preloadImages: true, /* Toggles loading bar (false: requires img attributes height and width) */ reflections: true, /* Toggle reflections */ reflectionGET: '', /* Pass variables via the GET method to the reflect_.php script */ reflectionP: 0.5, /* Height of the reflection in percent of the source image */ reflectionPNG: true, /* Toggle reflect2.php or reflect3.php */ reflectPath: '%%reflectPath%%/', /* Path to the reflect_.php script */ scrollbarP: 0.6, /* Width of the scrollbar in percent */ slider: true, /* Toggle slider */ sliderCursor: 'e-resize', /* Slider cursor type - default is 'default' */ sliderWidth: 14, /* Width of the slider in px */ slideshow: false, /* Toggle slideshow */ slideshowSpeed: 1500, /* Time between slides in ms */ slideshowAutoplay: false, /* Toggle automatic slideshow play on startup */ startID: 1, /* Image ID to begin with */ glideToStartID: true, /* Toggle glide animation to start ID */ startAnimation: false, /* Animate images moving in from the right on startup */ xStep: 150 /* Step width on the x-axis in px */ }; /* Closure for this */ var my = this; /* Initiate ImageFlow */ this.init = function (options) { /* Evaluate options */ for(var name in my.defaults) { this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : my.defaults[name]; } /* Try to get ImageFlow div element */ var ImageFlowDiv = document.getElementById(my.ImageFlowID); if(ImageFlowDiv) { /* Set it global within the ImageFlow scope */ ImageFlowDiv.style.visibility = 'visible'; this.ImageFlowDiv = ImageFlowDiv; /* Try to create XHTML structure */ if(this.createStructure()) { this.imagesDiv = document.getElementById(my.ImageFlowID+'_images'); this.captionDiv = document.getElementById(my.ImageFlowID+'_caption'); this.navigationDiv = document.getElementById(my.ImageFlowID+'_navigation'); this.scrollbarDiv = document.getElementById(my.ImageFlowID+'_scrollbar'); this.sliderDiv = document.getElementById(my.ImageFlowID+'_slider'); this.buttonNextDiv = document.getElementById(my.ImageFlowID+'_next'); this.buttonPreviousDiv = document.getElementById(my.ImageFlowID+'_previous'); this.buttonSlideshow = document.getElementById(my.ImageFlowID+'_slideshow'); this.indexArray = []; this.current = 0; this.imageID = 0; this.target = 0; this.memTarget = 0; this.firstRefresh = true; this.firstCheck = true; this.busy = false; /* Set height of the ImageFlow container and center the loading bar */ var width = this.ImageFlowDiv.offsetWidth; var height = Math.round(width / my.aspectRatio); document.getElementById(my.ImageFlowID+'_loading_txt').style.paddingTop = ((height * 0.5) -22) + 'px'; ImageFlowDiv.style.height = height + 'px'; /* Init loading progress */ this.loadingProgress(); } } }; /* Create HTML Structure */ this.createStructure = function() { /* Create images div container */ var imagesDiv = my.Helper.createDocumentElement('div','images'); /* Shift all images into the images div */ var node, version, src, imageNode; var max = my.ImageFlowDiv.childNodes.length; for(var index = 0; index < max; index++) { node = my.ImageFlowDiv.childNodes[index]; if (node && node.nodeType == 1 && node.nodeName == 'IMG') { /* Add 'reflect.php?img=' */ if(my.reflections === true) { version = (my.reflectionPNG) ? '3' : '2'; src = my.imagePath+node.getAttribute('src',2); src = my.reflectPath+'reflect'+version+'.php?img='+src+my.reflectionGET; node.setAttribute('src',src); } /* Clone image nodes and append them to the images div */ imageNode = node.cloneNode(true); imagesDiv.appendChild(imageNode); } } /* Clone some more images to make a circular animation possible */ if(my.circular) { /* Create temporary elements to hold the cloned images */ var first = my.Helper.createDocumentElement('div','images'); var last = my.Helper.createDocumentElement('div','images'); /* Make sure, that there are enough images to use circular mode */ max = imagesDiv.childNodes.length; if(max < my.imageFocusMax) { my.imageFocusMax = max; } /* Do not clone anything if there is only one image */ if(max > 1) { /* Clone the first and last images */ var i; for(i = 0; i < max; i++) { /* Number of clones on each side equals the imageFocusMax */ node = imagesDiv.childNodes[i]; if(i < my.imageFocusMax) { imageNode = node.cloneNode(true); first.appendChild(imageNode); } if(max-i < my.imageFocusMax+1) { imageNode = node.cloneNode(true); last.appendChild(imageNode); } } /* Sort the image nodes in the following order: last | originals | first */ for(i = 0; i < max; i++) { node = imagesDiv.childNodes[i]; imageNode = node.cloneNode(true); last.appendChild(imageNode); } for(i = 0; i < my.imageFocusMax; i++) { node = first.childNodes[i]; imageNode = node.cloneNode(true); last.appendChild(imageNode); } /* Overwrite the imagesDiv with the new order */ imagesDiv = last; } } /* Create slideshow button div and append it to the images div */ if(my.slideshow) { var slideshowButton = my.Helper.createDocumentElement('div','slideshow'); imagesDiv.appendChild(slideshowButton); } /* Create loading text container */ var loadingP = my.Helper.createDocumentElement('p','loading_txt'); var loadingText = document.createTextNode(' '); loadingP.appendChild(loadingText); /* Create loading div container */ var loadingDiv = my.Helper.createDocumentElement('div','loading'); /* Create loading bar div container inside the loading div */ var loadingBarDiv = my.Helper.createDocumentElement('div','loading_bar'); loadingDiv.appendChild(loadingBarDiv); /* Create captions div container */ var captionDiv = my.Helper.createDocumentElement('div','caption'); /* Create slider and button div container inside the scrollbar div */ var scrollbarDiv = my.Helper.createDocumentElement('div','scrollbar'); var sliderDiv = my.Helper.createDocumentElement('div','slider'); scrollbarDiv.appendChild(sliderDiv); if(my.buttons) { var buttonPreviousDiv = my.Helper.createDocumentElement('div','previous', 'button'); var buttonNextDiv = my.Helper.createDocumentElement('div','next', 'button'); scrollbarDiv.appendChild(buttonPreviousDiv); scrollbarDiv.appendChild(buttonNextDiv); } /* Create navigation div container beneath images div */ var navigationDiv = my.Helper.createDocumentElement('div','navigation'); navigationDiv.appendChild(captionDiv); navigationDiv.appendChild(scrollbarDiv); /* Update document structure and return true on success */ var success = false; if (my.ImageFlowDiv.appendChild(imagesDiv) && my.ImageFlowDiv.appendChild(loadingP) && my.ImageFlowDiv.appendChild(loadingDiv) && my.ImageFlowDiv.appendChild(navigationDiv)) { /* Remove image nodes outside the images div */ max = my.ImageFlowDiv.childNodes.length; for(index = 0; index < max; index++) { node = my.ImageFlowDiv.childNodes[index]; if (node && node.nodeType == 1 && node.nodeName == 'IMG') { my.ImageFlowDiv.removeChild(node); } } success = true; } return success; }; /* Manage loading progress and call the refresh function */ this.loadingProgress = function() { var p = my.loadingStatus(); if((p < 100 || my.firstCheck) && my.preloadImages) { /* Insert a short delay if the browser loads rapidly from its cache */ if(my.firstCheck && p == 100) { my.firstCheck = false; window.setTimeout(my.loadingProgress, 100); } else { window.setTimeout(my.loadingProgress, 40); } } else { /* Hide loading elements */ document.getElementById(my.ImageFlowID+'_loading_txt').style.display = 'none'; document.getElementById(my.ImageFlowID+'_loading').style.display = 'none'; /* Refresh ImageFlow on window resize - delay adding this event for the IE */ window.setTimeout(my.Helper.addResizeEvent, 1000); /* Call refresh once on startup to display images */ my.refresh(); /* Only initialize navigation elements if there is more than one image */ if(my.max > 1) { /* Initialize mouse, touch and key support */ my.MouseWheel.init(); my.MouseDrag.init(); my.Touch.init(); my.Key.init(); /* Toggle slideshow */ if(my.slideshow) { my.Slideshow.init(); } /* Toggle scrollbar visibility */ if(my.slider) { my.scrollbarDiv.style.visibility = 'visible'; } } } }; /* Return loaded images in percent, set loading bar width and loading text */ this.loadingStatus = function() { var max = my.imagesDiv.childNodes.length; var i = 0, completed = 0; var image = null; for(var index = 0; index < max; index++) { image = my.imagesDiv.childNodes[index]; if(image && image.nodeType == 1 && image.nodeName == 'IMG') { if(image.complete) { completed++; } i++; } } var finished = Math.round((completed/i)*100); var loadingBar = document.getElementById(my.ImageFlowID+'_loading_bar'); loadingBar.style.width = finished+'%'; /* Do not count the cloned images */ if(my.circular) { i = i - (my.imageFocusMax*2); completed = (finished < 1) ? 0 : Math.round((i/100)*finished); } var loadingP = document.getElementById(my.ImageFlowID+'_loading_txt'); var loadingTxt = document.createTextNode('loading images '+completed+'/'+i); loadingP.replaceChild(loadingTxt,loadingP.firstChild); return finished; }; /* Cache EVERYTHING that only changes on refresh or resize of the window */ this.refresh = function() { /* Cache global variables */ this.imagesDivWidth = my.imagesDiv.offsetWidth+my.imagesDiv.offsetLeft; this.maxHeight = Math.round(my.imagesDivWidth / my.aspectRatio); this.maxFocus = my.imageFocusMax * my.xStep; this.size = my.imagesDivWidth * 0.5; this.sliderWidth = my.sliderWidth * 0.5; this.scrollbarWidth = (my.imagesDivWidth - ( Math.round(my.sliderWidth) * 2)) * my.scrollbarP; this.imagesDivHeight = Math.round(my.maxHeight * my.imagesHeight); /* Change imageflow div properties */ my.ImageFlowDiv.style.height = my.maxHeight + 'px'; /* Change images div properties */ my.imagesDiv.style.height = my.imagesDivHeight + 'px'; /* Change images div properties */ my.navigationDiv.style.height = (my.maxHeight - my.imagesDivHeight) + 'px'; /* Change captions div properties */ my.captionDiv.style.width = my.imagesDivWidth + 'px'; my.captionDiv.style.paddingTop = Math.round(my.imagesDivWidth * 0.02) + 'px'; /* Change scrollbar div properties */ my.scrollbarDiv.style.width = my.scrollbarWidth + 'px'; my.scrollbarDiv.style.marginTop = Math.round(my.imagesDivWidth * 0.02) + 'px'; my.scrollbarDiv.style.marginLeft = Math.round(my.sliderWidth + ((my.imagesDivWidth - my.scrollbarWidth)/2)) + 'px'; /* Set slider attributes */ my.sliderDiv.style.cursor = my.sliderCursor; my.sliderDiv.onmousedown = function () { my.MouseDrag.start(this); return false;}; if(my.buttons) { my.buttonPreviousDiv.onclick = function () { my.MouseWheel.handle(1); }; my.buttonNextDiv.onclick = function () { my.MouseWheel.handle(-1); }; } /* Set the reflection multiplicator */ var multi = (my.reflections === true) ? my.reflectionP + 1 : 1; /* Set image attributes */ var max = my.imagesDiv.childNodes.length; var i = 0; var image = null; for (var index = 0; index < max; index++) { image = my.imagesDiv.childNodes[index]; if(image !== null && image.nodeType == 1 && image.nodeName == 'IMG') { this.indexArray[i] = index; /* Set image attributes to store values */ image.url = image.getAttribute('longdesc'); image.xPosition = (-i * my.xStep); image.i = i; /* Add width and height as attributes only once */ if(my.firstRefresh) { if(image.getAttribute('width') !== null && image.getAttribute('height') !== null) { image.w = image.getAttribute('width'); image.h = image.getAttribute('height') * multi; } else{ image.w = image.width; image.h = image.height; } } /* Check source image format. Get image height minus reflection height! */ if((image.w) > (image.h / (my.reflectionP + 1))) { /* Landscape format */ image.pc = my.percentLandscape; image.pcMem = my.percentLandscape; } else { /* Portrait and square format */ image.pc = my.percentOther; image.pcMem = my.percentOther; } /* Change image positioning */ if(my.imageScaling === false) { image.style.position = 'relative'; image.style.display = 'inline'; } /* Set image cursor type */ image.style.cursor = my.imageCursor; i++; } } this.max = my.indexArray.length; /* Override dynamic sizes based on the first image */ if(my.imageScaling === false) { image = my.imagesDiv.childNodes[my.indexArray[0]]; /* Set left padding for the first image */ this.totalImagesWidth = image.w * my.max; image.style.paddingLeft = (my.imagesDivWidth/2) + (image.w/2) + 'px'; /* Override images and navigation div height */ my.imagesDiv.style.height = image.h + 'px'; my.navigationDiv.style.height = (my.maxHeight - image.h) + 'px'; } /* Handle startID on the first refresh */ if(my.firstRefresh) { /* Reset variable */ my.firstRefresh = false; /* Set imageID to the startID */ my.imageID = my.startID-1; if (my.imageID < 0 ) { my.imageID = 0; } /* Map image id range in cicular mode (ignore the cloned images) */ if(my.circular) { my.imageID = my.imageID + my.imageFocusMax; } /* Make sure, that the id is smaller than the image count */ maxId = (my.circular) ? (my.max-(my.imageFocusMax))-1 : my.max-1; if (my.imageID > maxId) { my.imageID = maxId; } /* Toggle glide animation to start ID */ if(my.glideToStartID === false) { my.moveTo(-my.imageID * my.xStep); } /* Animate images moving in from the right */ if(my.startAnimation) { my.moveTo(5000); } } /* Only animate if there is more than one image */ if(my.max > 1) { my.glideTo(my.imageID); } /* Display images in current order */ my.moveTo(my.current); }; /* Main animation function */ this.moveTo = function(x) { this.current = x; this.zIndex = my.max; /* Main loop */ for (var index = 0; index < my.max; index++) { var image = my.imagesDiv.childNodes[my.indexArray[index]]; var currentImage = index * -my.xStep; /* Enabled image scaling */ if(my.imageScaling) { /* Don't display images that are not conf_focussed */ if ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget) { image.style.visibility = 'hidden'; image.style.display = 'none'; } else { var z = (Math.sqrt(10000 + x * x) + 100) * my.imagesM; var xs = x / z * my.size + my.size; /* Still hide images until they are processed, but set display style to block */ image.style.display = 'block'; /* Process new image height and width */ var newImageH = (image.h / image.w * image.pc) / z * my.size; var newImageW = 0; switch (newImageH > my.maxHeight) { case false: newImageW = image.pc / z * my.size; break; default: newImageH = my.maxHeight; newImageW = image.w * newImageH / image.h; break; } var newImageTop = (my.imagesDivHeight - newImageH) + ((newImageH / (my.reflectionP + 1)) * my.reflectionP); /* Set new image properties */ image.style.left = xs - (image.pc / 2) / z * my.size + 'px'; if(newImageW && newImageH) { image.style.height = newImageH + 'px'; image.style.width = newImageW + 'px'; image.style.top = newImageTop + 'px'; } image.style.visibility = 'visible'; /* Set image layer through zIndex */ switch ( x < 0 ) { case true: this.zIndex++; break; default: this.zIndex = my.zIndex - 1; break; } /* Change zIndex and onclick function of the focussed image */ switch ( image.i == my.imageID ) { case false: image.onclick = function() { my.glideTo(this.i);}; break; default: this.zIndex = my.zIndex + 1; if(image.url !== '') { image.onclick = my.onClick; } break; } image.style.zIndex = my.zIndex; } } /* Disabled image scaling */ else { if ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget) { image.style.visibility = 'hidden'; } else { image.style.visibility = 'visible'; /* Change onclick function of the focussed image */ switch ( image.i == my.imageID ) { case false: image.onclick = function() { my.glideTo(this.i);}; break; default: if(image.url !== '') { image.onclick = my.onClick; } break; } } my.imagesDiv.style.marginLeft = (x - my.totalImagesWidth) + 'px'; } x += my.xStep; } }; /* Initializes image gliding animation */ this.glideTo = function(imageID) { /* Check for jumppoints */ var jumpTarget, clonedImageID; if(my.circular) { /* Trigger left jumppoint */ if(imageID+1 === my.imageFocusMax) { /* Set jump target to the same cloned image on the right */ clonedImageID = my.max - my.imageFocusMax; jumpTarget = -clonedImageID * my.xStep; /* Set the imageID to the last image */ imageID = clonedImageID-1 ; } /* Trigger right jumppoint */ if(imageID === (my.max - my.imageFocusMax)) { /* Set jump target to the same cloned image on the left */ clonedImageID = my.imageFocusMax-1; jumpTarget = -clonedImageID * my.xStep; /* Set the imageID to the first image */ imageID = clonedImageID+1; } } /* Calculate new image position target */ var x = -imageID * my.xStep; this.target = x; this.memTarget = x; this.imageID = imageID; /* Display new caption */ var caption = my.imagesDiv.childNodes[imageID].getAttribute('alt'); if (caption === '' || my.captions === false) { caption = '&nbsp;'; } my.captionDiv.innerHTML = caption; /* Set scrollbar slider to new position */ if (my.MouseDrag.busy === false) { if(my.circular) { this.newSliderX = ((imageID-my.imageFocusMax) * my.scrollbarWidth) / (my.max-(my.imageFocusMax*2)-1) - my.MouseDrag.newX; } else { this.newSliderX = (imageID * my.scrollbarWidth) / (my.max-1) - my.MouseDrag.newX; } my.sliderDiv.style.marginLeft = (my.newSliderX - my.sliderWidth) + 'px'; } /* Only process if opacity or a multiplicator for the focussed image has been set */ if(my.opacity === true || my.imageFocusM !== my.defaults.imageFocusM) { /* Set opacity for centered image */ my.Helper.setOpacity(my.imagesDiv.childNodes[imageID], my.opacityArray[0]); my.imagesDiv.childNodes[imageID].pc = my.imagesDiv.childNodes[imageID].pc * my.imageFocusM; /* Set opacity for the other images that are displayed */ var opacityValue = 0; var rightID = 0; var leftID = 0; var last = my.opacityArray.length; for (var i = 1; i < (my.imageFocusMax+1); i++) { if((i+1) > last) { opacityValue = my.opacityArray[last-1]; } else { opacityValue = my.opacityArray[i]; } rightID = imageID + i; leftID = imageID - i; if (rightID < my.max) { my.Helper.setOpacity(my.imagesDiv.childNodes[rightID], opacityValue); my.imagesDiv.childNodes[rightID].pc = my.imagesDiv.childNodes[rightID].pcMem; } if (leftID >= 0) { my.Helper.setOpacity(my.imagesDiv.childNodes[leftID], opacityValue); my.imagesDiv.childNodes[leftID].pc = my.imagesDiv.childNodes[leftID].pcMem; } } } /* Move the images to the jump target */ if(jumpTarget) { my.moveTo(jumpTarget); } /* Animate gliding to new x position */ if (my.busy === false) { my.busy = true; my.animate(); } }; /* Animates image gliding */ this.animate = function() { switch (my.target < my.current-1 || my.target > my.current+1) { case true: my.moveTo(my.current + (my.target-my.current)/3); window.setTimeout(my.animate, my.animationSpeed); my.busy = true; break; default: my.busy = false; break; } }; /* Used by user events to call the glideTo function */ this.glideOnEvent = function(imageID) { /* Interrupt slideshow on mouse wheel, keypress, touch and mouse drag */ if(my.slideshow) { my.Slideshow.interrupt(); } /* Glide to new imageID */ my.glideTo(imageID); }; /* Slideshow function */ this.Slideshow = { direction: 1, init: function() { /* Call start() if autoplay is enabled, stop() if it is disabled */ (my.slideshowAutoplay) ? my.Slideshow.start() : my.Slideshow.stop(); }, interrupt: function() { /* Remove interrupt event */ my.Helper.removeEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt); /* Interrupt the slideshow */ my.Slideshow.stop(); }, addInterruptEvent: function() { /* A click anywhere inside the ImageFlow div interrupts the slideshow */ my.Helper.addEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt); }, start: function() { /* Set button style to pause */ my.Helper.setClassName(my.buttonSlideshow, 'slideshow pause'); /* Set onclick behaviour to stop */ my.buttonSlideshow.onclick = function () { my.Slideshow.stop(); }; /* Set slide interval */ my.Slideshow.action = window.setInterval(my.Slideshow.slide, my.slideshowSpeed); /* Allow the user to always interrupt the slideshow */ window.setTimeout(my.Slideshow.addInterruptEvent, 100); }, stop: function() { /* Set button style to play */ my.Helper.setClassName(my.buttonSlideshow, 'slideshow play'); /* Set onclick behaviour to start */ my.buttonSlideshow.onclick = function () { my.Slideshow.start(); }; /* Clear slide interval */ window.clearInterval(my.Slideshow.action); }, slide: function() { var newImageID = my.imageID + my.Slideshow.direction; var reverseDirection = false; /* Reverse direction at the last image on the right */ if(newImageID === my.max) { my.Slideshow.direction = -1; reverseDirection = true; } /* Reverse direction at the last image on the left */ if(newImageID < 0) { my.Slideshow.direction = 1; reverseDirection = true; } /* If direction is reversed recall this method, else call the glideTo method */ (reverseDirection) ? my.Slideshow.slide() : my.glideTo(newImageID); } }; /* Mouse Wheel support */ this.MouseWheel = { init: function() { /* Init mouse wheel listener */ if(window.addEventListener) { my.ImageFlowDiv.addEventListener('DOMMouseScroll', my.MouseWheel.get, false); } my.Helper.addEvent(my.ImageFlowDiv,'mousewheel',my.MouseWheel.get); }, get: function(event) { var delta = 0; if (!event) { event = window.event; } if (event.wheelDelta) { delta = event.wheelDelta / 120; } else if (event.detail) { delta = -event.detail / 3; } if (delta) { my.MouseWheel.handle(delta); } my.Helper.suppressBrowserDefault(event); }, handle: function(delta) { var change = false; var newImageID = 0; if(delta > 0) { if(my.imageID >= 1) { newImageID = my.imageID -1; change = true; } } else { if(my.imageID < (my.max-1)) { newImageID = my.imageID +1; change = true; } } /* Glide to next (mouse wheel down) / previous (mouse wheel up) image */ if(change) { my.glideOnEvent(newImageID); } } }; /* Mouse Dragging */ this.MouseDrag = { object: null, objectX: 0, mouseX: 0, newX: 0, busy: false, /* Init mouse event listener */ init: function() { my.Helper.addEvent(my.ImageFlowDiv,'mousemove',my.MouseDrag.drag); my.Helper.addEvent(my.ImageFlowDiv,'mouseup',my.MouseDrag.stop); my.Helper.addEvent(document,'mouseup',my.MouseDrag.stop); /* Avoid text and image selection while dragging */ my.ImageFlowDiv.onselectstart = function () { var selection = true; if (my.MouseDrag.busy) { selection = false; } return selection; }; }, start: function(o) { my.MouseDrag.object = o; my.MouseDrag.objectX = my.MouseDrag.mouseX - o.offsetLeft + my.newSliderX; }, stop: function() { my.MouseDrag.object = null; my.MouseDrag.busy = false; }, drag: function(e) { var posx = 0; if (!e) { e = window.event; } if (e.pageX) { posx = e.pageX; } else if (e.clientX) { posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; } my.MouseDrag.mouseX = posx; if(my.MouseDrag.object !== null) { var newX = (my.MouseDrag.mouseX - my.MouseDrag.objectX) + my.sliderWidth; /* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */ if(newX < ( - my.newSliderX)) { newX = - my.newSliderX; } if(newX > (my.scrollbarWidth - my.newSliderX)) { newX = my.scrollbarWidth - my.newSliderX; } /* Set new slider position */ var step, imageID; if(my.circular) { step = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-(my.imageFocusMax*2)-1)); imageID = Math.round(step)+my.imageFocusMax; } else { step = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-1)); imageID = Math.round(step); } my.MouseDrag.newX = newX; my.MouseDrag.object.style.left = newX + 'px'; if(my.imageID !== imageID) { my.glideOnEvent(imageID); } my.MouseDrag.busy = true; } } }; /* Safari touch events on the iPhone and iPod Touch */ this.Touch = { x: 0, startX: 0, stopX: 0, busy: false, first: true, /* Init touch event listener */ init: function() { my.Helper.addEvent(my.navigationDiv,'touchstart',my.Touch.start); my.Helper.addEvent(document,'touchmove',my.Touch.handle); my.Helper.addEvent(document,'touchend',my.Touch.stop); }, isOnNavigationDiv: function(e) { var state = false; if(e.touches) { var target = e.touches[0].target; if(target === my.navigationDiv || target === my.sliderDiv || target === my.scrollbarDiv) { state = true; } } return state; }, getX: function(e) { var x = 0; if(e.touches) { x = e.touches[0].pageX; } return x; }, start: function(e) { my.Touch.startX = my.Touch.getX(e); my.Touch.busy = true; my.Helper.suppressBrowserDefault(e); }, isBusy: function() { var busy = false; if(my.Touch.busy) { busy = true; } return busy; }, /* Handle touch event position within the navigation div */ handle: function(e) { if(my.Touch.isBusy && my.Touch.isOnNavigationDiv(e)) { var max = (my.circular) ? (my.max-(my.imageFocusMax*2)-1) : (my.max-1); if(my.Touch.first) { my.Touch.stopX = (max - my.imageID) * (my.imagesDivWidth / max); my.Touch.first = false; } var newX = -(my.Touch.getX(e) - my.Touch.startX - my.Touch.stopX); /* Map x-axis touch coordinates in range of the ImageFlow width */ if(newX < 0) { newX = 0; } if(newX > my.imagesDivWidth) { newX = my.imagesDivWidth; } my.Touch.x = newX; var imageID = Math.round(newX / (my.imagesDivWidth / max)); imageID = max - imageID; if(my.imageID !== imageID) { if(my.circular) { imageID = imageID + my.imageFocusMax; } my.glideOnEvent(imageID); } my.Helper.suppressBrowserDefault(e); } }, stop: function() { my.Touch.stopX = my.Touch.x; my.Touch.busy = false; } }; /* Key support */ this.Key = { /* Init key event listener */ init: function() { document.onkeydown = function(event){ my.Key.handle(event); }; }, /* Handle the arrow keys */ handle: function(event) { var charCode = my.Key.get(event); switch (charCode) { /* Right arrow key */ case 39: my.MouseWheel.handle(-1); break; /* Left arrow key */ case 37: my.MouseWheel.handle(1); break; } }, /* Get the current keycode */ get: function(event) { event = event || window.event; return event.keyCode; } }; /* Helper functions */ this.Helper = { /* Add events */ addEvent: function(obj, type, fn) { if(obj.addEventListener) { obj.addEventListener(type, fn, false); } else if(obj.attachEvent) { obj["e"+type+fn] = fn; obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }; obj.attachEvent( "on"+type, obj[type+fn] ); } }, /* Remove events */ removeEvent: function( obj, type, fn ) { if (obj.removeEventListener) { obj.removeEventListener( type, fn, false ); } else if (obj.detachEvent) { /* The IE breaks if you're trying to detach an unattached event http://msdn.microsoft.com/en-us/library/ms536411(VS.85).aspx */ if(obj[type+fn] === undefined) { alert('Helper.removeEvent » Pointer to detach event is undefined - perhaps you are trying to detach an unattached event?'); } obj.detachEvent( 'on'+type, obj[type+fn] ); obj[type+fn] = null; obj['e'+type+fn] = null; } }, /* Set image opacity */ setOpacity: function(object, value) { if(my.opacity === true) { object.style.opacity = value/10; object.style.filter = 'alpha(opacity=' + value*10 + ')'; } }, /* Create HTML elements */ createDocumentElement: function(type, id, optionalClass) { var element = document.createElement(type); element.setAttribute('id', my.ImageFlowID+'_'+id); if(optionalClass !== undefined) { id += ' '+optionalClass; } my.Helper.setClassName(element, id); return element; }, /* Set CSS class */ setClassName: function(element, className) { if(element) { element.setAttribute('class', className); element.setAttribute('className', className); } }, /* Suppress default browser behaviour to avoid image/text selection while dragging */ suppressBrowserDefault: function(e) { if(e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } return false; }, /* Add functions to the window.onresize event - can not be done by addEvent */ addResizeEvent: function() { var otherFunctions = window.onresize; if(typeof window.onresize != 'function') { window.onresize = function() { my.refresh(); }; } else { window.onresize = function(){ if (otherFunctions) { otherFunctions(); } my.refresh(); }; } } }; } /* DOMContentLoaded event handler - by Tanny O'Haley [4] */ var domReadyEvent = { name: "domReadyEvent", /* Array of DOMContentLoaded event handlers.*/ events: {}, domReadyID: 1, bDone: false, DOMContentLoadedCustom: null, /* Function that adds DOMContentLoaded listeners to the array.*/ add: function(handler) { /* Assign each event handler a unique ID. If the handler has an ID, it has already been added to the events object or been run.*/ if (!handler.$$domReadyID) { handler.$$domReadyID = this.domReadyID++; /* If the DOMContentLoaded event has happened, run the function. */ if(this.bDone) { handler(); } /* store the event handler in the hash table */ this.events[handler.$$domReadyID] = handler; } }, remove: function(handler) { /* Delete the event handler from the hash table */ if (handler.$$domReadyID) { delete this.events[handler.$$domReadyID]; } }, /* Function to process the DOMContentLoaded events array. */ run: function() { /* quit if this function has already been called */ if (this.bDone) { return; } /* Flag this function so we don't do the same thing twice */ this.bDone = true; /* iterates through array of registered functions */ for (var i in this.events) { this.events[i](); } }, schedule: function() { /* Quit if the init function has already been called*/ if (this.bDone) { return; } /* First, check for Safari or KHTML.*/ if(/KHTML|WebKit/i.test(navigator.userAgent)) { if(/loaded|complete/.test(document.readyState)) { this.run(); } else { /* Not ready yet, wait a little more.*/ setTimeout(this.name + ".schedule()", 100); } } else if(document.getElementById("__ie_onload")) { /* Second, check for IE.*/ return true; } /* Check for custom developer provided function.*/ if(typeof this.DOMContentLoadedCustom === "function") { /* if DOM methods are supported, and the body element exists (using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section) */ if(typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null)) { /* Call custom function. */ if(this.DOMContentLoadedCustom()) { this.run(); } else { /* Not ready yet, wait a little more. */ setTimeout(this.name + ".schedule()", 250); } } } return true; }, init: function() { /* If addEventListener supports the DOMContentLoaded event.*/ if(document.addEventListener) { document.addEventListener("DOMContentLoaded", function() { domReadyEvent.run(); }, false); } /* Schedule to run the init function.*/ setTimeout("domReadyEvent.schedule()", 100); function run() { domReadyEvent.run(); } /* Just in case window.onload happens first, add it to onload using an available method.*/ if(typeof addEvent !== "undefined") { addEvent(window, "load", run); } else if(document.addEventListener) { document.addEventListener("load", run, false); } else if(typeof window.onload === "function") { var oldonload = window.onload; window.onload = function() { domReadyEvent.run(); oldonload(); }; } else { window.onload = run; } /* for Internet Explorer */ /*@cc_on @if (@_win32 || @_win64) document.write("<script id=__ie_onload defer src=\"//:\"><\/script>"); var script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") { domReadyEvent.run(); // call the onload handler } }; @end @*/ } }; var domReady = function(handler) { domReadyEvent.add(handler); }; domReadyEvent.init(); /* Create ImageFlow instances when the DOM structure has been loaded */ domReady(function() { var instanceOne = new ImageFlow(); instanceOne.init({ ImageFlowID:'myImageFlow' }); });
014miharu-hirayama
custom_itunes.php-ext/ImageFlow_1.3.0/imageflow.js
JavaScript
oos
39,143
<?php /* ------------------------------------------------------------------- Easy Reflections v3 by Richard Davey, Core PHP (rich@corephp.co.uk) Released 13th March 2007 Includes code submissions from Monte Ohrt (monte@ohrt.com) ------------------------------------------------------------------- You are free to use this in any product, or on any web site. I'd appreciate it if you email and tell me where you use it, thanks. Latest builds at: http://reflection.corephp.co.uk ------------------------------------------------------------------- This script accepts the following $_GET parameters: img required The source image to reflect height optional Height of the reflection (% or pixel value) fade_start optional Start the alpha fade from whch value? (% value) fade_end optional End the alpha fade from whch value? (% value) cache optional Save reflection image to the cache? (boolean) tint optional Tint the reflection with this colour (hex) */ // PHP Version sanity check if (version_compare('4.3.2', phpversion()) == 1) { echo 'This version of PHP is not fully supported. You need 4.3.2 or above.'; exit(); } // GD check if (extension_loaded('gd') == false && !dl('gd.so')) { echo 'You are missing the GD extension for PHP, sorry but I cannot continue.'; exit(); } // GD Version check $gd_info = gd_info(); if ($gd_info['PNG Support'] == false) { echo 'This version of the GD extension cannot output PNG images.'; exit(); } if (ereg_replace('[[:alpha:][:space:]()]+', '', $gd_info['GD Version']) < '2.0.1') { echo 'GD library is too old. Version 2.0.1 or later is required, and 2.0.28 is strongly recommended.'; exit(); } // Our allowed query string parameters // To cache or not to cache? that is the question if (isset($_GET['cache'])) { if ((int) $_GET['cache'] == 1) { $cache = true; } else { $cache = false; } } else { $cache = true; } // img (the image to reflect) if (isset($_GET['img'])) { $source_image = $_GET['img']; $source_image = str_replace('://','',$source_image); //$source_image = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $source_image; if (file_exists($source_image)) { if ($cache) { $cache_dir = dirname($source_image); $cache_base = basename($source_image); $cache_file = 'refl_' . md5($_SERVER['REQUEST_URI']) . '_' . $cache_base; $cache_path = $cache_dir . DIRECTORY_SEPARATOR . $cache_file; if (file_exists($cache_path) && filemtime($cache_path) >= filemtime($source_image)) { // Use cached image $image_info = getimagesize($cache_path); header("Content-type: " . $image_info['mime']); readfile($cache_path); exit(); } } } else { echo 'Cannot find or read source image'; exit(); } } else { echo 'No source image to reflect supplied'; exit(); } // tint (the colour used for the tint, defaults to white if not given) if (isset($_GET['tint']) == false) { $red = 127; $green = 127; $blue = 127; } else { // Extract the hex colour $hex_bgc = $_GET['tint']; // Does it start with a hash? If so then strip it $hex_bgc = str_replace('#', '', $hex_bgc); switch (strlen($hex_bgc)) { case 6: $red = hexdec(substr($hex_bgc, 0, 2)); $green = hexdec(substr($hex_bgc, 2, 2)); $blue = hexdec(substr($hex_bgc, 4, 2)); break; case 3: $red = substr($hex_bgc, 0, 1); $green = substr($hex_bgc, 1, 1); $blue = substr($hex_bgc, 2, 1); $red = hexdec($red . $red); $green = hexdec($green . $green); $blue = hexdec($blue . $blue); break; default: // Wrong values passed, default to white $red = 127; $green = 127; $blue = 127; } } // height (how tall should the reflection be?) if (isset($_GET['height'])) { $output_height = $_GET['height']; // Have they given us a percentage? if (substr($output_height, -1) == '%') { // Yes, remove the % sign $output_height = (int) substr($output_height, 0, -1); // Gotta love auto type casting ;) if ($output_height == 100) { $output_height = "0.99"; } elseif ($output_height < 10) { $output_height = "0.0$output_height"; } else { $output_height = "0.$output_height"; } } else { $output_height = (int) $output_height; } } else { // No height was given, so default to 50% of the source images height $output_height = 0.50; } if (isset($_GET['fade_start'])) { if (strpos($_GET['fade_start'], '%') !== false) { $alpha_start = str_replace('%', '', $_GET['fade_start']); $alpha_start = (int) (127 * $alpha_start / 100); } else { $alpha_start = (int) $_GET['fade_start']; if ($alpha_start < 1 || $alpha_start > 127) { $alpha_start = 80; } } } else { $alpha_start = 80; } if (isset($_GET['fade_end'])) { if (strpos($_GET['fade_end'], '%') !== false) { $alpha_end = str_replace('%', '', $_GET['fade_end']); $alpha_end = (int) (127 * $alpha_end / 100); } else { $alpha_end = (int) $_GET['fade_end']; if ($alpha_end < 1 || $alpha_end > 0) { $alpha_end = 0; } } } else { $alpha_end = 0; } /* ---------------------------------------------------------------- Ok, let's do it ... ---------------------------------------------------------------- */ // How big is the image? $image_details = getimagesize($source_image); if ($image_details === false) { echo 'Not a valid image supplied, or this script does not have permissions to access it.'; exit(); } else { $width = $image_details[0]; $height = $image_details[1]; $type = $image_details[2]; $mime = $image_details['mime']; } // Calculate the height of the output image if ($output_height < 1) { // The output height is a percentage $new_height = $height * $output_height; } else { // The output height is a fixed pixel value $new_height = $output_height; } // Detect the source image format - only GIF, JPEG and PNG are supported. If you need more, extend this yourself. switch ($type) { case 1: // GIF $source = imagecreatefromgif($source_image); break; case 2: // JPG $source = imagecreatefromjpeg($source_image); break; case 3: // PNG $source = imagecreatefrompng($source_image); break; default: echo 'Unsupported image file format.'; exit(); } /* ---------------------------------------------------------------- Build the reflection image ---------------------------------------------------------------- */ // We'll store the final reflection in $output. $buffer is for internal use. $output = imagecreatetruecolor($width, $new_height); $buffer = imagecreatetruecolor($width, $new_height); // Save any alpha data that might have existed in the source image and disable blending imagesavealpha($source, true); imagesavealpha($output, true); imagealphablending($output, false); imagesavealpha($buffer, true); imagealphablending($buffer, false); // Copy the bottom-most part of the source image into the output imagecopy($output, $source, 0, 0, 0, $height - $new_height, $width, $new_height); // Rotate and flip it (strip flip method) for ($y = 0; $y < $new_height; $y++) { imagecopy($buffer, $output, 0, $y, 0, $new_height - $y - 1, $width, 1); } $output = $buffer; /* ---------------------------------------------------------------- Apply the fade effect ---------------------------------------------------------------- */ // This is quite simple really. There are 127 available levels of alpha, so we just // step-through the reflected image, drawing a box over the top, with a set alpha level. // The end result? A cool fade. // There are a maximum of 127 alpha fade steps we can use, so work out the alpha step rate $alpha_length = abs($alpha_start - $alpha_end); imagelayereffect($output, IMG_EFFECT_OVERLAY); for ($y = 0; $y <= $new_height; $y++) { // Get % of reflection height $pct = $y / $new_height; // Get % of alpha if ($alpha_start > $alpha_end) { $alpha = (int) ($alpha_start - ($pct * $alpha_length)); } else { $alpha = (int) ($alpha_start + ($pct * $alpha_length)); } // Rejig it because of the way in which the image effect overlay works $final_alpha = 127 - $alpha; //imagefilledrectangle($output, 0, $y, $width, $y, imagecolorallocatealpha($output, 127, 127, 127, $final_alpha)); imagefilledrectangle($output, 0, $y, $width, $y, imagecolorallocatealpha($output, $red, $green, $blue, $final_alpha)); } /* ---------------------------------------------------------------- HACK - Build the reflection image by combining the source image AND the reflection in one new image! ---------------------------------------------------------------- */ $finaloutput = imagecreatetruecolor($width, $height+$new_height); imagesavealpha($finaloutput, true); $trans_colour = imagecolorallocatealpha($finaloutput, 0, 0, 0, 127); imagefill($finaloutput, 0, 0, $trans_colour); imagecopy($finaloutput, $source, 0, 0, 0, 0, $width, $height); imagecopy($finaloutput, $output, 0, $height, 0, 0, $width, $new_height); $output = $finaloutput; /* ---------------------------------------------------------------- Output our final PNG ---------------------------------------------------------------- */ if (headers_sent()) { echo 'Headers already sent, I cannot display an image now. Have you got an extra line-feed in this file somewhere?'; exit(); } else { // PNG header("Content-type: image/png"); imagepng($output); // Save cached file if ($cache) { imagepng($output, $cache_path); } imagedestroy($output); exit(); } ?>
014miharu-hirayama
custom_itunes.php-ext/ImageFlow_1.3.0/reflect3.php
PHP
oos
10,883
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
1031868817-hws
mock_server/playfoursquare.py
Python
asf20
2,253
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredSettings { public static final boolean USE_DEBUG_SERVER = false; public static final boolean DEBUG = false; public static final boolean LOCATION_DEBUG = false; public static final boolean USE_DUMPCATCHER = true; public static final boolean DUMPCATCHER_TEST = false; }
1031868817-hws
examples/FoursquaredSettings.java
Java
asf20
444
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare; public class TestCredentials { public static final String oAuthConsumerKey = ""; public static final String oAuthConsumerSecret = ""; public static final String oAuthToken = ""; public static final String oAuthTokenSecret = ""; public static final String testFoursquarePhone = ""; public static final String testFoursquarePassword = ""; }
1031868817-hws
examples/TestCredentials.java
Java
asf20
441
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
1031868817-hws
util/generate.py
Python
asf20
772
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
1031868817-hws
util/oget.py
Python
asf20
3,416
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
1031868817-hws
util/gen_parser.py
Python
asf20
4,392
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
1031868817-hws
util/common.py
Python
asf20
2,820
<html> <head> <style type="text/css"> body { background:#fff; color:#000; font:normal 12px Tahoma, Arial, Helvetica, Serif; margin:0px; padding:0px; } h4 { float:left; height:15px; margin:0px 0 0; padding:20px 0 0 10px; font:bold 15px Arial, Helvetica, Serif; } h4 span { float:left; padding:0 5px; margin-top:-10px; } ul { clear:both;margin:0 0 15px; padding:0 0 0 20px; } ul li { margin:0;padding:0; list-style-type:square; margin-bottom:5px; margin-left:20px; font:13px Arial, Helvetica, Serif; } </style> </head> <body> <h4><span>What's new in v2010-10-05?</span></h4> <ul> <li>Badge description now being shown with badge-unlock in post-checkin dialog.</li> <li>Post-checkin scores were not being displayed. Scores were still being recorded for users on the foursquare servers, just not being shown in the results dialog.</li> <li>Venue shortcut-creation bug fixed.</li> <li>URLs now being linked in tip/to-do details screen.</li> </ul> <h4><span>What's new in v2010-09-30</span></h4> <ul> <li>Redesign for most activity screens.</li> <li>Tips and To-do screens added as top-level tabs.</li> <li>Friend information added to venue pages.</li> <li>Can access friend requests from Me tab.</li> <li>Can now refresh Me tab.</li> <li>Switched from xml to json for API calls.</li> </ul> <h4><span>What's new in v2010-08-31</span></h4> <ul> <li>Option for install to SD card (Android 2.2 and above required).</li> <li>Added profile settings information to Preferences page. This is a convenience to let users see what email address and name they're using with their Foursquare account.</li> <li>SSL support.</li> </ul> <h4><span>What's new in v2010-08-05</span></h4> <ul> <li>Click your user photo in the 'Me' tab to set a new photo for yourself.</li> <li>Added an option in preferences to use a Foursquare image viewer for viewing user photos. Un-check "Image Viewing" to use it instead of your phone's native image viewer (default).</li> </ul> <h4><span>What's new in v2010-07-13</span></h4> <ul> <li>Bug fix for new category icons (from 2010-07-12 version) which could cause a force-close on the Places tab.</li> </ul> <h4><span>What's new in v2010-07-12</span></h4> <ul> <li>Friend requests screen now has an input filter at top, should make it easier to locate specific friend requests by name.</li> <li>Places list items now have a 'special' icon when the venue is offering a special. Also now showing a person icon when the venue is trending.</li> <li>High res category icons being used now.</li> <li>Added last n system logs messages to feedback emails to help diagnose application errors.</li> </ul> <h4><span>What's new in v2010-06-28</span></h4> <ul> <li>Showing recent nearby friend checkins on a map. You can find this on the Friends tab, Menu -> More -> Map.</li> <li>Add Friends screen now has an option to find Facebook friends that are also using Foursquare. NOTE: There's a render bug in Android for the Facebook login page which makes the username and password fields misalign when the virtual keypad is displayed, this should be fixed in Android Froyo.</li> </ul> <h4><span>What's new in v2010-06-16</span></h4> <ul> <li>The venue activity has a new menu option called 'Edit Venue' which gives you the option to propose venue edits. These include marking a venue as closed, duplicate, or mislocated. The last option allows you to update all venue information such as address, name, etc.</li> <li>Menu for Friends tab updated to have a 'more' item, which gives the option to sort friend checkins by time or distance.</li> <li>Add friends and find friends items added to 'more' item on Friends tab menu. <li>Refresh menu item moved to first position in Places tab to be consistent with Friends tab.</li> <li>Fixed bug introduced in v2010-06-07 which was formatting the times of checkins incorrectly in the Friends tab.</li> </ul> <h4><span>What's new in v2010-06-07</span></h4> <ul> <li>Now showing the 'add friend' option on user details screens, if not already friends. Should make it easier to build your network. </li> <li>Checkin pings support. A service will wake every N minutes (user-configurable) to check for new checkins from friends. </li> <li>New item on user details pages named 'pings', allows you to turn pings on/off per user. Only applicable if you have enabled ping notifications for yourself. </li> <li>Fix a widget bug that would cause "Application Not Responding" errors.</li> <li>Fixed bug for new users on 1.5. The empty friends screen would crash on some android 1.5 devices.</li> </ul> <h4><span>What's new in v2010-05-11</span></h4> <ul> <li>Friend invites page now has an option to generate a list of contacts not on foursquare for sending email invites to join. This should make it easier to get friends playing along. </li> <li>For new users, the Friends tab will now show a sad face and two buttons 'add friends' & 'friend requests'. This should make it a little easier for new users to start adding friends. </li> <li>Updated default message for venue pages when there are no recent checkins. This was done to make it clear that the venue page is only showing recent checkins, not a total checkin history. </li> <li>Sorting nearby venues by popularity and distance instead of just distance, <a href="http://blog.foursquare.com/post/589698188/weve-just-made-the-places-screen-smarter">read here</a> for more info.</li> <li>Updated to SDK level 6. </li> </ul> <h4><span>v2010-04-23</span></h4> <ul> <li>Default zoom level for venue map is closer to street level.</li> <li>Added a new option through preferences which allows user to clear their current geo location before each venue search. This may help users having issues with geolocation.</li> <li>Updated application icon and menu icons for v6 and newer platforms.</li> <li>Showing reverse geolocation footer on Places tab.</li> </ul> <h4><span>v2010-04-09</span></h4> <ul> <li>New check-in button on venue page.</li> <li>Added a native sign up screen from the login page.</li> <li>Added a 'special' button to the venue page if the venue has a special available.</li> <li>Menu added for Me page, makes it easier to get to the Friend Requests page.</li> <li>Made quick-check-in off by default instead of on. Users can change this in preferences page.</li> <li>Fixed timestamp bug which would place some Droid users in the year 1910.</li> </ul> <h4><span>v2010-03-29</span></h4> <ul> <li>Update for timestamp formatting.</li> </ul> <h4><span>v2010-03-28</span></h4> <ul> <li>Updated checkin screen.</li> </ul> <h4><span>v2010-03-26</span></h4> <ul> <li>Added user photos to venue tips list.</li> <li>Clicking a tip from a venue page displays a new list of options (listing your to-do/completed tips will be added in a future version).</li> <li>Clicking on a nearby special shows venue details for that venue on post-checkin screen.</li> <li>Clicking on mayor photo in post-checkin screen shows user details.</li> <li>Updated distance sorting of venue searches.</li> </ul> <h4><span>v2010-03-23</span></h4> <ul> <li>This "What's New" page.</li> <li>View a user's mayorships through the user details page.</li> <li>History times are now formatted.</li> <li>Choose startup tab (Friends or Places) through the preferences page.</li> <li>Friends checkin tab is sorted by distance and checkin times.</li> <li>Added category icons for user history list.</li> </ul> <h4><span>v2010-03-12</span></h4> <ul> <li>New UI design.</li> <li>See user's mayorhip and badge count.</li> <li>See your own foursquare history.</li> <li>See friends of friends.</li> <li>See contact info of friends.</li> </ul> <h4><span>v2010-03-05</span></h4> <ul> <li>Global Search.</li> <li>Add Friends from Preferences page.</li> <li>Handle friend requests from Preferences page.</li> <li>Click on a user's photo in user details page to see full-size image.</li> </ul> </body> </html>
1031868817-hws
main/assets/changelog-en.html
HTML
asf20
9,096
/** * Copyright 2010 Mark Wyszomierski * * 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.facebook.android; import com.joelapenna.foursquared.R; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.ViewGroup.LayoutParams; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; import android.widget.TextView; /** * This activity can be used to run a facebook url request through a webview. * The user must supply these intent extras: * <ul> * <li>INTENT_EXTRA_ACTION - string, which facebook action to perform, like * "login", or "stream.publish".</li> * <li>INTENT_EXTRA_KEY_APP_ID - string, facebook developer key.</li> * <li>INTENT_EXTRA_KEY_PERMISSIONS - string array, set of facebook permissions * you want to use.</li> * </ul> * or you can supply only INTENT_EXTRA_KEY_CLEAR_COOKIES to just have the * activity clear its stored cookies (you can also supply it in combination with * the above flags to clear cookies before trying to run a request too). If * you've already authenticated the user, you can optionally pass in the token * and expiration time as intent extras using: * <ul> * <li>INTENT_EXTRA_AUTHENTICATED_TOKEN</li> * <li>INTENT_EXTRA_AUTHENTICATED_EXPIRES</li> * </ul> * they will then be used in web requests. You should use * <code>startActivityForResult</code> to start the activity. When the activity * finishes, it will return status code RESULT_OK. You can then check the * returned intent data object for: * <ul> * <li>INTENT_RESULT_KEY_RESULT_STATUS - boolean, whether the request succeeded * or not.</li> * <li>INTENT_RESULT_KEY_SUPPLIED_ACTION - string, the action you supplied as an * intent extra echoed back as a convenience.</li> * <li>INTENT_RESULT_KEY_RESULT_BUNDLE - bundle, present if request succeeded, * will have all the returned parameters as supplied by the WebView operation.</li> * <li>INTENT_RESULT_KEY_ERROR - string, present if request failed.</li> * </ul> * If the user canceled this activity, the activity result code will be * RESULT_CANCELED and there will be no intent data returned. You need the * <code>android.permission.INTERNET</code> permission added to your manifest. * You need to add this activity definition to your manifest. You can prevent * this activity from restarting on rotation so the network operations are * preserved within the WebView like so: * * <activity * android:name="com.facebook.android.FacebookWebViewActivity" * android:configChanges="orientation|keyboardHidden" /> * * This class and the rest of the facebook classes within this package are from * the facebook android library project: * * http://github.com/facebook/facebook-android-sdk * * The project implementation had several problems with it which made it unusable * in a production application. It has been rewritten here for use with the * Foursquare project. * * @date June 14, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class FacebookWebViewActivity extends Activity { private static final String TAG = "FacebookWebViewActivity"; public static final String INTENT_EXTRA_ACTION = "com.facebook.android.FacebookWebViewActivity.action"; public static final String INTENT_EXTRA_KEY_APP_ID = "com.facebook.android.FacebookWebViewActivity.appid"; public static final String INTENT_EXTRA_KEY_PERMISSIONS = "com.facebook.android.FacebookWebViewActivity.permissions"; public static final String INTENT_EXTRA_AUTHENTICATED_TOKEN = "com.facebook.android.FacebookWebViewActivity.authenticated_token"; public static final String INTENT_EXTRA_AUTHENTICATED_EXPIRES = "com.facebook.android.FacebookWebViewActivity.authenticated_expires"; public static final String INTENT_EXTRA_KEY_CLEAR_COOKIES = "com.facebook.android.FacebookWebViewActivity.clear_cookies"; public static final String INTENT_EXTRA_KEY_DEBUG = "com.facebook.android.FacebookWebViewActivity.debug"; public static final String INTENT_RESULT_KEY_RESULT_STATUS = "result_status"; public static final String INTENT_RESULT_KEY_SUPPLIED_ACTION = "supplied_action"; public static final String INTENT_RESULT_KEY_RESULT_BUNDLE = "bundle"; public static final String INTENT_RESULT_KEY_ERROR = "error"; private static final String DISPLAY_STRING = "touch"; private static final int FB_BLUE = 0xFF6D84B4; private static final int MARGIN = 4; private static final int PADDING = 2; private TextView mTitle; private WebView mWebView; private ProgressDialog mSpinner; private String mAction; private String mAppId; private String[] mPermissions; private boolean mDebug; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); CookieSyncManager.createInstance(this); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mTitle = new TextView(this); mTitle.setText("Facebook"); mTitle.setTextColor(Color.WHITE); mTitle.setTypeface(Typeface.DEFAULT_BOLD); mTitle.setBackgroundColor(FB_BLUE); mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN); mTitle.setCompoundDrawablePadding(MARGIN + PADDING); mTitle.setCompoundDrawablesWithIntrinsicBounds(this.getResources().getDrawable( R.drawable.facebook_icon), null, null, null); ll.addView(mTitle); mWebView = new WebView(this); mWebView.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mWebView.setWebViewClient(new WebViewClientFacebook()); mWebView.setVerticalScrollBarEnabled(false); mWebView.setHorizontalScrollBarEnabled(false); mWebView.getSettings().setJavaScriptEnabled(true); ll.addView(mWebView); mSpinner = new ProgressDialog(this); mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE); mSpinner.setMessage("Loading..."); setContentView(ll, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); Bundle extras = getIntent().getExtras(); if (extras != null) { if (extras.containsKey(INTENT_EXTRA_KEY_DEBUG)) { mDebug = extras.getBoolean(INTENT_EXTRA_KEY_DEBUG); } if (extras.containsKey(INTENT_EXTRA_ACTION)) { if (extras.getBoolean(INTENT_EXTRA_KEY_CLEAR_COOKIES, false)) { clearCookies(); } if (extras.containsKey(INTENT_EXTRA_KEY_APP_ID)) { if (extras.containsKey(INTENT_EXTRA_KEY_PERMISSIONS)) { mAction = extras.getString(INTENT_EXTRA_ACTION); mAppId = extras.getString(INTENT_EXTRA_KEY_APP_ID); mPermissions = extras.getStringArray(INTENT_EXTRA_KEY_PERMISSIONS); // If the user supplied a pre-authenticated info, use it // here. Facebook facebook = new Facebook(); if (extras.containsKey(INTENT_EXTRA_AUTHENTICATED_TOKEN) && extras.containsKey(INTENT_EXTRA_AUTHENTICATED_EXPIRES)) { facebook.setAccessToken(extras .getString(INTENT_EXTRA_AUTHENTICATED_TOKEN)); facebook.setAccessExpires(extras .getLong(INTENT_EXTRA_AUTHENTICATED_EXPIRES)); if (mDebug) { Log.d(TAG, "onCreate(): authenticated token being used."); } } // Generate the url based on the action. String url = facebook.generateUrl(mAction, mAppId, mPermissions); if (mDebug) { String permissionsDump = "(null)"; if (mPermissions != null) { if (mPermissions.length > 0) { for (int i = 0; i < mPermissions.length; i++) { permissionsDump += mPermissions[i] + ", "; } } else { permissionsDump = "[empty]"; } } Log.d(TAG, "onCreate(): action: " + mAction + ", appid: " + mAppId + ", permissions: " + permissionsDump); Log.d(TAG, "onCreate(): Loading url: " + url); } // Start the request finally. mWebView.loadUrl(url); } else { Log.e(TAG, "Missing intent extra: INTENT_EXTRA_KEY_PERMISSIONS, finishing immediately."); finish(); } } else { Log.e(TAG, "Missing intent extra: INTENT_EXTRA_KEY_APP_ID, finishing immediately."); finish(); } } else if (extras.getBoolean(INTENT_EXTRA_KEY_CLEAR_COOKIES)) { clearCookies(); } else { Log.e(TAG, "Missing intent extra: INTENT_EXTRA_ACTION or INTENT_EXTRA_KEY_CLEAR_COOKIES, finishing immediately."); finish(); } } else { Log.e(TAG, "No intent extras supplied, finishing immediately."); finish(); } } private void clearCookies() { CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); } @Override protected void onResume() { super.onResume(); CookieSyncManager.getInstance().startSync(); } @Override protected void onPause() { super.onPause(); CookieSyncManager.getInstance().stopSync(); } private class WebViewClientFacebook extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (mDebug) { Log.d(TAG, "WebViewClientFacebook:shouldOverrideUrlLoading(): " + url); } if (url.startsWith(Facebook.REDIRECT_URI)) { Bundle values = FacebookUtil.parseUrl(url); String error = values.getString("error_reason"); Intent result = new Intent(); result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction); if (error == null) { CookieSyncManager.getInstance().sync(); result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, true); result.putExtra(INTENT_RESULT_KEY_RESULT_BUNDLE, values); FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result); } else { result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, false); result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction); result.putExtra(INTENT_RESULT_KEY_ERROR, error); FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result); } FacebookWebViewActivity.this.finish(); return true; } else if (url.startsWith(Facebook.CANCEL_URI)) { FacebookWebViewActivity.this.setResult(Activity.RESULT_CANCELED); FacebookWebViewActivity.this.finish(); return true; } else if (url.contains(DISPLAY_STRING)) { return false; } // Launch non-dialog URLs in a full browser. startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); if (mDebug) { Log.e(TAG, "WebViewClientFacebook:onReceivedError(): " + errorCode + ", " + description + ", " + failingUrl); } Intent result = new Intent(); result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, false); result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction); result.putExtra(INTENT_RESULT_KEY_ERROR, description + ", " + errorCode + ", " + failingUrl); FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result); FacebookWebViewActivity.this.finish(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (mDebug) { Log.d(TAG, "WebViewClientFacebook:onPageStarted(): " + url); } mSpinner.show(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (mDebug) { Log.d(TAG, "WebViewClientFacebook:onPageFinished(): " + url); } String title = mWebView.getTitle(); if (title != null && title.length() > 0) { mTitle.setText(title); } mSpinner.dismiss(); } } }
1031868817-hws
main/src/com/facebook/android/FacebookWebViewActivity.java
Java
asf20
14,675
/* * Copyright 2010 Facebook, 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.facebook.android; /** * Encapsulation of a Facebook Error: a Facebook request that could not be * fulfilled. * * @author ssoneff@facebook.com */ public class FacebookError extends Throwable { private static final long serialVersionUID = 1L; private int mErrorCode = 0; private String mErrorType; public FacebookError(String message) { super(message); } public FacebookError(String message, String type, int code) { super(message); mErrorType = type; mErrorCode = code; } public int getErrorCode() { return mErrorCode; } public String getErrorType() { return mErrorType; } }
1031868817-hws
main/src/com/facebook/android/FacebookError.java
Java
asf20
1,304
/* * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 Facebook, 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.facebook.android; import android.os.Bundle; import android.text.TextUtils; import java.io.IOException; import java.net.MalformedURLException; /** * Main Facebook object for storing session token and session expiration date * in memory, as well as generating urls to access different facebook endpoints. * * @author Steven Soneff (ssoneff@facebook.com): * -original author. * @author Mark Wyszomierski (markww@gmail.com): * -modified to remove network operation calls, and dialog creation, * focused on making this class only generate urls for external use * and storage of a session token and expiration date. */ public class Facebook { /** Strings used in the OAuth flow */ public static final String REDIRECT_URI = "fbconnect://success"; public static final String CANCEL_URI = "fbconnect:cancel"; public static final String TOKEN = "access_token"; public static final String EXPIRES = "expires_in"; /** Login action requires a few extra steps for setup and completion. */ public static final String LOGIN = "login"; /** Facebook server endpoints: may be modified in a subclass for testing */ protected static String OAUTH_ENDPOINT = "https://graph.facebook.com/oauth/authorize"; // https protected static String UI_SERVER = "http://www.facebook.com/connect/uiserver.php"; // http protected static String GRAPH_BASE_URL = "https://graph.facebook.com/"; protected static String RESTSERVER_URL = "https://api.facebook.com/restserver.php"; private String mAccessToken = null; private long mAccessExpires = 0; public Facebook() { } /** * Invalidates the current access token in memory, and generates a * prepared URL that can be used to log the user out. * * @throws MalformedURLException * @return PreparedUrl instance reflecting the full url of the service. */ public PreparedUrl logout() throws MalformedURLException, IOException { setAccessToken(null); setAccessExpires(0); Bundle b = new Bundle(); b.putString("method", "auth.expireSession"); return requestUrl(b); } /** * Build a url to Facebook's old (pre-graph) API with the given * parameters. One of the parameter keys must be "method" and its value * should be a valid REST server API method. * * See http://developers.facebook.com/docs/reference/rest/ * * Example: * <code> * Bundle parameters = new Bundle(); * parameters.putString("method", "auth.expireSession"); * PreparedUrl preparedUrl = requestUrl(parameters); * </code> * * @param parameters * Key-value pairs of parameters to the request. Refer to the * documentation: one of the parameters must be "method". * @throws MalformedURLException * if accessing an invalid endpoint * @throws IllegalArgumentException * if one of the parameters is not "method" * @return PreparedUrl instance reflecting the full url of the service. */ public PreparedUrl requestUrl(Bundle parameters) throws MalformedURLException { if (!parameters.containsKey("method")) { throw new IllegalArgumentException("API method must be specified. " + "(parameters must contain key \"method\" and value). See" + " http://developers.facebook.com/docs/reference/rest/"); } return requestUrl(null, parameters, "GET"); } /** * Build a url to the Facebook Graph API without any parameters. * * See http://developers.facebook.com/docs/api * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @throws MalformedURLException * @return PreparedUrl instance reflecting the full url of the service. */ public PreparedUrl requestUrl(String graphPath) throws MalformedURLException { return requestUrl(graphPath, new Bundle(), "GET"); } /** * Build a url to the Facebook Graph API with the given string * parameters using an HTTP GET (default method). * * See http://developers.facebook.com/docs/api * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters "q" : "facebook" would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @throws MalformedURLException * @return PreparedUrl instance reflecting the full url of the service. */ public PreparedUrl requestUrl(String graphPath, Bundle parameters) throws MalformedURLException { return requestUrl(graphPath, parameters, "GET"); } /** * Build a PreparedUrl object which can be used with Util.openUrl(). * You can also use the returned PreparedUrl.getUrl() to run the * network operation yourself. * * Note that binary data parameters * (e.g. pictures) are not yet supported by this helper function. * * See http://developers.facebook.com/docs/api * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters {"q" : "facebook"} would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param httpMethod * http verb, e.g. "GET", "POST", "DELETE" * @throws MalformedURLException * @return PreparedUrl instance reflecting the full url of the service. */ public PreparedUrl requestUrl(String graphPath, Bundle parameters, String httpMethod) throws MalformedURLException { parameters.putString("format", "json"); if (isSessionValid()) { parameters.putString(TOKEN, getAccessToken()); } String url = graphPath != null ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL; return new PreparedUrl(url, parameters, httpMethod); } public boolean isSessionValid() { return (getAccessToken() != null) && ((getAccessExpires() == 0) || (System.currentTimeMillis() < getAccessExpires())); } public String getAccessToken() { return mAccessToken; } public long getAccessExpires() { return mAccessExpires; } public void setAccessToken(String token) { mAccessToken = token; } public void setAccessExpires(long time) { mAccessExpires = time; } public void setAccessExpiresIn(String expiresIn) { if (expiresIn != null) { setAccessExpires(System.currentTimeMillis() + Integer.parseInt(expiresIn) * 1000); } } public String generateUrl(String action, String appId, String[] permissions) { Bundle params = new Bundle(); String endpoint; if (action.equals(LOGIN)) { params.putString("client_id", appId); if (permissions != null && permissions.length > 0) { params.putString("scope", TextUtils.join(",", permissions)); } endpoint = OAUTH_ENDPOINT; params.putString("type", "user_agent"); params.putString("redirect_uri", REDIRECT_URI); } else { endpoint = UI_SERVER; params.putString("method", action); params.putString("next", REDIRECT_URI); } params.putString("display", "touch"); params.putString("sdk", "android"); if (isSessionValid()) { params.putString(TOKEN, getAccessToken()); } String url = endpoint + "?" + FacebookUtil.encodeUrl(params); return url; } /** * Stores a prepared url and parameters bundle from one of the <code>requestUrl</code> * methods. It can then be used with Util.openUrl() to run the network operation. * The Util.openUrl() requires the original params bundle and http method, so this * is just a convenience wrapper around it. * * @author Mark Wyszomierski (markww@gmail.com) */ public static class PreparedUrl { private String mUrl; private Bundle mParameters; private String mHttpMethod; public PreparedUrl(String url, Bundle parameters, String httpMethod) { mUrl = url; mParameters = parameters; mHttpMethod = httpMethod; } public String getUrl() { return mUrl; } public Bundle getParameters() { return mParameters; } public String getHttpMethod() { return mHttpMethod; } } }
1031868817-hws
main/src/com/facebook/android/Facebook.java
Java
asf20
10,363
/* * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 Facebook, 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.facebook.android; import org.json.JSONException; import org.json.JSONObject; import android.os.Bundle; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Set; /** * Utility class supporting the Facebook Object. * * @author ssoneff@facebook.com * -original author. * @author Mark Wyszomierski (markww@gmail.com): * -just removed alert dialog method which can be handled by managed * dialogs in third party apps. */ public final class FacebookUtil { public static String encodeUrl(Bundle parameters) { if (parameters == null) { return ""; } StringBuilder sb = new StringBuilder(); boolean first = true; for (String key : parameters.keySet()) { if (first) first = false; else sb.append("&"); sb.append(key + "=" + parameters.getString(key)); } return sb.toString(); } public static Bundle decodeUrl(String s) { Bundle params = new Bundle(); if (s != null) { String array[] = s.split("&"); for (String parameter : array) { String v[] = parameter.split("="); params.putString(v[0], v[1]); } } return params; } /** * Parse a URL query and fragment parameters into a key-value bundle. * * @param url the URL to parse * @return a dictionary bundle of keys and values */ public static Bundle parseUrl(String url) { // hack to prevent MalformedURLException url = url.replace("fbconnect", "http"); try { URL u = new URL(url); Bundle b = decodeUrl(u.getQuery()); b.putAll(decodeUrl(u.getRef())); return b; } catch (MalformedURLException e) { return new Bundle(); } } /** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties(). getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { // use method override params.putString("method", method); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write( encodeUrl(params).getBytes("UTF-8")); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; } private static String read(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } in.close(); return sb.toString(); } /** * Parse a server response into a JSON Object. This is a basic * implementation using org.json.JSONObject representation. More * sophisticated applications may wish to do their own parsing. * * The parsed JSON is checked for a variety of error fields and * a FacebookException is thrown if an error condition is set, * populated with the error message and error type or code if * available. * * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ public static JSONObject parseJson(String response) throws JSONException, FacebookError { // Edge case: when sending a POST request to /[post_id]/likes // the return value is 'true' or 'false'. Unfortunately // these values cause the JSONObject constructor to throw // an exception. if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response = "{value : true}"; } JSONObject json = new JSONObject(response); // errors set by the server are not consistent // they depend on the method and endpoint if (json.has("error")) { JSONObject error = json.getJSONObject("error"); throw new FacebookError( error.getString("message"), error.getString("type"), 0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"), "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; } public static String printBundle(Bundle bundle) { StringBuilder sb = new StringBuilder(); sb.append("Bundle: "); if (bundle != null) { sb.append(bundle.toString()); sb.append("\n"); Set<String> keys = bundle.keySet(); for (String it : keys) { sb.append(" "); sb.append(it); sb.append(": "); sb.append(bundle.get(it).toString()); sb.append("\n"); } } else { sb.append("(null)"); } return sb.toString(); } }
1031868817-hws
main/src/com/facebook/android/FacebookUtil.java
Java
asf20
7,679
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.maps.CheckinGroup; import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay; import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay.CheckinGroupOverlayTapListener; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.util.CheckinTimestampSort; import com.joelapenna.foursquared.util.GeoUtils; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.MapCalloutView; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added support for checkingroup items, also stopped recreation * of overlay group in onResume(). [2010-06-21] */ public class FriendsMapActivity extends MapActivity { public static final String TAG = "FriendsMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_CHECKIN_PARCELS = Foursquared.PACKAGE_NAME + ".FriendsMapActivity.EXTRA_CHECKIN_PARCELS"; private StateHolder mStateHolder; private Venue mTappedVenue; private MapCalloutView mCallout; private MapView mMapView; private MapController mMapController; private List<CheckinGroupItemizedOverlay> mCheckinGroupOverlays; private MyLocationOverlay mMyLocationOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_map_activity); if (getLastNonConfigurationInstance() != null) { mStateHolder = (StateHolder) getLastNonConfigurationInstance(); } else { if (getIntent().hasExtra(EXTRA_CHECKIN_PARCELS)) { Parcelable[] parcelables = getIntent().getParcelableArrayExtra(EXTRA_CHECKIN_PARCELS); Group<Checkin> checkins = new Group<Checkin>(); for (int i = 0; i < parcelables.length; i++) { checkins.add((Checkin)parcelables[i]); } mStateHolder = new StateHolder(); mStateHolder.setCheckins(checkins); } else { Log.e(TAG, "FriendsMapActivity requires checkin array in intent extras."); finish(); return; } } initMap(); } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.enableCompass(); } } @Override public void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); } private void initMap() { mMapView = (MapView) findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); loadSearchResults(mStateHolder.getCheckins()); mCallout = (MapCalloutView) findViewById(R.id.map_callout); mCallout.setVisibility(View.GONE); mCallout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(FriendsMapActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, mTappedVenue); startActivity(intent); } }); recenterMap(); } private void loadSearchResults(Group<Checkin> checkins) { // One CheckinItemizedOverlay per group! CheckinGroupItemizedOverlay mappableCheckinsOverlay = createMappableCheckinsOverlay(checkins); mCheckinGroupOverlays = new ArrayList<CheckinGroupItemizedOverlay>(); if (mappableCheckinsOverlay != null) { mCheckinGroupOverlays.add(mappableCheckinsOverlay); } // Only add the list of checkin group overlays if it contains any overlays. if (mCheckinGroupOverlays.size() > 0) { mMapView.getOverlays().addAll(mCheckinGroupOverlays); } else { Toast.makeText(this, getResources().getString( R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show(); } } /** * Create an overlay that contains a specific group's list of mappable * checkins. */ private CheckinGroupItemizedOverlay createMappableCheckinsOverlay(Group<Checkin> group) { // We want to group checkins by venue. Do max three checkins per venue, a total // of 100 venues total. We should only also display checkins that are within a // city radius, and are at most three hours old. CheckinTimestampSort timestamps = new CheckinTimestampSort(); Map<String, CheckinGroup> checkinMap = new HashMap<String, CheckinGroup>(); for (int i = 0, m = group.size(); i < m; i++) { Checkin checkin = (Checkin)group.get(i); Venue venue = checkin.getVenue(); if (VenueUtils.hasValidLocation(venue)) { // Make sure the venue is within city radius. try { int distance = Integer.parseInt(checkin.getDistance()); if (distance > FriendsActivity.CITY_RADIUS_IN_METERS) { continue; } } catch (NumberFormatException ex) { // Distance was invalid, ignore this checkin. continue; } // Make sure the checkin happened within the last three hours. try { Date date = new Date(checkin.getCreated()); if (date.before(timestamps.getBoundaryRecent())) { continue; } } catch (Exception ex) { // Timestamps was invalid, ignore this checkin. continue; } String venueId = venue.getId(); CheckinGroup cg = checkinMap.get(venueId); if (cg == null) { cg = new CheckinGroup(); checkinMap.put(venueId, cg); } // Stop appending if we already have three checkins here. if (cg.getCheckinCount() < 3) { cg.appendCheckin(checkin); } } // We can't have too many pins on the map. if (checkinMap.size() > 99) { break; } } Group<CheckinGroup> mappableCheckins = new Group<CheckinGroup>(checkinMap.values()); if (mappableCheckins.size() > 0) { CheckinGroupItemizedOverlay mappableCheckinsGroupOverlay = new CheckinGroupItemizedOverlay( this, ((Foursquared) getApplication()).getRemoteResourceManager(), this.getResources().getDrawable(R.drawable.pin_checkin_multiple), mCheckinGroupOverlayTapListener); mappableCheckinsGroupOverlay.setGroup(mappableCheckins); return mappableCheckinsGroupOverlay; } else { return null; } } private void recenterMap() { // Previously we'd try to zoom to span, but this gives us odd results a lot of times, // so falling back to zoom at a fixed level. GeoPoint center = mMyLocationOverlay.getMyLocation(); if (center != null) { Log.i(TAG, "Using my location overlay as center point for map centering."); mMapController.animateTo(center); mMapController.setZoom(16); } else { // Location overlay wasn't ready yet, try using last known geolocation from manager. Location bestLocation = GeoUtils.getBestLastGeolocation(this); if (bestLocation != null) { Log.i(TAG, "Using last known location for map centering."); mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation)); mMapController.setZoom(16); } else { // We have no location information at all, so we'll just show the map at a high // zoom level and the user can zoom in as they wish. Log.i(TAG, "No location available for map centering."); mMapController.setZoom(8); } } } /** Handle taps on one of the pins. */ private CheckinGroupOverlayTapListener mCheckinGroupOverlayTapListener = new CheckinGroupOverlayTapListener() { @Override public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg) { mTappedVenue = cg.getVenue(); mCallout.setTitle(cg.getVenue().getName()); mCallout.setMessage(cg.getDescription()); mCallout.setVisibility(View.VISIBLE); mMapController.animateTo(new GeoPoint(cg.getLatE6(), cg.getLonE6())); } @Override public void onTap(GeoPoint p, MapView mapView) { mCallout.setVisibility(View.GONE); } }; @Override protected boolean isRouteDisplayed() { return false; } private static class StateHolder { private Group<Checkin> mCheckins; public StateHolder() { mCheckins = new Group<Checkin>(); } public Group<Checkin> getCheckins() { return mCheckins; } public void setCheckins(Group<Checkin> checkins) { mCheckins = checkins; } } }
1031868817-hws
main/src/com/joelapenna/foursquared/FriendsMapActivity.java
Java
asf20
10,764
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnCancelListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; /** * Handles fetching an image from the web, then writes it to a temporary file on * the sdcard so we can hand it off to a view intent. This activity can be * styled with a custom transparent-background theme, so that it appears like a * simple progress dialog to the user over whichever activity launches it, * instead of two seaparate activities before they finally get to the * image-viewing activity. The only required intent extra is the URL to download * the image, the others are optional: * <ul> * <li>IMAGE_URL - String, url of the image to download, either jpeg or png.</li> * <li>CONNECTION_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for * download, in seconds.</li> * <li>READ_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for read of * image, in seconds.</li> * <li>PROGRESS_BAR_TITLE - String, optional, title of the progress bar during * download.</li> * <li>PROGRESS_BAR_MESSAGE - String, optional, message body of the progress bar * during download.</li> * </ul> * * When the download is complete, the activity will return the path of the * saved image on disk. The calling activity can then choose to launch an * intent to view the image. * * @date February 25, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FetchImageForViewIntent extends Activity { private static final String TAG = "FetchImageForViewIntent"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final String TEMP_FILE_NAME = "tmp_fsq"; public static final String IMAGE_URL = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.IMAGE_URL"; public static final String CONNECTION_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.CONNECTION_TIMEOUT_IN_SECONDS"; public static final String READ_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.READ_TIMEOUT_IN_SECONDS"; public static final String PROGRESS_BAR_TITLE = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.PROGRESS_BAR_TITLE"; public static final String PROGRESS_BAR_MESSAGE = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.PROGRESS_BAR_MESSAGE"; public static final String LAUNCH_VIEW_INTENT_ON_COMPLETION = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION"; public static final String EXTRA_SAVED_IMAGE_PATH_RETURNED = Foursquared.PACKAGE_NAME + ".FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED"; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setContentView(R.layout.fetch_image_for_view_intent_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { String url = null; if (getIntent().getExtras().containsKey(IMAGE_URL)) { url = getIntent().getExtras().getString(IMAGE_URL); } else { Log.e(TAG, "FetchImageForViewIntent requires intent extras parameter 'IMAGE_URL'."); finish(); return; } if (DEBUG) Log.d(TAG, "Fetching image: " + url); // Grab the extension of the file that should be present at the end // of the url. We can do a better job of this, and could even check // that the extension is of an expected type. int posdot = url.lastIndexOf("."); if (posdot < 0) { Log.e(TAG, "FetchImageForViewIntent requires a url to an image resource with a file extension in its name."); finish(); return; } String progressBarTitle = getIntent().getStringExtra(PROGRESS_BAR_TITLE); String progressBarMessage = getIntent().getStringExtra(PROGRESS_BAR_MESSAGE); if (progressBarMessage == null) { progressBarMessage = "Fetching image..."; } mStateHolder = new StateHolder(); mStateHolder.setLaunchViewIntentOnCompletion( getIntent().getBooleanExtra(LAUNCH_VIEW_INTENT_ON_COMPLETION, true)); mStateHolder.startTask( FetchImageForViewIntent.this, url, url.substring(posdot), progressBarTitle, progressBarMessage, getIntent().getIntExtra(CONNECTION_TIMEOUT_IN_SECONDS, 20), getIntent().getIntExtra(READ_TIMEOUT_IN_SECONDS, 20)); } } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunning()) { startProgressBar(mStateHolder.getProgressTitle(), mStateHolder.getProgressMessage()); } } @Override public void onPause() { super.onPause(); stopProgressBar(); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); mDlgProgress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dlg) { mStateHolder.cancel(); finish(); } }); mDlgProgress.setCancelable(true); } mDlgProgress.setTitle(title); mDlgProgress.setMessage(message); } private void stopProgressBar() { if (mDlgProgress != null && mDlgProgress.isShowing()) { mDlgProgress.dismiss(); } mDlgProgress = null; } private void onFetchImageTaskComplete(Boolean result, String path, String extension, Exception ex) { try { // If successful, start an intent to view the image. if (result != null && result.equals(Boolean.TRUE)) { // If the image can't be loaded or an intent can't be found to // view it, launchViewIntent() will create a toast with an error // message. if (mStateHolder.getLaunchViewIntentOnCompletion()) { launchViewIntent(path, extension); } else { // We'll finish now by handing the save image path back to the // calling activity. Intent intent = new Intent(); intent.putExtra(EXTRA_SAVED_IMAGE_PATH_RETURNED, path); setResult(Activity.RESULT_OK, intent); } } else { NotificationsUtil.ToastReasonForFailure(FetchImageForViewIntent.this, ex); } } finally { // Whether download worked or not, we finish ourselves now. If an // error occurred, the toast should remain on the calling activity. mStateHolder.setIsRunning(false); stopProgressBar(); finish(); } } private boolean launchViewIntent(String outputPath, String extension) { Foursquared foursquared = (Foursquared) getApplication(); if (foursquared.getUseNativeImageViewerForFullScreenImages()) { // Try to open the file now to create the uri we'll hand to the intent. Uri uri = null; try { File file = new File(outputPath); uri = Uri.fromFile(file); } catch (Exception ex) { Log.e(TAG, "Error opening downloaded image from temp location: ", ex); Toast.makeText(this, "No application could be found to diplay the full image.", Toast.LENGTH_SHORT); return false; } // Try to start an intent to view the image. It's possible that the user // may not have any intents to handle the request. try { Intent intent = new Intent(android.content.Intent.ACTION_VIEW); intent.setDataAndType(uri, "image/" + extension); startActivity(intent); } catch (Exception ex) { Log.e(TAG, "Error starting intent to view image: ", ex); Toast.makeText(this, "There was an error displaying the image.", Toast.LENGTH_SHORT); return false; } } else { Intent intent = new Intent(this, FullSizeImageActivity.class); intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, outputPath); startActivity(intent); } return true; } /** * Handles fetching the image from the net and saving it to disk in a task. */ private static class FetchImageTask extends AsyncTask<Void, Void, Boolean> { private FetchImageForViewIntent mActivity; private final String mUrl; private String mExtension; private final String mOutputPath; private final int mConnectionTimeoutInSeconds; private final int mReadTimeoutInSeconds; private Exception mReason; public FetchImageTask(FetchImageForViewIntent activity, String url, String extension, int connectionTimeoutInSeconds, int readTimeoutInSeconds) { mActivity = activity; mUrl = url; mExtension = extension; mOutputPath = Environment.getExternalStorageDirectory() + "/" + TEMP_FILE_NAME; mConnectionTimeoutInSeconds = connectionTimeoutInSeconds; mReadTimeoutInSeconds = readTimeoutInSeconds; } public void setActivity(FetchImageForViewIntent activity) { mActivity = activity; } @Override protected Boolean doInBackground(Void... params) { try { saveImage(mUrl, mOutputPath, mConnectionTimeoutInSeconds, mReadTimeoutInSeconds); return Boolean.TRUE; } catch (Exception e) { if (DEBUG) Log.d(TAG, "FetchImageTask: Exception while fetching image.", e); mReason = e; } return Boolean.FALSE; } @Override protected void onPostExecute(Boolean result) { if (DEBUG) Log.d(TAG, "FetchImageTask: onPostExecute()"); if (mActivity != null) { mActivity.onFetchImageTaskComplete(result, mOutputPath, mExtension, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFetchImageTaskComplete(null, null, null, new FoursquareException("Image download cancelled.")); } } } public static void saveImage(String urlImage, String savePath, int connectionTimeoutInSeconds, int readTimeoutInSeconds) throws Exception { URL url = new URL(urlImage); URLConnection conn = url.openConnection(); conn.setConnectTimeout(connectionTimeoutInSeconds * 1000); conn.setReadTimeout(readTimeoutInSeconds * 1000); int contentLength = conn.getContentLength(); InputStream raw = conn.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; int offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) { break; } offset += bytesRead; } in.close(); if (offset != contentLength) { Log.e(TAG, "Error fetching image, only read " + offset + " bytes of " + contentLength + " total."); throw new FoursquareException("Error fetching full image, please try again."); } // This will fail if the user has no sdcard present, catch it specifically // to alert user. try { FileOutputStream out = new FileOutputStream(savePath); out.write(data); out.flush(); out.close(); } catch (Exception ex) { Log.e(TAG, "Error saving fetched image to disk.", ex); throw new FoursquareException("Error opening fetched image, make sure an sdcard is present."); } } /** Maintains state between rotations. */ private static class StateHolder { FetchImageTask mTaskFetchImage; boolean mIsRunning; String mProgressTitle; String mProgressMessage; boolean mLaunchViewIntentOnCompletion; public StateHolder() { mIsRunning = false; mLaunchViewIntentOnCompletion = true; } public void startTask(FetchImageForViewIntent activity, String url, String extension, String progressBarTitle, String progressBarMessage, int connectionTimeoutInSeconds, int readTimeoutInSeconds) { mIsRunning = true; mProgressTitle = progressBarTitle; mProgressMessage = progressBarMessage; mTaskFetchImage = new FetchImageTask(activity, url, extension, connectionTimeoutInSeconds, readTimeoutInSeconds); mTaskFetchImage.execute(); } public void setActivity(FetchImageForViewIntent activity) { if (mTaskFetchImage != null) { mTaskFetchImage.setActivity(activity); } } public void setIsRunning(boolean isRunning) { mIsRunning = isRunning; } public boolean getIsRunning() { return mIsRunning; } public String getProgressTitle() { return mProgressTitle; } public String getProgressMessage() { return mProgressMessage; } public void cancel() { if (mTaskFetchImage != null) { mTaskFetchImage.cancel(true); mIsRunning = false; } } public boolean getLaunchViewIntentOnCompletion() { return mLaunchViewIntentOnCompletion; } public void setLaunchViewIntentOnCompletion(boolean launchViewIntentOnCompletion) { mLaunchViewIntentOnCompletion = launchViewIntentOnCompletion; } } }
1031868817-hws
main/src/com/joelapenna/foursquared/FetchImageForViewIntent.java
Java
asf20
16,224
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.maps.VenueItemizedOverlayWithIcons; import com.joelapenna.foursquared.maps.VenueItemizedOverlayWithIcons.VenueItemizedOverlayTapListener; import com.joelapenna.foursquared.util.GeoUtils; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.MapCalloutView; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; import java.util.ArrayList; /** * Takes an array of venues and shows them on a map. * * @date June 30, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class NearbyVenuesMapActivity extends MapActivity { public static final String TAG = "NearbyVenuesMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUES = Foursquared.PACKAGE_NAME + ".NearbyVenuesMapActivity.INTENT_EXTRA_VENUES"; private StateHolder mStateHolder; private String mTappedVenueId; private MapCalloutView mCallout; private MapView mMapView; private MapController mMapController; private ArrayList<VenueItemizedOverlayWithIcons> mVenueGroupOverlays = new ArrayList<VenueItemizedOverlayWithIcons>(); private MyLocationOverlay mMyLocationOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_map_activity); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { if (getIntent().hasExtra(INTENT_EXTRA_VENUES)) { Parcelable[] parcelables = getIntent().getParcelableArrayExtra( INTENT_EXTRA_VENUES); Group<Venue> venues = new Group<Venue>(); for (int i = 0; i < parcelables.length; i++) { venues.add((Venue)parcelables[i]); } mStateHolder = new StateHolder(venues); } else { Log.e(TAG, TAG + " requires venue array in intent extras."); finish(); return; } } ensureUi(); } private void ensureUi() { mMapView = (MapView) findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); mCallout = (MapCalloutView) findViewById(R.id.map_callout); mCallout.setVisibility(View.GONE); mCallout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(NearbyVenuesMapActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, mTappedVenueId); startActivity(intent); } }); // One CheckinItemizedOverlay per group! VenueItemizedOverlayWithIcons mappableVenuesOverlay = createMappableVenuesOverlay( mStateHolder.getVenues()); if (mappableVenuesOverlay != null) { mVenueGroupOverlays.add(mappableVenuesOverlay); } if (mVenueGroupOverlays.size() > 0) { mMapView.getOverlays().addAll(mVenueGroupOverlays); recenterMap(); } else { Toast.makeText(this, getResources().getString( R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show(); finish(); } } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.enableCompass(); } } @Override public void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.disableCompass(); } } @Override protected boolean isRouteDisplayed() { return false; } /** * We can do something more fun here like create an overlay per category, so the user * can hide parks and show only bars, for example. */ private VenueItemizedOverlayWithIcons createMappableVenuesOverlay(Group<Venue> venues) { Group<Venue> mappableVenues = new Group<Venue>(); for (Venue it : venues) { mappableVenues.add(it); } if (mappableVenues.size() > 0) { VenueItemizedOverlayWithIcons overlay = new VenueItemizedOverlayWithIcons( this, ((Foursquared) getApplication()).getRemoteResourceManager(), getResources().getDrawable(R.drawable.pin_checkin_multiple), mVenueOverlayTapListener); overlay.setGroup(mappableVenues); return overlay; } else { return null; } } private void recenterMap() { // Previously we'd try to zoom to span, but this gives us odd results a lot of times, // so falling back to zoom at a fixed level. GeoPoint center = mMyLocationOverlay.getMyLocation(); if (center != null) { mMapController.animateTo(center); mMapController.setZoom(14); } else { // Location overlay wasn't ready yet, try using last known geolocation from manager. Location bestLocation = GeoUtils.getBestLastGeolocation(this); if (bestLocation != null) { mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation)); mMapController.setZoom(14); } else { // We have no location information at all, so we'll just show the map at a high // zoom level and the user can zoom in as they wish. Venue venue = mStateHolder.getVenues().get(0); mMapController.animateTo(new GeoPoint( (int)(Float.valueOf(venue.getGeolat()) * 1E6), (int)(Float.valueOf(venue.getGeolong()) * 1E6))); mMapController.setZoom(8); } } } /** * Handle taps on one of the pins. */ private VenueItemizedOverlayTapListener mVenueOverlayTapListener = new VenueItemizedOverlayTapListener() { @Override public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, Venue venue) { mTappedVenueId = venue.getId(); mCallout.setTitle(venue.getName()); mCallout.setMessage(venue.getAddress()); mCallout.setVisibility(View.VISIBLE); mMapController.animateTo(GeoUtils.stringLocationToGeoPoint( venue.getGeolat(), venue.getGeolong())); } @Override public void onTap(GeoPoint p, MapView mapView) { mCallout.setVisibility(View.GONE); } }; private class StateHolder { private Group<Venue> mVenues; public StateHolder(Group<Venue> venues) { mVenues = venues; } public Group<Venue> getVenues() { return mVenues; } } }
1031868817-hws
main/src/com/joelapenna/foursquared/NearbyVenuesMapActivity.java
Java
asf20
8,273
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.List; /** * Allows the user to add a new venue. This activity can also be used to submit * edits to an existing venue. Pass a venue parcelable using the EXTRA_VENUE_TO_EDIT * key to put the activity into edit mode. * * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added support for using this activity to edit existing venues (June 8, 2010). */ public class AddVenueActivity extends Activity { private static final String TAG = "AddVenueActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_VENUE_TO_EDIT = "com.joelapenna.foursquared.VenueParcel"; private static final double MINIMUM_ACCURACY_FOR_ADDRESS = 100.0; private static final int DIALOG_PICK_CATEGORY = 1; private static final int DIALOG_ERROR = 2; private StateHolder mStateHolder; private EditText mNameEditText; private EditText mAddressEditText; private EditText mCrossstreetEditText; private EditText mCityEditText; private EditText mStateEditText; private EditText mZipEditText; private EditText mPhoneEditText; private Button mAddOrEditVenueButton; private LinearLayout mCategoryLayout; private ImageView mCategoryImageView; private TextView mCategoryTextView; private ProgressBar mCategoryProgressBar; private ProgressDialog mDlgProgress; private TextWatcher mNameFieldWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mAddOrEditVenueButton.setEnabled(canEnableSaveButton()); } }; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.add_venue_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mAddOrEditVenueButton = (Button) findViewById(R.id.addVenueButton); mNameEditText = (EditText) findViewById(R.id.nameEditText); mAddressEditText = (EditText) findViewById(R.id.addressEditText); mCrossstreetEditText = (EditText) findViewById(R.id.crossstreetEditText); mCityEditText = (EditText) findViewById(R.id.cityEditText); mStateEditText = (EditText) findViewById(R.id.stateEditText); mZipEditText = (EditText) findViewById(R.id.zipEditText); mPhoneEditText = (EditText) findViewById(R.id.phoneEditText); mCategoryLayout = (LinearLayout) findViewById(R.id.addVenueCategoryLayout); mCategoryImageView = (ImageView) findViewById(R.id.addVenueCategoryIcon); mCategoryTextView = (TextView) findViewById(R.id.addVenueCategoryTextView); mCategoryProgressBar = (ProgressBar) findViewById(R.id.addVenueCategoryProgressBar); mCategoryLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { showDialog(DIALOG_PICK_CATEGORY); } }); mCategoryLayout.setEnabled(false); mAddOrEditVenueButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String name = mNameEditText.getText().toString(); String address = mAddressEditText.getText().toString(); String crossstreet = mCrossstreetEditText.getText().toString(); String city = mCityEditText.getText().toString(); String state = mStateEditText.getText().toString(); String zip = mZipEditText.getText().toString(); String phone = mPhoneEditText.getText().toString(); if (mStateHolder.getVenueBeingEdited() != null) { if (TextUtils.isEmpty(name)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_name)); return; } else if (TextUtils.isEmpty(address)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_address)); return; } else if (TextUtils.isEmpty(city)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_city)); return; } else if (TextUtils.isEmpty(state)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_state)); return; } } mStateHolder.startTaskAddOrEditVenue( AddVenueActivity.this, new String[] { name, address, crossstreet, city, state, zip, phone, mStateHolder.getChosenCategory() != null ? mStateHolder.getChosenCategory().getId() : "" }, // If editing a venue, pass in its id. mStateHolder.getVenueBeingEdited() != null ? mStateHolder.getVenueBeingEdited().getId() : null); } }); mNameEditText.addTextChangedListener(mNameFieldWatcher); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); setFields(mStateHolder.getAddressLookup()); setChosenCategory(mStateHolder.getChosenCategory()); if (mStateHolder.getCategories() != null && mStateHolder.getCategories().size() > 0) { mCategoryLayout.setEnabled(true); mCategoryProgressBar.setVisibility(View.GONE); } } else { mStateHolder = new StateHolder(); mStateHolder.startTaskGetCategories(this); // If passed the venue parcelable, then we are in 'edit' mode. if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_VENUE_TO_EDIT)) { Venue venue = getIntent().getExtras().getParcelable(EXTRA_VENUE_TO_EDIT); if (venue != null) { mStateHolder.setVenueBeingEdited(venue); setFields(venue); setTitle(getResources().getString(R.string.add_venue_activity_label_edit_venue)); mAddOrEditVenueButton.setText(getResources().getString( R.string.add_venue_activity_btn_submit_edits)); } else { Log.e(TAG, "Null venue parcelable supplied at startup, will finish immediately."); finish(); } } else { mStateHolder.startTaskAddressLookup(this); } } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(true); if (mStateHolder.getIsRunningTaskAddOrEditVenue()) { startProgressBar(); } } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(); stopProgressBar(); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void showDialogError(String message) { mStateHolder.setError(message); showDialog(DIALOG_ERROR); } /** * Set fields from an address lookup, only used when adding a venue. This is done * to prepopulate some fields for the user. */ private void setFields(AddressLookup addressLookup) { if (mStateHolder.getVenueBeingEdited() == null && addressLookup != null && addressLookup.getAddress() != null) { // Don't fill in the street unless we're reasonably confident we // know where the user is. String address = addressLookup.getAddress().getAddressLine(0); double accuracy = addressLookup.getLocation().getAccuracy(); if (address != null && (accuracy > 0.0 && accuracy < MINIMUM_ACCURACY_FOR_ADDRESS)) { if (DEBUG) Log.d(TAG, "Accuracy good enough, setting address field."); mAddressEditText.setText(address); } String city = addressLookup.getAddress().getLocality(); if (city != null) { mCityEditText.setText(city); } String state = addressLookup.getAddress().getAdminArea(); if (state != null) { mStateEditText.setText(state); } String zip = addressLookup.getAddress().getPostalCode(); if (zip != null) { mZipEditText.setText(zip); } String phone = addressLookup.getAddress().getPhone(); if (phone != null) { mPhoneEditText.setText(phone); } } } /** * Set fields from an existing venue, this is only used when editing a venue. */ private void setFields(Venue venue) { mNameEditText.setText(venue.getName()); mCrossstreetEditText.setText(venue.getCrossstreet()); mAddressEditText.setText(venue.getAddress()); mCityEditText.setText(venue.getCity()); mStateEditText.setText(venue.getState()); mZipEditText.setText(venue.getZip()); mPhoneEditText.setText(venue.getPhone()); } private void startProgressBar() { startProgressBar( getResources().getString( mStateHolder.getVenueBeingEdited() == null ? R.string.add_venue_progress_bar_message_add_venue : R.string.add_venue_progress_bar_message_edit_venue)); } private void startProgressBar(String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, null, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void onGetCategoriesTaskComplete(Group<Category> categories, Exception ex) { mStateHolder.setIsRunningTaskGetCategories(false); try { // Populate the categories list now. if (categories != null) { mStateHolder.setCategories(categories); mCategoryLayout.setEnabled(true); mCategoryTextView.setText(getResources().getString(R.string.add_venue_activity_pick_category_label)); mCategoryProgressBar.setVisibility(View.GONE); // If we are editing a venue, set its category here. if (mStateHolder.getVenueBeingEdited() != null) { Venue venue = mStateHolder.getVenueBeingEdited(); if (venue.getCategory() != null) { setChosenCategory(venue.getCategory()); } } } else { // If error, feed list adapter empty user group. mStateHolder.setCategories(new Group<Category>()); NotificationsUtil.ToastReasonForFailure(this, ex); } } finally { } stopIndeterminateProgressBar(); } private void ooGetAddressLookupTaskComplete(AddressLookup addressLookup, Exception ex) { mStateHolder.setIsRunningTaskAddressLookup(false); stopIndeterminateProgressBar(); if (addressLookup != null) { mStateHolder.setAddressLookup(addressLookup); setFields(addressLookup); } else { // Nothing to do on failure, don't need to report. } } private void onAddOrEditVenueTaskComplete(Venue venue, String venueIdIfEditing, Exception ex) { mStateHolder.setIsRunningTaskAddOrEditVenue(false); stopProgressBar(); if (venueIdIfEditing == null) { if (venue != null) { // If they added the venue ok, then send them to an activity displaying it // so they can play around with it. Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); finish(); } else { // Error, let them hang out here. NotificationsUtil.ToastReasonForFailure(this, ex); } } else { if (venue != null) { // Editing the venue worked ok, just return to caller. Toast.makeText(this, getResources().getString( R.string.add_venue_activity_edit_venue_success), Toast.LENGTH_SHORT).show(); finish(); } else { // Error, let them hang out here. NotificationsUtil.ToastReasonForFailure(this, ex); } } } private void stopIndeterminateProgressBar() { if (mStateHolder.getIsRunningTaskAddressLookup() == false && mStateHolder.getIsRunningTaskGetCategories() == false) { setProgressBarIndeterminateVisibility(false); } } private static class AddOrEditVenueTask extends AsyncTask<Void, Void, Venue> { private AddVenueActivity mActivity; private String[] mParams; private String mVenueIdIfEditing; private Exception mReason; private Foursquared mFoursquared; private String mErrorMsgForEditVenue; public AddOrEditVenueTask(AddVenueActivity activity, String[] params, String venueIdIfEditing) { mActivity = activity; mParams = params; mVenueIdIfEditing = venueIdIfEditing; mFoursquared = (Foursquared) activity.getApplication(); mErrorMsgForEditVenue = activity.getResources().getString( R.string.add_venue_activity_edit_venue_fail); } public void setActivity(AddVenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(); } @Override protected Venue doInBackground(Void... params) { try { Foursquare foursquare = mFoursquared.getFoursquare(); Location location = mFoursquared.getLastKnownLocationOrThrow(); if (mVenueIdIfEditing == null) { return foursquare.addVenue( mParams[0], // name mParams[1], // address mParams[2], // cross street mParams[3], // city mParams[4], // state, mParams[5], // zip mParams[6], // phone mParams[7], // category id LocationUtils.createFoursquareLocation(location)); } else { Response response = foursquare.proposeedit( mVenueIdIfEditing, mParams[0], // name mParams[1], // address mParams[2], // cross street mParams[3], // city mParams[4], // state, mParams[5], // zip mParams[6], // phone mParams[7], // category id LocationUtils.createFoursquareLocation(location)); if (response != null && response.getValue().equals("ok")) { // TODO: Come up with a better method than returning an empty venue on success. return new Venue(); } else { throw new Exception(mErrorMsgForEditVenue); } } } catch (Exception e) { Log.e(TAG, "Exception during add or edit venue.", e); mReason = e; } return null; } @Override protected void onPostExecute(Venue venue) { if (DEBUG) Log.d(TAG, "onPostExecute()"); if (mActivity != null) { mActivity.onAddOrEditVenueTaskComplete(venue, mVenueIdIfEditing, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onAddOrEditVenueTaskComplete(null, mVenueIdIfEditing, mReason); } } } private static class AddressLookupTask extends AsyncTask<Void, Void, AddressLookup> { private AddVenueActivity mActivity; private Exception mReason; public AddressLookupTask(AddVenueActivity activity) { mActivity = activity; } public void setActivity(AddVenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setProgressBarIndeterminateVisibility(true); } @Override protected AddressLookup doInBackground(Void... params) { try { Location location = ((Foursquared)mActivity.getApplication()).getLastKnownLocationOrThrow(); Geocoder geocoder = new Geocoder(mActivity); List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); if (addresses != null && addresses.size() > 0) { Log.i(TAG, "Address found: " + addresses.toString()); return new AddressLookup(location, addresses.get(0)); } else { Log.i(TAG, "No address could be found for current location."); throw new FoursquareException("No address could be found for the current geolocation."); } } catch (Exception ex) { Log.e(TAG, "Error during address lookup.", ex); mReason = ex; } return null; } @Override protected void onPostExecute(AddressLookup address) { if (mActivity != null) { mActivity.ooGetAddressLookupTaskComplete(address, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.ooGetAddressLookupTaskComplete(null, mReason); } } } private static class GetCategoriesTask extends AsyncTask<Void, Void, Group<Category>> { private AddVenueActivity mActivity; private Exception mReason; public GetCategoriesTask(AddVenueActivity activity) { mActivity = activity; } public void setActivity(AddVenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setProgressBarIndeterminateVisibility(true); } @Override protected Group<Category> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.categories(); } catch (Exception e) { if (DEBUG) Log.d(TAG, "GetCategoriesTask: Exception doing send friend request.", e); mReason = e; } return null; } @Override protected void onPostExecute(Group<Category> categories) { if (DEBUG) Log.d(TAG, "GetCategoriesTask: onPostExecute()"); if (mActivity != null) { mActivity.onGetCategoriesTaskComplete(categories, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onGetCategoriesTaskComplete(null, new Exception("Get categories task request cancelled.")); } } } private static class StateHolder { private AddressLookupTask mTaskGetAddress; private AddressLookup mAddressLookup; private boolean mIsRunningTaskAddressLookup; private GetCategoriesTask mTaskGetCategories; private Group<Category> mCategories; private boolean mIsRunningTaskGetCategories; private AddOrEditVenueTask mTaskAddOrEditVenue; private boolean mIsRunningTaskAddOrEditVenue; private Category mChosenCategory; private Venue mVenueBeingEdited; private String mError; public StateHolder() { mCategories = new Group<Category>(); mIsRunningTaskAddressLookup = false; mIsRunningTaskGetCategories = false; mIsRunningTaskAddOrEditVenue = false; mVenueBeingEdited = null; } public void setCategories(Group<Category> categories) { mCategories = categories; } public void setAddressLookup(AddressLookup addressLookup) { mAddressLookup = addressLookup; } public Group<Category> getCategories() { return mCategories; } public AddressLookup getAddressLookup() { return mAddressLookup; } public Venue getVenueBeingEdited() { return mVenueBeingEdited; } public void setVenueBeingEdited(Venue venue) { mVenueBeingEdited = venue; } public void startTaskGetCategories(AddVenueActivity activity) { mIsRunningTaskGetCategories = true; mTaskGetCategories = new GetCategoriesTask(activity); mTaskGetCategories.execute(); } public void startTaskAddressLookup(AddVenueActivity activity) { mIsRunningTaskAddressLookup = true; mTaskGetAddress = new AddressLookupTask(activity); mTaskGetAddress.execute(); } public void startTaskAddOrEditVenue(AddVenueActivity activity, String[] params, String venueIdIfEditing) { mIsRunningTaskAddOrEditVenue = true; mTaskAddOrEditVenue = new AddOrEditVenueTask(activity, params, venueIdIfEditing); mTaskAddOrEditVenue.execute(); } public void setActivity(AddVenueActivity activity) { if (mTaskGetCategories != null) { mTaskGetCategories.setActivity(activity); } if (mTaskGetAddress != null) { mTaskGetAddress.setActivity(activity); } if (mTaskAddOrEditVenue != null) { mTaskAddOrEditVenue.setActivity(activity); } } public void setIsRunningTaskAddressLookup(boolean isRunning) { mIsRunningTaskAddressLookup = isRunning; } public void setIsRunningTaskGetCategories(boolean isRunning) { mIsRunningTaskGetCategories = isRunning; } public void setIsRunningTaskAddOrEditVenue(boolean isRunning) { mIsRunningTaskAddOrEditVenue = isRunning; } public boolean getIsRunningTaskAddressLookup() { return mIsRunningTaskAddressLookup; } public boolean getIsRunningTaskGetCategories() { return mIsRunningTaskGetCategories; } public boolean getIsRunningTaskAddOrEditVenue() { return mIsRunningTaskAddOrEditVenue; } public Category getChosenCategory() { return mChosenCategory; } public void setChosenCategory(Category category) { mChosenCategory = category; } public String getError() { return mError; } public void setError(String error) { mError = error; } } private static class AddressLookup { private Location mLocation; private Address mAddress; public AddressLookup(Location location, Address address) { mLocation = location; mAddress = address; } public Location getLocation() { return mLocation; } public Address getAddress() { return mAddress; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PICK_CATEGORY: // When the user cancels the dialog (by hitting the 'back' key), we // finish this activity. We don't listen to onDismiss() for this // action, because a device rotation will fire onDismiss(), and our // dialog would not be re-displayed after the rotation is complete. CategoryPickerDialog dlg = new CategoryPickerDialog( this, mStateHolder.getCategories(), ((Foursquared)getApplication())); dlg.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CategoryPickerDialog dlg = (CategoryPickerDialog)dialog; setChosenCategory(dlg.getChosenCategory()); removeDialog(DIALOG_PICK_CATEGORY); } }); return dlg; case DIALOG_ERROR: AlertDialog dlgInfo = new AlertDialog.Builder(this) .setIcon(0) .setTitle(getResources().getString(R.string.add_venue_progress_bar_title_edit_venue)) .setMessage(mStateHolder.getError()).create(); dlgInfo.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(DIALOG_ERROR); } }); return dlgInfo; } return null; } private void setChosenCategory(Category category) { if (category == null) { mCategoryTextView.setText(getResources().getString( R.string.add_venue_activity_pick_category_label)); return; } try { Bitmap bitmap = BitmapFactory.decodeStream( ((Foursquared)getApplication()).getRemoteResourceManager().getInputStream( Uri.parse(category.getIconUrl()))); mCategoryImageView.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.e(TAG, "Error loading category icon.", e); } mCategoryTextView.setText(category.getNodeName()); // Record the chosen category. mStateHolder.setChosenCategory(category); if (canEnableSaveButton()) { mAddOrEditVenueButton.setEnabled(canEnableSaveButton()); } } private boolean canEnableSaveButton() { return mNameEditText.getText().length() > 0; } }
1031868817-hws
main/src/com/joelapenna/foursquared/AddVenueActivity.java
Java
asf20
30,780
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.TipUtils; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import com.joelapenna.foursquared.widget.TodosListAdapter; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import java.util.Observable; import java.util.Observer; /** * Shows a list of a user's todos. We can operate on the logged-in user, * or a friend user, specified through the intent extras. * * If operating on the logged-in user, we remove items from the todo list * if they mark a todo as done or un-mark it. If operating on another user, * we do not remove them from the list. * * @date September 12, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TodosActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "TodosActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_USER_ID = Foursquared.PACKAGE_NAME + ".TodosActivity.INTENT_EXTRA_USER_ID"; public static final String INTENT_EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".TodosActivity.INTENT_EXTRA_USER_NAME"; private static final int ACTIVITY_TIP = 500; private StateHolder mStateHolder; private TodosListAdapter mListAdapter; private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private View mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { // Optional user id and username, if not present, will be null and default to // logged-in user. mStateHolder = new StateHolder( getIntent().getStringExtra(INTENT_EXTRA_USER_ID), getIntent().getStringExtra(INTENT_EXTRA_USER_NAME)); mStateHolder.setRecentOnly(false); } ensureUi(); // Nearby todos is shown first by default so auto-fetch it if necessary. // Nearby is the right button, not the left one, which is a bit strange // but this was a design req. if (!mStateHolder.getRanOnceTodosNearby()) { mStateHolder.startTaskTodos(this, false); } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); setTitle(getString(R.string.todos_activity_title, mStateHolder.getUsername())); mLayoutEmpty = inflater.inflate( R.layout.todos_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new TodosListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); if (mStateHolder.getRecentOnly()) { mListAdapter.setGroup(mStateHolder.getTodosRecent()); if (mStateHolder.getTodosRecent().size() == 0) { if (mStateHolder.getRanOnceTodosRecent()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } else { mListAdapter.setGroup(mStateHolder.getTodosNearby()); if (mStateHolder.getTodosNearby().size() == 0) { if (mStateHolder.getRanOnceTodosNearby()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.todos_activity_btn_recent), getString(R.string.todos_activity_btn_nearby)); if (mStateHolder.getRecentOnly()) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setRecentOnly(true); mListAdapter.setGroup(mStateHolder.getTodosRecent()); if (mStateHolder.getTodosRecent().size() < 1) { if (mStateHolder.getRanOnceTodosRecent()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskTodos(TodosActivity.this, true); } } } else { mStateHolder.setRecentOnly(false); mListAdapter.setGroup(mStateHolder.getTodosNearby()); if (mStateHolder.getTodosNearby().size() < 1) { if (mStateHolder.getRanOnceTodosNearby()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskTodos(TodosActivity.this, false); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Todo todo = (Todo) parent.getAdapter().getItem(position); if (todo.getTip() != null) { Intent intent = new Intent(TodosActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip()); startActivityForResult(intent, ACTIVITY_TIP); } } }); if (mStateHolder.getIsRunningTaskTodosRecent() || mStateHolder.getIsRunningTaskTodosNearby()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); MenuUtils.addPreferencesToMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTaskTodos(this, mStateHolder.getRecentOnly()); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // We ignore the returned to-do (if any). We search for any to-dos in our // state holder by the linked tip ID for update. if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) { if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) { updateTodo((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED)); } } } private void updateTodo(Tip tip) { mStateHolder.updateTodo(tip); mListAdapter.notifyDataSetInvalidated(); } private void onStartTaskTodos() { if (mListAdapter != null) { if (mStateHolder.getRecentOnly()) { mStateHolder.setIsRunningTaskTodosRecent(true); mListAdapter.setGroup(mStateHolder.getTodosRecent()); } else { mStateHolder.setIsRunningTaskTodosNearby(true); mListAdapter.setGroup(mStateHolder.getTodosNearby()); } mListAdapter.notifyDataSetChanged(); } setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskTodosComplete(Group<Todo> group, boolean recentOnly, Exception ex) { SegmentedButton buttons = getHeaderButton(); boolean update = false; if (group != null) { if (recentOnly) { mStateHolder.setTodosRecent(group); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getTodosRecent()); update = true; } } else { mStateHolder.setTodosNearby(group); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getTodosNearby()); update = true; } } } else { if (recentOnly) { mStateHolder.setTodosRecent(new Group<Todo>()); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getTodosRecent()); update = true; } } else { mStateHolder.setTodosNearby(new Group<Todo>()); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getTodosNearby()); update = true; } } NotificationsUtil.ToastReasonForFailure(this, ex); } if (recentOnly) { mStateHolder.setIsRunningTaskTodosRecent(false); mStateHolder.setRanOnceTodosRecent(true); if (mStateHolder.getTodosRecent().size() == 0 && buttons.getSelectedButtonIndex() == 0) { setEmptyView(mLayoutEmpty); } } else { mStateHolder.setIsRunningTaskTodosNearby(false); mStateHolder.setRanOnceTodosNearby(true); if (mStateHolder.getTodosNearby().size() == 0 && buttons.getSelectedButtonIndex() == 1) { setEmptyView(mLayoutEmpty); } } if (update) { mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } if (!mStateHolder.getIsRunningTaskTodosRecent() && !mStateHolder.getIsRunningTaskTodosNearby()) { setProgressBarIndeterminateVisibility(false); } } /** * Gets friends of the current user we're working for. */ private static class TaskTodos extends AsyncTask<Void, Void, Group<Todo>> { private String mUserId; private TodosActivity mActivity; private boolean mRecentOnly; private Exception mReason; public TaskTodos(TodosActivity activity, String userId, boolean friendsOnly) { mActivity = activity; mUserId = userId; mRecentOnly = friendsOnly; } @Override protected void onPreExecute() { mActivity.onStartTaskTodos(); } @Override protected Group<Todo> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location loc = foursquared.getLastKnownLocation(); if (loc == null) { try { Thread.sleep(3000); } catch (InterruptedException ex) {} loc = foursquared.getLastKnownLocation(); if (loc == null) { throw new FoursquareException("Your location could not be determined!"); } } return foursquare.todos( LocationUtils.createFoursquareLocation(loc), mUserId, mRecentOnly, !mRecentOnly, 30); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<Todo> todos) { if (mActivity != null) { mActivity.onTaskTodosComplete(todos, mRecentOnly, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskTodosComplete(null, mRecentOnly, mReason); } } public void setActivity(TodosActivity activity) { mActivity = activity; } } private static class StateHolder { private Group<Todo> mTodosRecent; private Group<Todo> mTodosNearby; private boolean mIsRunningTaskTodosRecent; private boolean mIsRunningTaskTodosNearby; private boolean mRecentOnly; private boolean mRanOnceTodosRecent; private boolean mRanOnceTodosNearby; private TaskTodos mTaskTodosRecent; private TaskTodos mTaskTodosNearby; private String mUserId; private String mUsername; public StateHolder(String userId, String username) { mIsRunningTaskTodosRecent = false; mIsRunningTaskTodosNearby = false; mRanOnceTodosRecent = false; mRanOnceTodosNearby = false; mTodosRecent = new Group<Todo>(); mTodosNearby = new Group<Todo>(); mRecentOnly = false; mUserId = userId; mUsername = username; } public String getUsername() { return mUsername; } public Group<Todo> getTodosRecent() { return mTodosRecent; } public void setTodosRecent(Group<Todo> todosRecent) { mTodosRecent = todosRecent; } public Group<Todo> getTodosNearby() { return mTodosNearby; } public void setTodosNearby(Group<Todo> todosNearby) { mTodosNearby = todosNearby; } public void startTaskTodos(TodosActivity activity, boolean recentOnly) { if (recentOnly) { if (mIsRunningTaskTodosRecent) { return; } mIsRunningTaskTodosRecent = true; mTaskTodosRecent = new TaskTodos(activity, mUserId, recentOnly); mTaskTodosRecent.execute(); } else { if (mIsRunningTaskTodosNearby) { return; } mIsRunningTaskTodosNearby = true; mTaskTodosNearby = new TaskTodos(activity, mUserId, recentOnly); mTaskTodosNearby.execute(); } } public void setActivity(TodosActivity activity) { if (mTaskTodosRecent != null) { mTaskTodosRecent.setActivity(activity); } if (mTaskTodosNearby != null) { mTaskTodosNearby.setActivity(activity); } } public boolean getIsRunningTaskTodosRecent() { return mIsRunningTaskTodosRecent; } public void setIsRunningTaskTodosRecent(boolean isRunning) { mIsRunningTaskTodosRecent = isRunning; } public boolean getIsRunningTaskTodosNearby() { return mIsRunningTaskTodosNearby; } public void setIsRunningTaskTodosNearby(boolean isRunning) { mIsRunningTaskTodosNearby = isRunning; } public void cancelTasks() { if (mTaskTodosRecent != null) { mTaskTodosRecent.setActivity(null); mTaskTodosRecent.cancel(true); } if (mTaskTodosNearby != null) { mTaskTodosNearby.setActivity(null); mTaskTodosNearby.cancel(true); } } public boolean getRecentOnly() { return mRecentOnly; } public void setRecentOnly(boolean recentOnly) { mRecentOnly = recentOnly; } public boolean getRanOnceTodosRecent() { return mRanOnceTodosRecent; } public void setRanOnceTodosRecent(boolean ranOnce) { mRanOnceTodosRecent = ranOnce; } public boolean getRanOnceTodosNearby() { return mRanOnceTodosNearby; } public void setRanOnceTodosNearby(boolean ranOnce) { mRanOnceTodosNearby = ranOnce; } public void updateTodo(Tip tip) { updateTodoFromArray(tip, mTodosRecent); updateTodoFromArray(tip, mTodosNearby); } private void updateTodoFromArray(Tip tip, Group<Todo> target) { for (int i = 0, m = target.size(); i < m; i++) { Todo todo = target.get(i); if (todo.getTip() != null) { // Fix for old garbage todos/tips from the API. if (todo.getTip().getId().equals(tip.getId())) { if (mUserId == null) { // Activity is operating on logged-in user, only removing todos // from the list, don't have to worry about updating states. if (!TipUtils.isTodo(tip)) { target.remove(todo); } } else { // Activity is operating on another user, so just update the status // of the tip within the todo. todo.getTip().setStatus(tip.getStatus()); } break; } } } } } /** * This is really just a dummy observer to get the GPS running * since this is the new splash page. After getting a fix, we * might want to stop registering this observer thereafter so * it doesn't annoy the user too much. */ private class SearchLocationObserver implements Observer { @Override public void update(Observable observable, Object data) { } } }
1031868817-hws
main/src/com/joelapenna/foursquared/TodosActivity.java
Java
asf20
21,177
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.VenueListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.ArrayList; /** * Shows a list of venues that the specified user is mayor of. * We can fetch these ourselves given a userId, or work from * a venue array parcel. * * @date March 15, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserMayorshipsActivity extends LoadableListActivity { static final String TAG = "UserMayorshipsActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME + ".UserMayorshipsActivity.EXTRA_USER_ID"; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".UserMayorshipsActivity.EXTRA_USER_NAME"; public static final String EXTRA_VENUE_LIST_PARCEL = Foursquared.PACKAGE_NAME + ".UserMayorshipsActivity.EXTRA_VENUE_LIST_PARCEL"; private StateHolder mStateHolder; private SeparatedListAdapter mListAdapter; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskVenues(this); } else { if (getIntent().hasExtra(EXTRA_USER_ID) && getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder( getIntent().getStringExtra(EXTRA_USER_ID), getIntent().getStringExtra(EXTRA_USER_NAME)); } else { Log.e(TAG, "UserMayorships requires a userid in its intent extras."); finish(); return; } if (getIntent().getExtras().containsKey(EXTRA_VENUE_LIST_PARCEL)) { // Can't jump from ArrayList to Group, argh. ArrayList<Venue> venues = getIntent().getExtras().getParcelableArrayList( EXTRA_VENUE_LIST_PARCEL); Group<Venue> group = new Group<Venue>(); for (Venue it : venues) { group.add(it); } mStateHolder.setVenues(group); } else { mStateHolder.startTaskVenues(this); } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskVenues(null); return mStateHolder; } private void ensureUi() { mListAdapter = new SeparatedListAdapter(this); VenueListAdapter adapter = new VenueListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); if (mStateHolder.getVenues().size() > 0) { adapter.setGroup(mStateHolder.getVenues()); mListAdapter.addSection( getResources().getString(R.string.user_mayorships_activity_adapter_title), adapter); } ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Venue venue = (Venue)mListAdapter.getItem(position); Intent intent = new Intent(UserMayorshipsActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); } }); if (mStateHolder.getIsRunningVenuesTask()) { setLoadingView(); } else if (mStateHolder.getFetchedVenuesOnce() && mStateHolder.getVenues().size() == 0) { setEmptyView(); } setTitle(getString(R.string.user_mayorships_activity_title, mStateHolder.getUsername())); } private void onVenuesTaskComplete(User user, Exception ex) { mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); if (user != null) { mStateHolder.setVenues(user.getMayorships()); } else { mStateHolder.setVenues(new Group<Venue>()); NotificationsUtil.ToastReasonForFailure(this, ex); } if (mStateHolder.getVenues().size() > 0) { VenueListAdapter adapter = new VenueListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getVenues()); mListAdapter.addSection( getResources().getString(R.string.user_mayorships_activity_adapter_title), adapter); } getListView().setAdapter(mListAdapter); mStateHolder.setIsRunningVenuesTask(false); mStateHolder.setFetchedVenuesOnce(true); // TODO: We can probably tighten this up by just calling ensureUI() again. if (mStateHolder.getVenues().size() == 0) { setEmptyView(); } } @Override public int getNoSearchResultsStringId() { return R.string.user_mayorships_activity_no_info; } /** * Gets venues that the current user is mayor of. */ private static class VenuesTask extends AsyncTask<String, Void, User> { private UserMayorshipsActivity mActivity; private Exception mReason; public VenuesTask(UserMayorshipsActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setLoadingView(); } @Override protected User doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.user(params[0], true, false, false, LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onVenuesTaskComplete(user, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onVenuesTaskComplete(null, mReason); } } public void setActivity(UserMayorshipsActivity activity) { mActivity = activity; } } private static class StateHolder { private String mUserId; private String mUsername; private Group<Venue> mVenues; private VenuesTask mTaskVenues; private boolean mIsRunningVenuesTask; private boolean mFetchedVenuesOnce; public StateHolder(String userId, String username) { mUserId = userId; mUsername = username; mIsRunningVenuesTask = false; mFetchedVenuesOnce = false; mVenues = new Group<Venue>(); } public String getUsername() { return mUsername; } public Group<Venue> getVenues() { return mVenues; } public void setVenues(Group<Venue> venues) { mVenues = venues; } public void startTaskVenues(UserMayorshipsActivity activity) { mIsRunningVenuesTask = true; mTaskVenues = new VenuesTask(activity); mTaskVenues.execute(mUserId); } public void setActivityForTaskVenues(UserMayorshipsActivity activity) { if (mTaskVenues != null) { mTaskVenues.setActivity(activity); } } public void setIsRunningVenuesTask(boolean isRunning) { mIsRunningVenuesTask = isRunning; } public boolean getIsRunningVenuesTask() { return mIsRunningVenuesTask; } public void setFetchedVenuesOnce(boolean fetchedOnce) { mFetchedVenuesOnce = fetchedOnce; } public boolean getFetchedVenuesOnce() { return mFetchedVenuesOnce; } public void cancelTasks() { if (mTaskVenues != null) { mTaskVenues.setActivity(null); mTaskVenues.cancel(true); } } } }
1031868817-hws
main/src/com/joelapenna/foursquared/UserMayorshipsActivity.java
Java
asf20
10,408
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Mayor; import com.joelapenna.foursquare.types.Stats; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.util.VenueUtils; import com.joelapenna.foursquared.widget.PhotoStrip; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * We may be given a pre-fetched venue ready to display, or we might also get just * a venue ID. If we only get a venue ID, then we need to fetch it immediately from * the API. * * The activity will set an intent result in EXTRA_VENUE_RETURNED if the venue status * changes as a result of a user modifying todos at the venue. Parent activities can * check the returned venue to see if this status has changed to update their UI. * For example, the NearbyVenues activity wants to show the todo corner png if the * venue has a todo. * * The result will also be set if the venue is fully fetched if originally given only * a venue id or partial venue object. This way the parent can also cache the full venue * object for next time they want to display this venue activity. * * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Replaced shout activity with CheckinGatherInfoActivity (3/10/2010). * -Redesign from tabbed layout (9/15/2010). */ public class VenueActivity extends Activity { private static final String TAG = "VenueActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int MENU_TIP_ADD = 1; private static final int MENU_TODO_ADD = 2; private static final int MENU_EDIT_VENUE = 3; private static final int MENU_CALL = 4; private static final int MENU_SHARE = 5; private static final int RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE = 1; private static final int RESULT_CODE_ACTIVITY_ADD_TIP = 2; private static final int RESULT_CODE_ACTIVITY_ADD_TODO = 3; private static final int RESULT_CODE_ACTIVITY_TIP = 4; private static final int RESULT_CODE_ACTIVITY_TIPS = 5; private static final int RESULT_CODE_ACTIVITY_TODO = 6; private static final int RESULT_CODE_ACTIVITY_TODOS = 7; public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME + ".VenueActivity.INTENT_EXTRA_VENUE_ID"; public static final String INTENT_EXTRA_VENUE_PARTIAL = Foursquared.PACKAGE_NAME + ".VenueActivity.INTENT_EXTRA_VENUE_PARTIAL"; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueActivity.INTENT_EXTRA_VENUE"; public static final String EXTRA_VENUE_RETURNED = Foursquared.PACKAGE_NAME + ".VenueActivity.EXTRA_VENUE_RETURNED"; private StateHolder mStateHolder; private Handler mHandler; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.venue_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mHandler = new Handler(); StateHolder holder = (StateHolder) getLastNonConfigurationInstance(); if (holder != null) { mStateHolder = holder; mStateHolder.setActivityForTasks(this); prepareResultIntent(); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_FULL); mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE)); } else if (getIntent().hasExtra(INTENT_EXTRA_VENUE_PARTIAL)) { mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_PARTIAL); mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE_PARTIAL)); mStateHolder.startTaskVenue(this); } else if (getIntent().hasExtra(INTENT_EXTRA_VENUE_ID)) { mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_ID); mStateHolder.setVenueId(getIntent().getStringExtra(INTENT_EXTRA_VENUE_ID)); mStateHolder.startTaskVenue(this); } else { Log.e(TAG, "VenueActivity must be given a venue id or a venue parcel as intent extras."); finish(); return; } } mRrm = ((Foursquared) getApplication()).getRemoteResourceManager(); mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); ensureUi(); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); mHandler.removeCallbacks(mRunnableMayorPhoto); if (mRrm != null) { mRrm.deleteObserver(mResourcesObserver); } } @Override public void onResume() { super.onResume(); ensureUiCheckinButton(); // TODO: ensure mayor photo. } private void ensureUi() { TextView tvVenueTitle = (TextView)findViewById(R.id.venueActivityName); TextView tvVenueAddress = (TextView)findViewById(R.id.venueActivityAddress); LinearLayout progress = (LinearLayout)findViewById(R.id.venueActivityDetailsProgress); View viewMayor = findViewById(R.id.venueActivityMayor); TextView tvMayorTitle = (TextView)findViewById(R.id.venueActivityMayorName); TextView tvMayorText = (TextView)findViewById(R.id.venueActivityMayorText); ImageView ivMayorPhoto = (ImageView)findViewById(R.id.venueActivityMayorPhoto); ImageView ivMayorChevron = (ImageView)findViewById(R.id.venueActivityMayorChevron); View viewCheckins = findViewById(R.id.venueActivityCheckins); TextView tvPeopleText = (TextView)findViewById(R.id.venueActivityPeopleText); PhotoStrip psPeoplePhotos = (PhotoStrip)findViewById(R.id.venueActivityPeoplePhotos); View viewTips = findViewById(R.id.venueActivityTips); TextView tvTipsText = (TextView)findViewById(R.id.venueActivityTipsText); TextView tvTipsTextExtra = (TextView)findViewById(R.id.venueActivityTipsExtra); ImageView ivTipsChevron = (ImageView)findViewById(R.id.venueActivityTipsChevron); View viewMoreInfo = findViewById(R.id.venueActivityMoreInfo); TextView tvMoreInfoText = (TextView)findViewById(R.id.venueActivityMoreTitle); Venue venue = mStateHolder.getVenue(); if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_FULL || mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_PARTIAL) { tvVenueTitle.setText(venue.getName()); tvVenueAddress.setText(StringFormatters.getVenueLocationFull(venue)); ensureUiCheckinButton(); if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_FULL) { Stats stats = venue.getStats(); Mayor mayor = stats != null ? stats.getMayor() : null; if (mayor != null) { tvMayorTitle.setText(StringFormatters.getUserFullName(mayor.getUser())); tvMayorText.setText(getResources().getString(R.string.venue_activity_mayor_text)); String photoUrl = mayor.getUser().getPhoto(); Uri uriPhoto = Uri.parse(photoUrl); if (mRrm.exists(uriPhoto)) { try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(photoUrl))); ivMayorPhoto.setImageBitmap(bitmap); } catch (IOException e) { } } else { ivMayorPhoto.setImageResource(UserUtils.getDrawableByGenderForUserThumbnail(mayor.getUser())); ivMayorPhoto.setTag(photoUrl); mRrm.request(uriPhoto); } ivMayorChevron.setVisibility(View.VISIBLE); setClickHandlerMayor(viewMayor); } else { tvMayorTitle.setText(getResources().getString(R.string.venue_activity_mayor_name_none)); tvMayorText.setText(getResources().getString(R.string.venue_activity_mayor_text_none)); ivMayorChevron.setVisibility(View.INVISIBLE); } viewMayor.setVisibility(View.VISIBLE); if (venue.getCheckins() != null && venue.getCheckins().size() > 0) { int friendCount = getFriendCountAtVenue(); int rest = venue.getCheckins().size() - friendCount; if (friendCount > 0 && rest == 0) { // N friends are here tvPeopleText.setText(getResources().getString( friendCount == 1 ? R.string.venue_activity_people_count_friend_single : R.string.venue_activity_people_count_friend_plural, friendCount)); } else if (friendCount > 0 && rest > 0) { // N friends are here with N other people if (friendCount == 1 && rest == 1) { tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_single_single, friendCount, rest)); } else if (friendCount == 1 && rest > 1) { tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_single_plural, friendCount, rest)); } else if (friendCount > 1 && rest == 1) { tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_plural_single, friendCount, rest)); } else { tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_plural_plural, friendCount, rest)); } } else { // N people are here tvPeopleText.setText(getResources().getString( venue.getCheckins().size() == 1 ? R.string.venue_activity_people_count_single : R.string.venue_activity_people_count_plural, venue.getCheckins().size())); } psPeoplePhotos.setCheckinsAndRemoteResourcesManager(venue.getCheckins(), mRrm); viewCheckins.setVisibility(View.VISIBLE); setClickHandlerCheckins(viewCheckins); } else { viewCheckins.setVisibility(View.GONE); } if (venue.getTips() != null && venue.getTips().size() > 0) { int tipCountFriends = getTipCountFriendsAtVenue(); if (tipCountFriends > 0) { tvTipsText.setText( getString(tipCountFriends == 1 ? R.string.venue_activity_tip_count_friend_single : R.string.venue_activity_tip_count_friend_plural, tipCountFriends)); int rest = venue.getTips().size() - tipCountFriends; if (rest > 0) { tvTipsTextExtra.setText( getString(R.string.venue_activity_tip_count_other_people, rest)); tvTipsTextExtra.setVisibility(View.VISIBLE); } } else { tvTipsText.setText( getString(venue.getTips().size() == 1 ? R.string.venue_activity_tip_count_single : R.string.venue_activity_tip_count_plural, venue.getTips().size())); tvTipsTextExtra.setVisibility(View.GONE); } ivTipsChevron.setVisibility(View.VISIBLE); setClickHandlerTips(viewTips); } else { tvTipsText.setText(getResources().getString(R.string.venue_activity_tip_count_none)); tvTipsTextExtra.setVisibility(View.GONE); ivTipsChevron.setVisibility(View.INVISIBLE); } viewTips.setVisibility(View.VISIBLE); if (tvTipsTextExtra.getVisibility() != View.VISIBLE) { tvTipsText.setPadding(tvTipsText.getPaddingLeft(), tvMoreInfoText.getPaddingTop(), tvTipsText.getPaddingRight(), tvMoreInfoText.getPaddingBottom()); } viewMoreInfo.setVisibility(View.VISIBLE); setClickHandlerMoreInfo(viewMoreInfo); progress.setVisibility(View.GONE); } } ensureUiTodosHere(); ImageView ivSpecialHere = (ImageView)findViewById(R.id.venueActivitySpecialHere); if (VenueUtils.getSpecialHere(venue)) { ivSpecialHere.setVisibility(View.VISIBLE); ivSpecialHere.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { showWebViewForSpecial(); } }); } else { ivSpecialHere.setVisibility(View.GONE); } } private void ensureUiCheckinButton() { Button btnCheckin = (Button)findViewById(R.id.venueActivityButtonCheckin); if (mStateHolder.getCheckedInHere()) { btnCheckin.setEnabled(false); } else { if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_ID) { btnCheckin.setEnabled(false); } else { btnCheckin.setEnabled(true); btnCheckin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences( VenueActivity.this); if (settings.getBoolean(Preferences.PREFERENCE_IMMEDIATE_CHECKIN, false)) { startCheckinQuick(); } else { startCheckin(); } } }); } } } private void ensureUiTipAdded() { Venue venue = mStateHolder.getVenue(); TextView tvTipsText = (TextView)findViewById(R.id.venueActivityTipsText); ImageView ivTipsChevron = (ImageView)findViewById(R.id.venueActivityTipsChevron); if (venue.getTips().size() == 1) { tvTipsText.setText(getResources().getString( R.string.venue_activity_tip_count_single, venue.getTips().size())); } else { tvTipsText.setText(getResources().getString( R.string.venue_activity_tip_count_plural, venue.getTips().size())); } ivTipsChevron.setVisibility(View.VISIBLE); } private void ensureUiTodosHere() { Venue venue = mStateHolder.getVenue(); RelativeLayout rlTodoHere = (RelativeLayout)findViewById(R.id.venueActivityTodoHere); if (venue != null && venue.getHasTodo()) { rlTodoHere.setVisibility(View.VISIBLE); rlTodoHere.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { showTodoHereActivity(); } }); } else { rlTodoHere.setVisibility(View.GONE); } } private void setClickHandlerMayor(View view) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VenueActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, mStateHolder.getVenue().getStats().getMayor().getUser()); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } }); } private void setClickHandlerCheckins(View view) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VenueActivity.this, VenueCheckinsActivity.class); intent.putExtra(VenueCheckinsActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivity(intent); } }); } private void setClickHandlerTips(View view) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = null; if (mStateHolder.getVenue().getTips().size() == 1) { Venue venue = new Venue(); venue.setName(mStateHolder.getVenue().getName()); venue.setAddress(mStateHolder.getVenue().getAddress()); venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet()); Tip tip = mStateHolder.getVenue().getTips().get(0); tip.setVenue(venue); intent = new Intent(VenueActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip); intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false); startActivityForResult(intent, RESULT_CODE_ACTIVITY_TIP); } else { intent = new Intent(VenueActivity.this, VenueTipsActivity.class); intent.putExtra(VenueTipsActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivityForResult(intent, RESULT_CODE_ACTIVITY_TIPS); } } }); } private void setClickHandlerMoreInfo(View view) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VenueActivity.this, VenueMapActivity.class); intent.putExtra(VenueMapActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivity(intent); } }); } private void prepareResultIntent() { Venue venue = mStateHolder.getVenue(); Intent intent = new Intent(); if (venue != null) { intent.putExtra(EXTRA_VENUE_RETURNED, venue); } setResult(Activity.RESULT_OK, intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_TIP_ADD, 1, R.string.venue_activity_menu_add_tip).setIcon( R.drawable.ic_menu_venue_leave_tip); menu.add(Menu.NONE, MENU_TODO_ADD, 2, R.string.venue_activity_menu_add_todo).setIcon( R.drawable.ic_menu_venue_add_todo); menu.add(Menu.NONE, MENU_EDIT_VENUE, 3, R.string.venue_activity_menu_flag).setIcon( R.drawable.ic_menu_venue_flag); menu.add(Menu.NONE, MENU_CALL, 4, R.string.venue_activity_menu_call).setIcon( R.drawable.ic_menu_venue_contact); menu.add(Menu.NONE, MENU_SHARE, 5, R.string.venue_activity_menu_share).setIcon( R.drawable.ic_menu_venue_share); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean callEnabled = mStateHolder.getVenue() != null && !TextUtils.isEmpty(mStateHolder.getVenue().getPhone()); menu.findItem(MENU_CALL).setEnabled(callEnabled); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_TIP_ADD: Intent intentTip = new Intent(VenueActivity.this, AddTipActivity.class); intentTip.putExtra(AddTipActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivityForResult(intentTip, RESULT_CODE_ACTIVITY_ADD_TIP); return true; case MENU_TODO_ADD: Intent intentTodo = new Intent(VenueActivity.this, AddTodoActivity.class); intentTodo.putExtra(AddTodoActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivityForResult(intentTodo, RESULT_CODE_ACTIVITY_ADD_TODO); return true; case MENU_EDIT_VENUE: Intent intentEditVenue = new Intent(this, EditVenueOptionsActivity.class); intentEditVenue.putExtra( EditVenueOptionsActivity.EXTRA_VENUE_PARCELABLE, mStateHolder.getVenue()); startActivity(intentEditVenue); return true; case MENU_CALL: try { Intent dial = new Intent(); dial.setAction(Intent.ACTION_DIAL); dial.setData(Uri.parse("tel:" + mStateHolder.getVenue().getPhone())); startActivity(dial); } catch (Exception ex) { Log.e(TAG, "Error starting phone dialer intent.", ex); Toast.makeText(this, "Sorry, we couldn't find any app to place a phone call!", Toast.LENGTH_SHORT).show(); } return true; case MENU_SHARE: Intent intentShare = new Intent(this, VenueShareActivity.class); intentShare.putExtra(VenueShareActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivity(intentShare); return true; } return super.onOptionsItemSelected(item); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTasks(null); return mStateHolder; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE: if (resultCode == Activity.RESULT_OK) { mStateHolder.setCheckedInHere(true); ensureUiCheckinButton(); } break; case RESULT_CODE_ACTIVITY_ADD_TIP: if (resultCode == Activity.RESULT_OK) { Tip tip = data.getParcelableExtra(AddTipActivity.EXTRA_TIP_RETURNED); VenueUtils.addTip(mStateHolder.getVenue(), tip); ensureUiTipAdded(); prepareResultIntent(); Toast.makeText(this, getResources().getString(R.string.venue_activity_tip_added_ok), Toast.LENGTH_SHORT).show(); } break; case RESULT_CODE_ACTIVITY_ADD_TODO: if (resultCode == Activity.RESULT_OK) { Todo todo = data.getParcelableExtra(AddTodoActivity.EXTRA_TODO_RETURNED); VenueUtils.addTodo(mStateHolder.getVenue(), todo.getTip(), todo); ensureUiTodosHere(); prepareResultIntent(); Toast.makeText(this, getResources().getString(R.string.venue_activity_todo_added_ok), Toast.LENGTH_SHORT).show(); } break; case RESULT_CODE_ACTIVITY_TIP: case RESULT_CODE_ACTIVITY_TODO: if (resultCode == Activity.RESULT_OK && data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) { Tip tip = (Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED); Todo todo = data.hasExtra(TipActivity.EXTRA_TODO_RETURNED) ? (Todo)data.getParcelableExtra(TipActivity.EXTRA_TODO_RETURNED) : null; VenueUtils.handleTipChange(mStateHolder.getVenue(), tip, todo); ensureUiTodosHere(); prepareResultIntent(); } break; case RESULT_CODE_ACTIVITY_TIPS: if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE)) { Venue venue = (Venue)data.getParcelableExtra(VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE); VenueUtils.replaceTipsAndTodos(mStateHolder.getVenue(), venue); ensureUiTodosHere(); prepareResultIntent(); } break; case RESULT_CODE_ACTIVITY_TODOS: if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE)) { Venue venue = (Venue)data.getParcelableExtra(VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE); VenueUtils.replaceTipsAndTodos(mStateHolder.getVenue(), venue); ensureUiTodosHere(); prepareResultIntent(); } break; } } private void startCheckin() { Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN, true); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenue().getId()); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME, mStateHolder.getVenue().getName()); startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE); } private void startCheckinQuick() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); boolean tellFriends = settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true); boolean tellTwitter = settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false); boolean tellFacebook = settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false); Intent intent = new Intent(VenueActivity.this, CheckinExecuteActivity.class); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenue().getId()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, ""); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, tellFriends); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, tellTwitter); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, tellFacebook); startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE); } private void showWebViewForSpecial() { Intent intent = new Intent(this, SpecialWebViewActivity.class); intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME, PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_LOGIN, "")); intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD, PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_PASSWORD, "")); intent.putExtra(SpecialWebViewActivity.EXTRA_SPECIAL_ID, mStateHolder.getVenue().getSpecials().get(0).getId()); startActivity(intent); } private void showTodoHereActivity() { Venue venue = new Venue(); venue.setName(mStateHolder.getVenue().getName()); venue.setAddress(mStateHolder.getVenue().getAddress()); venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet()); Group<Todo> todos = mStateHolder.getVenue().getTodos(); for (Todo it : todos) { it.getTip().setVenue(venue); } if (todos.size() == 1) { Todo todo = (Todo) todos.get(0); Intent intent = new Intent(VenueActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip()); intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false); startActivityForResult(intent, RESULT_CODE_ACTIVITY_TODO); } else if (todos.size() > 1) { Intent intent = new Intent(VenueActivity.this, VenueTodosActivity.class); intent.putExtra(VenueTodosActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue()); startActivityForResult(intent, RESULT_CODE_ACTIVITY_TODOS); } } private int getFriendCountAtVenue() { int count = 0; Venue venue = mStateHolder.getVenue(); if (venue.getCheckins() != null) { for (Checkin it : venue.getCheckins()) { User user = it.getUser(); if (UserUtils.isFriend(user)) { count++; } } } return count; } private int getTipCountFriendsAtVenue() { int count = 0; Venue venue = mStateHolder.getVenue(); if (venue.getTips() != null) { for (Tip it : venue.getTips()) { User user = it.getUser(); if (UserUtils.isFriend(user)) { count++; } } } return count; } private static class TaskVenue extends AsyncTask<String, Void, Venue> { private VenueActivity mActivity; private Exception mReason; public TaskVenue(VenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { } @Override protected Venue doInBackground(String... params) { try { Foursquared foursquared = (Foursquared)mActivity.getApplication(); return foursquared.getFoursquare().venue( params[0], LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { Log.e(TAG, "Error getting venue details.", e); mReason = e; } return null; } @Override protected void onPostExecute(Venue venue) { if (mActivity != null) { mActivity.mStateHolder.setIsRunningTaskVenue(false); if (venue != null) { mActivity.mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_FULL); mActivity.mStateHolder.setVenue(venue); mActivity.prepareResultIntent(); mActivity.ensureUi(); } else { NotificationsUtil.ToastReasonForFailure(mActivity, mReason); mActivity.finish(); } } } @Override protected void onCancelled() { } public void setActivity(VenueActivity activity) { mActivity = activity; } } private static final class StateHolder { private Venue mVenue; private String mVenueId; private boolean mCheckedInHere; private TaskVenue mTaskVenue; private boolean mIsRunningTaskVenue; private int mLoadType; public static final int LOAD_TYPE_VENUE_ID = 0; public static final int LOAD_TYPE_VENUE_PARTIAL = 1; public static final int LOAD_TYPE_VENUE_FULL = 2; public StateHolder() { mIsRunningTaskVenue = false; } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } public void setVenueId(String venueId) { mVenueId = venueId; } public boolean getCheckedInHere() { return mCheckedInHere; } public void setCheckedInHere(boolean checkedInHere) { mCheckedInHere = checkedInHere; } public void setIsRunningTaskVenue(boolean isRunningTaskVenue) { mIsRunningTaskVenue = isRunningTaskVenue; } public void startTaskVenue(VenueActivity activity) { if (!mIsRunningTaskVenue) { mIsRunningTaskVenue = true; mTaskVenue = new TaskVenue(activity); if (mLoadType == LOAD_TYPE_VENUE_ID) { mTaskVenue.execute(mVenueId); } else if (mLoadType == LOAD_TYPE_VENUE_PARTIAL) { mTaskVenue.execute(mVenue.getId()); } } } public void setActivityForTasks(VenueActivity activity) { if (mTaskVenue != null) { mTaskVenue.setActivity(activity); } } public int getLoadType() { return mLoadType; } public void setLoadType(int loadType) { mLoadType = loadType; } } /** * Handles population of the mayor photo. The strip of checkin photos has its own * internal observer. */ private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mRunnableMayorPhoto); } } private Runnable mRunnableMayorPhoto = new Runnable() { @Override public void run() { ImageView ivMayorPhoto = (ImageView)findViewById(R.id.venueActivityMayorPhoto); if (ivMayorPhoto.getTag() != null) { String mayorPhotoUrl = (String)ivMayorPhoto.getTag(); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(mayorPhotoUrl))); ivMayorPhoto.setImageBitmap(bitmap); ivMayorPhoto.setTag(null); ivMayorPhoto.invalidate(); } catch (IOException ex) { Log.e(TAG, "Error decoding mayor photo on notification, ignoring.", ex); } } } }; }
1031868817-hws
main/src/com/joelapenna/foursquared/VenueActivity.java
Java
asf20
35,457
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import com.joelapenna.foursquared.widget.TipsListAdapter; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import java.util.Observable; import java.util.Observer; /** * Shows a list of nearby tips. User can sort tips by friends-only. * * @date August 31, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TipsActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "TipsActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int ACTIVITY_TIP = 500; private StateHolder mStateHolder; private TipsListAdapter mListAdapter; private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private View mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); mStateHolder.setFriendsOnly(true); } ensureUi(); // Friend tips is shown first by default so auto-fetch it if necessary. if (!mStateHolder.getRanOnceTipsFriends()) { mStateHolder.startTaskTips(this, true); } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); mLayoutEmpty = inflater.inflate(R.layout.tips_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new TipsListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item); if (mStateHolder.getFriendsOnly()) { mListAdapter.setGroup(mStateHolder.getTipsFriends()); if (mStateHolder.getTipsFriends().size() == 0) { if (mStateHolder.getRanOnceTipsFriends()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } else { mListAdapter.setGroup(mStateHolder.getTipsEveryone()); if (mStateHolder.getTipsEveryone().size() == 0) { if (mStateHolder.getRanOnceTipsEveryone()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.tips_activity_btn_friends_only), getString(R.string.tips_activity_btn_everyone)); if (mStateHolder.mFriendsOnly) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setFriendsOnly(true); mListAdapter.setGroup(mStateHolder.getTipsFriends()); if (mStateHolder.getTipsFriends().size() < 1) { if (mStateHolder.getRanOnceTipsFriends()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskTips(TipsActivity.this, true); } } } else { mStateHolder.setFriendsOnly(false); mListAdapter.setGroup(mStateHolder.getTipsEveryone()); if (mStateHolder.getTipsEveryone().size() < 1) { if (mStateHolder.getRanOnceTipsEveryone()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskTips(TipsActivity.this, false); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tip tip = (Tip) parent.getAdapter().getItem(position); Intent intent = new Intent(TipsActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip); startActivityForResult(intent, ACTIVITY_TIP); } }); if (mStateHolder.getIsRunningTaskTipsFriends() || mStateHolder.getIsRunningTaskTipsEveryone()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); MenuUtils.addPreferencesToMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTaskTips(this, mStateHolder.getFriendsOnly()); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // We don't care about the returned to-do (if any) since we're not bound // to a venue in this activity for update. We just update the status member // of the target tip. if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) { if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) { Log.d(TAG, "onActivityResult(), return tip intent extra found, processing."); updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED)); } else { Log.d(TAG, "onActivityResult(), no return tip intent extra found."); } } } private void updateTip(Tip tip) { mStateHolder.updateTip(tip); mListAdapter.notifyDataSetInvalidated(); } private void onStartTaskTips() { if (mListAdapter != null) { if (mStateHolder.getFriendsOnly()) { mStateHolder.setIsRunningTaskTipsFriends(true); mListAdapter.setGroup(mStateHolder.getTipsFriends()); } else { mStateHolder.setIsRunningTaskTipsEveryone(true); mListAdapter.setGroup(mStateHolder.getTipsEveryone()); } mListAdapter.notifyDataSetChanged(); } setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskTipsComplete(Group<Tip> group, boolean friendsOnly, Exception ex) { SegmentedButton buttons = getHeaderButton(); boolean update = false; if (group != null) { if (friendsOnly) { mStateHolder.setTipsFriends(group); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getTipsFriends()); update = true; } } else { mStateHolder.setTipsEveryone(group); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getTipsEveryone()); update = true; } } } else { if (friendsOnly) { mStateHolder.setTipsFriends(new Group<Tip>()); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getTipsFriends()); update = true; } } else { mStateHolder.setTipsEveryone(new Group<Tip>()); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getTipsEveryone()); update = true; } } NotificationsUtil.ToastReasonForFailure(this, ex); } if (friendsOnly) { mStateHolder.setIsRunningTaskTipsFriends(false); mStateHolder.setRanOnceTipsFriends(true); if (mStateHolder.getTipsFriends().size() == 0 && buttons.getSelectedButtonIndex() == 0) { setEmptyView(mLayoutEmpty); } } else { mStateHolder.setIsRunningTaskTipsEveryone(false); mStateHolder.setRanOnceTipsEveryone(true); if (mStateHolder.getTipsEveryone().size() == 0 && buttons.getSelectedButtonIndex() == 1) { setEmptyView(mLayoutEmpty); } } if (update) { mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } if (!mStateHolder.getIsRunningTaskTipsFriends() && !mStateHolder.getIsRunningTaskTipsEveryone()) { setProgressBarIndeterminateVisibility(false); } } /** * Gets friends of the current user we're working for. */ private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> { private TipsActivity mActivity; private boolean mFriendsOnly; private Exception mReason; public TaskTips(TipsActivity activity, boolean friendsOnly) { mActivity = activity; mFriendsOnly = friendsOnly; } @Override protected void onPreExecute() { mActivity.onStartTaskTips(); } @Override protected Group<Tip> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location loc = foursquared.getLastKnownLocation(); if (loc == null) { try { Thread.sleep(3000); } catch (InterruptedException ex) {} loc = foursquared.getLastKnownLocation(); if (loc == null) { throw new FoursquareException("Your location could not be determined!"); } } return foursquare.tips( LocationUtils.createFoursquareLocation(loc), null, mFriendsOnly ? "friends" : "nearby", null, 30); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<Tip> tips) { if (mActivity != null) { mActivity.onTaskTipsComplete(tips, mFriendsOnly, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskTipsComplete(null, mFriendsOnly, mReason); } } public void setActivity(TipsActivity activity) { mActivity = activity; } } private static class StateHolder { /** Tips by friends. */ private Group<Tip> mTipsFriends; /** Tips by everyone. */ private Group<Tip> mTipsEveryone; private TaskTips mTaskTipsFriends; private TaskTips mTaskTipsEveryone; private boolean mIsRunningTaskTipsFriends; private boolean mIsRunningTaskTipsEveryone; private boolean mFriendsOnly; private boolean mRanOnceTipsFriends; private boolean mRanOnceTipsEveryone; public StateHolder() { mIsRunningTaskTipsFriends = false; mIsRunningTaskTipsEveryone = false; mRanOnceTipsFriends = false; mRanOnceTipsEveryone = false; mTipsFriends = new Group<Tip>(); mTipsEveryone = new Group<Tip>(); mFriendsOnly = true; } public Group<Tip> getTipsFriends() { return mTipsFriends; } public void setTipsFriends(Group<Tip> tipsFriends) { mTipsFriends = tipsFriends; } public Group<Tip> getTipsEveryone() { return mTipsEveryone; } public void setTipsEveryone(Group<Tip> tipsEveryone) { mTipsEveryone = tipsEveryone; } public void startTaskTips(TipsActivity activity, boolean friendsOnly) { if (friendsOnly) { if (mIsRunningTaskTipsFriends) { return; } mIsRunningTaskTipsFriends = true; mTaskTipsFriends = new TaskTips(activity, friendsOnly); mTaskTipsFriends.execute(); } else { if (mIsRunningTaskTipsEveryone) { return; } mIsRunningTaskTipsEveryone = true; mTaskTipsEveryone = new TaskTips(activity, friendsOnly); mTaskTipsEveryone.execute(); } } public void setActivity(TipsActivity activity) { if (mTaskTipsFriends != null) { mTaskTipsFriends.setActivity(activity); } if (mTaskTipsEveryone != null) { mTaskTipsEveryone.setActivity(activity); } } public boolean getIsRunningTaskTipsFriends() { return mIsRunningTaskTipsFriends; } public void setIsRunningTaskTipsFriends(boolean isRunning) { mIsRunningTaskTipsFriends = isRunning; } public boolean getIsRunningTaskTipsEveryone() { return mIsRunningTaskTipsEveryone; } public void setIsRunningTaskTipsEveryone(boolean isRunning) { mIsRunningTaskTipsEveryone = isRunning; } public void cancelTasks() { if (mTaskTipsFriends != null) { mTaskTipsFriends.setActivity(null); mTaskTipsFriends.cancel(true); } if (mTaskTipsEveryone != null) { mTaskTipsEveryone.setActivity(null); mTaskTipsEveryone.cancel(true); } } public boolean getFriendsOnly() { return mFriendsOnly; } public void setFriendsOnly(boolean friendsOnly) { mFriendsOnly = friendsOnly; } public boolean getRanOnceTipsFriends() { return mRanOnceTipsFriends; } public void setRanOnceTipsFriends(boolean ranOnce) { mRanOnceTipsFriends = ranOnce; } public boolean getRanOnceTipsEveryone() { return mRanOnceTipsEveryone; } public void setRanOnceTipsEveryone(boolean ranOnce) { mRanOnceTipsEveryone = ranOnce; } public void updateTip(Tip tip) { updateTipFromArray(tip, mTipsFriends); updateTipFromArray(tip, mTipsEveryone); } private void updateTipFromArray(Tip tip, Group<Tip> target) { for (Tip it : target) { if (it.getId().equals(tip.getId())) { it.setStatus(tip.getStatus()); break; } } } } /** * This is really just a dummy observer to get the GPS running * since this is the new splash page. After getting a fix, we * might want to stop registering this observer thereafter so * it doesn't annoy the user too much. */ private class SearchLocationObserver implements Observer { @Override public void update(Observable observable, Object data) { } } }
1031868817-hws
main/src/com/joelapenna/foursquared/TipsActivity.java
Java
asf20
19,171
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LoginActivity extends Activity { public static final String TAG = "LoginActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private AsyncTask<Void, Void, Boolean> mLoginTask; private TextView mNewAccountTextView; private EditText mPhoneUsernameEditText; private EditText mPasswordEditText; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.login_activity); Preferences.logoutUser( // ((Foursquared) getApplication()).getFoursquare(), // PreferenceManager.getDefaultSharedPreferences(this).edit()); // Set up the UI. ensureUi(); // Re-task if the request was cancelled. mLoginTask = (LoginTask) getLastNonConfigurationInstance(); if (mLoginTask != null && mLoginTask.isCancelled()) { if (DEBUG) Log.d(TAG, "LoginTask previously cancelled, trying again."); mLoginTask = new LoginTask().execute(); } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(false); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(); } @Override public Object onRetainNonConfigurationInstance() { if (DEBUG) Log.d(TAG, "onRetainNonConfigurationInstance()"); if (mLoginTask != null) { mLoginTask.cancel(true); } return mLoginTask; } private ProgressDialog showProgressDialog() { if (mProgressDialog == null) { ProgressDialog dialog = new ProgressDialog(this); dialog.setTitle(R.string.login_dialog_title); dialog.setMessage(getString(R.string.login_dialog_message)); dialog.setIndeterminate(true); dialog.setCancelable(true); mProgressDialog = dialog; } mProgressDialog.show(); return mProgressDialog; } private void dismissProgressDialog() { try { mProgressDialog.dismiss(); } catch (IllegalArgumentException e) { // We don't mind. android cleared it for us. } } private void ensureUi() { final Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mLoginTask = new LoginTask().execute(); } }); mNewAccountTextView = (TextView) findViewById(R.id.newAccountTextView); mNewAccountTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_MOBILE_SIGNUP))); } }); mPhoneUsernameEditText = ((EditText) findViewById(R.id.phoneEditText)); mPasswordEditText = ((EditText) findViewById(R.id.passwordEditText)); TextWatcher fieldValidatorTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { button.setEnabled(phoneNumberEditTextFieldIsValid() && passwordEditTextFieldIsValid()); } private boolean phoneNumberEditTextFieldIsValid() { // This can be either a phone number or username so we don't // care too much about the // format. return !TextUtils.isEmpty(mPhoneUsernameEditText.getText()); } private boolean passwordEditTextFieldIsValid() { return !TextUtils.isEmpty(mPasswordEditText.getText()); } }; mPhoneUsernameEditText.addTextChangedListener(fieldValidatorTextWatcher); mPasswordEditText.addTextChangedListener(fieldValidatorTextWatcher); } private class LoginTask extends AsyncTask<Void, Void, Boolean> { private static final String TAG = "LoginTask"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private Exception mReason; @Override protected void onPreExecute() { if (DEBUG) Log.d(TAG, "onPreExecute()"); showProgressDialog(); } @Override protected Boolean doInBackground(Void... params) { if (DEBUG) Log.d(TAG, "doInBackground()"); SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(LoginActivity.this); Editor editor = prefs.edit(); Foursquared foursquared = (Foursquared) getApplication(); Foursquare foursquare = foursquared.getFoursquare(); try { String phoneNumber = mPhoneUsernameEditText.getText().toString(); String password = mPasswordEditText.getText().toString(); Foursquare.Location location = null; location = LocationUtils.createFoursquareLocation( foursquared.getLastKnownLocation()); boolean loggedIn = Preferences.loginUser(foursquare, phoneNumber, password, location, editor); // Make sure prefs makes a round trip. String userId = Preferences.getUserId(prefs); if (TextUtils.isEmpty(userId)) { if (DEBUG) Log.d(TAG, "Preference store calls failed"); throw new FoursquareException(getResources().getString( R.string.login_failed_login_toast)); } return loggedIn; } catch (Exception e) { if (DEBUG) Log.d(TAG, "Caught Exception logging in.", e); mReason = e; Preferences.logoutUser(foursquare, editor); return false; } } @Override protected void onPostExecute(Boolean loggedIn) { if (DEBUG) Log.d(TAG, "onPostExecute(): " + loggedIn); Foursquared foursquared = (Foursquared) getApplication(); if (loggedIn) { sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_IN)); Toast.makeText(LoginActivity.this, getString(R.string.login_welcome_toast), Toast.LENGTH_LONG).show(); // Launch the service to update any widgets, etc. foursquared.requestStartService(); // Launch the main activity to let the user do anything. Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); // Be done with the activity. finish(); } else { sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT)); NotificationsUtil.ToastReasonForFailure(LoginActivity.this, mReason); } dismissProgressDialog(); } @Override protected void onCancelled() { dismissProgressDialog(); } } }
1031868817-hws
main/src/com/joelapenna/foursquared/LoginActivity.java
Java
asf20
8,813
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider; import com.joelapenna.foursquared.util.Comparators; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.TabsUtil; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.VenueListAdapter; import android.app.Activity; import android.app.SearchManager; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcelable; import android.provider.SearchRecentSuggestions; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.Collections; import java.util.Observable; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class SearchVenuesActivity extends TabActivity { static final String TAG = "SearchVenuesActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String QUERY_NEARBY = null; public static SearchResultsObservable searchResultsObservable; private static final int MENU_SEARCH = 0; private static final int MENU_REFRESH = 1; private static final int MENU_NEARBY = 2; private static final int MENU_ADD_VENUE = 3; private static final int MENU_GROUP_SEARCH = 0; private SearchTask mSearchTask; private SearchHolder mSearchHolder = new SearchHolder(); private ListView mListView; private LinearLayout mEmpty; private TextView mEmptyText; private ProgressBar mEmptyProgress; private TabHost mTabHost; private SeparatedListAdapter mListAdapter; private boolean mIsShortcutPicker; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.search_venues_activity); setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); searchResultsObservable = new SearchResultsObservable(); initTabHost(); initListViewAdapter(); // Watch to see if we've been called as a shortcut intent. mIsShortcutPicker = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction()); if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Restoring state."); SearchHolder holder = (SearchHolder) getLastNonConfigurationInstance(); if (holder.results != null) { mSearchHolder.query = holder.query; setSearchResults(holder.results); putSearchResultsInAdapter(holder.results); } } else { onNewIntent(getIntent()); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(true); if (mSearchHolder.results == null && mSearchTask == null) { mSearchTask = (SearchTask) new SearchTask().execute(); } } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onStop() { super.onStop(); if (mSearchTask != null) { mSearchTask.cancel(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Always show these. menu.add(MENU_GROUP_SEARCH, MENU_SEARCH, Menu.NONE, R.string.search_label) // .setIcon(R.drawable.ic_menu_search) // .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(MENU_GROUP_SEARCH, MENU_NEARBY, Menu.NONE, R.string.nearby_label) // .setIcon(R.drawable.ic_menu_places); menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh) // .setIcon(R.drawable.ic_menu_refresh); menu.add(MENU_GROUP_SEARCH, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) // .setIcon(R.drawable.ic_menu_add); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SEARCH: onSearchRequested(); return true; case MENU_NEARBY: executeSearchTask(null); return true; case MENU_REFRESH: executeSearchTask(mSearchHolder.query); return true; case MENU_ADD_VENUE: Intent intent = new Intent(SearchVenuesActivity.this, AddVenueActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onNewIntent(Intent intent) { if (intent != null) { String action = intent.getAction(); String query = intent.getStringExtra(SearchManager.QUERY); Log.i(TAG, "New Intent: action[" + action + "]."); if (!TextUtils.isEmpty(action)) { if (action.equals(Intent.ACTION_CREATE_SHORTCUT)) { Log.i(TAG, " action = create shortcut, user can click one of the current venues."); } else if (action.equals(Intent.ACTION_VIEW)) { if (!TextUtils.isEmpty(query)) { Log.i(TAG, " action = view, query term provided, prepopulating search."); startSearch(query, false, null, false); } else { Log.i(TAG, " action = view, but no query term provided, doing nothing."); } } else if (action.equals(Intent.ACTION_SEARCH) && !TextUtils.isEmpty(query)) { Log.i(TAG, " action = search, query term provided, executing search immediately."); SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, VenueQuerySuggestionsProvider.AUTHORITY, VenueQuerySuggestionsProvider.MODE); suggestions.saveRecentQuery(query, null); executeSearchTask(query); } } } } @Override public Object onRetainNonConfigurationInstance() { return mSearchHolder; } public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) { mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); int groupCount = searchResults.size(); for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) { Group<Venue> group = searchResults.get(groupsIndex); if (group.size() > 0) { VenueListAdapter groupAdapter = new VenueListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); groupAdapter.setGroup(group); if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType()); mListAdapter.addSection(group.getType(), groupAdapter); } } mListView.setAdapter(mListAdapter); } public void setSearchResults(Group<Group<Venue>> searchResults) { if (DEBUG) Log.d(TAG, "Setting search results."); mSearchHolder.results = searchResults; searchResultsObservable.notifyObservers(); } void executeSearchTask(String query) { if (DEBUG) Log.d(TAG, "sendQuery()"); mSearchHolder.query = query; // not going through set* because we don't want to notify search result // observers. mSearchHolder.results = null; // If a task is already running, don't start a new one. if (mSearchTask != null && mSearchTask.getStatus() != AsyncTask.Status.FINISHED) { if (DEBUG) Log.d(TAG, "Query already running attempting to cancel: " + mSearchTask); if (!mSearchTask.cancel(true) && !mSearchTask.isCancelled()) { if (DEBUG) Log.d(TAG, "Unable to cancel search? Notifying the user."); Toast.makeText(this, getString(R.string.search_already_in_progress_toast), Toast.LENGTH_SHORT); return; } } mSearchTask = (SearchTask) new SearchTask().execute(); } void startItemActivity(Venue venue) { Intent intent = new Intent(SearchVenuesActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); } private void ensureSearchResults() { if (mListAdapter.getCount() > 0) { mEmpty.setVisibility(LinearLayout.GONE); mListView.setVisibility(ViewGroup.VISIBLE); } else { mEmpty.setVisibility(LinearLayout.VISIBLE); mEmptyProgress.setVisibility(ViewGroup.GONE); mEmptyText.setText(R.string.no_search_results); mListView.setVisibility(ViewGroup.GONE); } } private void ensureTitle(boolean finished) { if (finished) { if (mSearchHolder.query == QUERY_NEARBY) { setTitle(getString(R.string.title_search_finished_noquery)); } else { setTitle(getString(R.string.title_search_finished, mSearchHolder.query)); } } else { if (mSearchHolder.query == QUERY_NEARBY) { setTitle(getString(R.string.title_search_inprogress_noquery)); } else { setTitle(getString(R.string.title_search_inprogress, mSearchHolder.query)); } } } private void initListViewAdapter() { if (mListView != null) { throw new IllegalStateException("Trying to initialize already initialized ListView"); } mEmpty = (LinearLayout) findViewById(R.id.empty); mEmptyText = (TextView) findViewById(R.id.emptyText); mEmptyProgress = (ProgressBar) findViewById(R.id.emptyProgress); mListView = (ListView) findViewById(R.id.list); mListAdapter = new SeparatedListAdapter(this); mListView.setAdapter(mListAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Venue venue = (Venue) parent.getAdapter().getItem(position); if (mIsShortcutPicker) { setupShortcut(venue); finish(); } else { startItemActivity(venue); } finish(); } }); } protected void setupShortcut(Venue venue) { // First, set up the shortcut intent. For this example, we simply create // an intent that will bring us directly back to this activity. A more // typical implementation would use a data Uri in order to display a more // specific result, or a custom action in order to launch a specific operation. Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); shortcutIntent.setClassName(this, VenueActivity.class.getName()); shortcutIntent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, venue.getId()); // Then, set up the container intent (the response to the caller) Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, venue.getName()); Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.venue_shortcut_icon); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); } private void initTabHost() { if (mTabHost != null) { throw new IllegalStateException("Trying to intialize already initializd TabHost"); } mTabHost = getTabHost(); TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_venues), R.drawable.tab_search_nav_venues_selector, 0, R.id.listviewLayout); TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_map), R.drawable.tab_search_nav_map_selector, 1, new Intent(this, SearchVenuesMapActivity.class)); mTabHost.setCurrentTab(0); // Fix layout for 1.5. if (UiUtil.sdkVersion() < 4) { FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent); flTabContent.setPadding(0, 0, 0, 0); } } private class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> { private Exception mReason = null; @Override public void onPreExecute() { if (DEBUG) Log.d(TAG, "SearchTask: onPreExecute()"); setProgressBarIndeterminateVisibility(true); ensureTitle(false); } @Override public Group<Group<Venue>> doInBackground(Void... params) { try { return search(); } catch (Exception e) { mReason = e; } return null; } @Override public void onPostExecute(Group<Group<Venue>> groups) { try { if (groups == null) { NotificationsUtil.ToastReasonForFailure(SearchVenuesActivity.this, mReason); } else { setSearchResults(groups); putSearchResultsInAdapter(groups); } } finally { setProgressBarIndeterminateVisibility(false); ensureTitle(true); ensureSearchResults(); } } public Group<Group<Venue>> search() throws FoursquareException, LocationException, IOException { Foursquare foursquare = ((Foursquared) getApplication()).getFoursquare(); Location location = ((Foursquared) getApplication()).getLastKnownLocationOrThrow(); Group<Group<Venue>> groups = foursquare.venues(LocationUtils .createFoursquareLocation(location), mSearchHolder.query, 30); for (int i = 0; i < groups.size(); i++) { Collections.sort(groups.get(i), Comparators.getVenueDistanceComparator()); } return groups; } } private static class SearchHolder { Group<Group<Venue>> results; String query; } class SearchResultsObservable extends Observable { @Override public void notifyObservers(Object data) { setChanged(); super.notifyObservers(data); } public Group<Group<Venue>> getSearchResults() { return mSearchHolder.results; } public String getQuery() { return mSearchHolder.query; } }; }
1031868817-hws
main/src/com/joelapenna/foursquared/SearchVenuesActivity.java
Java
asf20
16,934
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.PhotoStrip; import com.joelapenna.foursquared.widget.UserContactAdapter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.CharacterStyle; import android.text.style.StyleSpan; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @date March 8, 2010. * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsActivity extends Activity { private static final String TAG = "UserDetailsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int ACTIVITY_REQUEST_CODE_PINGS = 815; private static final int ACTIVITY_REQUEST_CODE_FETCH_IMAGE = 816; private static final int ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE = 817; public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME + ".UserDetailsActivity.EXTRA_USER_PARCEL"; public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME + ".UserDetailsActivity.EXTRA_USER_ID"; public static final String EXTRA_SHOW_ADD_FRIEND_OPTIONS = Foursquared.PACKAGE_NAME + ".UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS"; private static final int LOAD_TYPE_USER_NONE = 0; private static final int LOAD_TYPE_USER_ID = 1; private static final int LOAD_TYPE_USER_PARTIAL = 2; private static final int LOAD_TYPE_USER_FULL = 3; private static final int MENU_REFRESH = 0; private static final int MENU_CONTACT = 1; private static final int MENU_PINGS = 2; private static final int DIALOG_CONTACTS = 0; private StateHolder mStateHolder; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.user_details_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTasks(this); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(EXTRA_USER_PARCEL)) { Log.i(TAG, "Starting " + TAG + " with full user parcel."); User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL); mStateHolder.setUser(user); mStateHolder.setLoadType(LOAD_TYPE_USER_PARTIAL); } else if (getIntent().hasExtra(EXTRA_USER_ID)) { Log.i(TAG, "Starting " + TAG + " with user ID."); User user = new User(); user.setId(getIntent().getExtras().getString(EXTRA_USER_ID)); mStateHolder.setUser(user); mStateHolder.setLoadType(LOAD_TYPE_USER_ID); } else { Log.i(TAG, "Starting " + TAG + " as logged-in user."); User user = new User(); user.setId(null); mStateHolder.setUser(user); mStateHolder.setLoadType(LOAD_TYPE_USER_ID); } mStateHolder.setIsLoggedInUser( mStateHolder.getUser().getId() == null || mStateHolder.getUser().getId().equals( ((Foursquared) getApplication()).getUserId())); } mHandler = new Handler(); mRrm = ((Foursquared) getApplication()).getRemoteResourceManager(); mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); ensureUi(); if (mStateHolder.getLoadType() != LOAD_TYPE_USER_FULL && !mStateHolder.getIsRunningUserDetailsTask() && !mStateHolder.getRanOnce()) { mStateHolder.startTaskUserDetails(this, mStateHolder.getUser().getId()); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mHandler.removeCallbacks(mRunnableUpdateUserPhoto); RemoteResourceManager rrm = ((Foursquared) getApplication()).getRemoteResourceManager(); rrm.deleteObserver(mResourcesObserver); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } private void ensureUi() { int sdk = UiUtil.sdkVersion(); View viewProgressBar = findViewById(R.id.venueActivityDetailsProgress); TextView tvUsername = (TextView)findViewById(R.id.userDetailsActivityUsername); TextView tvLastSeen = (TextView)findViewById(R.id.userDetailsActivityHometownOrLastSeen); Button btnFriend = (Button)findViewById(R.id.userDetailsActivityFriendButton); View viewMayorships = findViewById(R.id.userDetailsActivityGeneralMayorships); View viewBadges = findViewById(R.id.userDetailsActivityGeneralBadges); View viewTips = findViewById(R.id.userDetailsActivityGeneralTips); TextView tvMayorships = (TextView)findViewById(R.id.userDetailsActivityGeneralMayorshipsValue); TextView tvBadges = (TextView)findViewById(R.id.userDetailsActivityGeneralBadgesValue); TextView tvTips = (TextView)findViewById(R.id.userDetailsActivityGeneralTipsValue); ImageView ivMayorshipsChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralMayorshipsChevron); ImageView ivBadgesChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralBadgesChevron); ImageView ivTipsChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralTipsChevron); View viewCheckins = findViewById(R.id.userDetailsActivityCheckins); View viewFriendsFollowers = findViewById(R.id.userDetailsActivityFriendsFollowers); View viewAddFriends = findViewById(R.id.userDetailsActivityAddFriends); View viewTodos = findViewById(R.id.userDetailsActivityTodos); View viewFriends = findViewById(R.id.userDetailsActivityFriends); TextView tvCheckins = (TextView)findViewById(R.id.userDetailsActivityCheckinsText); ImageView ivCheckinsChevron = (ImageView)findViewById(R.id.userDetailsActivityCheckinsChevron); TextView tvFriendsFollowers = (TextView)findViewById(R.id.userDetailsActivityFriendsFollowersText); ImageView ivFriendsFollowersChevron = (ImageView)findViewById(R.id.userDetailsActivityFriendsFollowersChevron); TextView tvTodos = (TextView)findViewById(R.id.userDetailsActivityTodosText); ImageView ivTodos = (ImageView)findViewById(R.id.userDetailsActivityTodosChevron); TextView tvFriends = (TextView)findViewById(R.id.userDetailsActivityFriendsText); ImageView ivFriends = (ImageView)findViewById(R.id.userDetailsActivityFriendsChevron); PhotoStrip psFriends = (PhotoStrip)findViewById(R.id.userDetailsActivityFriendsPhotos); viewProgressBar.setVisibility(View.VISIBLE); tvUsername.setText(""); tvLastSeen.setText(""); viewMayorships.setFocusable(false); viewBadges.setFocusable(false); viewTips.setFocusable(false); tvMayorships.setText("0"); tvBadges.setText("0"); tvTips.setText("0"); ivMayorshipsChevron.setVisibility(View.INVISIBLE); ivBadgesChevron.setVisibility(View.INVISIBLE); ivTipsChevron.setVisibility(View.INVISIBLE); btnFriend.setVisibility(View.INVISIBLE); viewCheckins.setFocusable(false); viewFriendsFollowers.setFocusable(false); viewAddFriends.setFocusable(false); viewTodos.setFocusable(false); viewFriends.setFocusable(false); viewCheckins.setVisibility(View.GONE); viewFriendsFollowers.setVisibility(View.GONE); viewAddFriends.setVisibility(View.GONE); viewTodos.setVisibility(View.GONE); viewFriends.setVisibility(View.GONE); ivCheckinsChevron.setVisibility(View.INVISIBLE); ivFriendsFollowersChevron.setVisibility(View.INVISIBLE); ivTodos.setVisibility(View.INVISIBLE); ivFriends.setVisibility(View.INVISIBLE); psFriends.setVisibility(View.GONE); tvCheckins.setText(""); tvFriendsFollowers.setText(""); tvTodos.setText(""); tvFriends.setText(""); if (mStateHolder.getLoadType() >= LOAD_TYPE_USER_PARTIAL) { User user = mStateHolder.getUser(); ensureUiPhoto(user); if (mStateHolder.getIsLoggedInUser() || UserUtils.isFriend(user)) { tvUsername.setText(StringFormatters.getUserFullName(user)); } else { tvUsername.setText(StringFormatters.getUserAbbreviatedName(user)); } tvLastSeen.setText(user.getHometown()); if (mStateHolder.getIsLoggedInUser() || UserUtils.isFriend(user) || UserUtils.isFriendStatusPendingThem(user) || UserUtils.isFriendStatusFollowingThem(user)) { btnFriend.setVisibility(View.INVISIBLE); } else if (UserUtils.isFriendStatusPendingYou(user)) { btnFriend.setVisibility(View.VISIBLE); btnFriend.setText(getString(R.string.user_details_activity_friend_confirm)); btnFriend.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mStateHolder.startTaskFriend(UserDetailsActivity.this, StateHolder.TASK_FRIEND_ACCEPT); } }); } else { btnFriend.setVisibility(View.VISIBLE); btnFriend.setText(getString(R.string.user_details_activity_friend_add)); btnFriend.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { view.setEnabled(false); mStateHolder.startTaskFriend(UserDetailsActivity.this, StateHolder.TASK_FRIEND_ADD); } }); } if (mStateHolder.getLoadType() >= LOAD_TYPE_USER_FULL) { viewProgressBar.setVisibility(View.GONE); tvMayorships.setText(String.valueOf(user.getMayorCount())); tvBadges.setText(String.valueOf(user.getBadgeCount())); tvTips.setText(String.valueOf(user.getTipCount())); if (user.getCheckin() != null && user.getCheckin().getVenue() != null) { String fixed = getResources().getString(R.string.user_details_activity_last_seen); String full = fixed + " " + user.getCheckin().getVenue().getName(); CharacterStyle bold = new StyleSpan(Typeface.BOLD); SpannableString ss = new SpannableString(full); ss.setSpan(bold, fixed.length(), full.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tvLastSeen.setText(ss); tvLastSeen.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startVenueActivity(); } }); } if (user.getMayorships() != null && user.getMayorships().size() > 0) { viewMayorships.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startMayorshipsActivity(); } }); viewMayorships.setFocusable(true); if (sdk > 3) { ivMayorshipsChevron.setVisibility(View.VISIBLE); } } if (user.getBadges() != null && user.getBadges().size() > 0) { viewBadges.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startBadgesActivity(); } }); viewBadges.setFocusable(true); if (sdk > 3) { ivBadgesChevron.setVisibility(View.VISIBLE); } } if (user.getTipCount() > 0) { viewTips.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startTipsActivity(); } }); viewTips.setFocusable(true); if (sdk > 3) { ivTipsChevron.setVisibility(View.VISIBLE); } } // The rest of the items depend on if we're viewing ourselves or not. if (mStateHolder.getIsLoggedInUser()) { viewCheckins.setVisibility(View.VISIBLE); viewFriendsFollowers.setVisibility(View.VISIBLE); viewAddFriends.setVisibility(View.VISIBLE); tvCheckins.setText( user.getCheckinCount() == 1 ? getResources().getString( R.string.user_details_activity_checkins_text_single, user.getCheckinCount()) : getResources().getString( R.string.user_details_activity_checkins_text_plural, user.getCheckinCount())); if (user.getCheckinCount() > 0) { viewCheckins.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startCheckinsActivity(); } }); viewCheckins.setFocusable(true); ivCheckinsChevron.setVisibility(View.VISIBLE); } if (user.getFollowerCount() > 0) { tvFriendsFollowers.setText( user.getFollowerCount() == 1 ? getResources().getString( R.string.user_details_activity_friends_followers_text_celeb_single, user.getFollowerCount()) : getResources().getString( R.string.user_details_activity_friends_followers_text_celeb_plural, user.getFollowerCount())); if (user.getFriendCount() > 0) { tvFriendsFollowers.setText(tvFriendsFollowers.getText() + ", "); } } tvFriendsFollowers.setText(tvFriendsFollowers.getText().toString() + (user.getFriendCount() == 1 ? getResources().getString( R.string.user_details_activity_friends_followers_text_single, user.getFriendCount()) : getResources().getString( R.string.user_details_activity_friends_followers_text_plural, user.getFriendCount()))); if (user.getFollowerCount() + user.getFriendCount() > 0) { viewFriendsFollowers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startFriendsFollowersActivity(); } }); viewFriendsFollowers.setFocusable(true); ivFriendsFollowersChevron.setVisibility(View.VISIBLE); } viewAddFriends.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startAddFriendsActivity(); } }); viewAddFriends.setFocusable(true); } else { viewTodos.setVisibility(View.VISIBLE); viewFriends.setVisibility(View.VISIBLE); tvTodos.setText( user.getTodoCount() == 1 ? getResources().getString( R.string.user_details_activity_todos_text_single, user.getTodoCount()) : getResources().getString( R.string.user_details_activity_todos_text_plural, user.getTodoCount())); if (user.getTodoCount() > 0 && UserUtils.isFriend(user)) { viewTodos.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startTodosActivity(); } }); viewTodos.setFocusable(true); ivTodos.setVisibility(View.VISIBLE); } tvFriends.setText( user.getFriendCount() == 1 ? getResources().getString( R.string.user_details_activity_friends_text_single, user.getFriendCount()) : getResources().getString( R.string.user_details_activity_friends_text_plural, user.getFriendCount())); int friendsInCommon = user.getFriendsInCommon() == null ? 0 : user.getFriendsInCommon().size(); if (friendsInCommon > 0) { tvFriends.setText(tvFriends.getText().toString() + (friendsInCommon == 1 ? getResources().getString( R.string.user_details_activity_friends_in_common_text_single, friendsInCommon) : getResources().getString( R.string.user_details_activity_friends_in_common_text_plural, friendsInCommon))); } if (user.getFriendCount() > 0) { viewFriends.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startFriendsInCommonActivity(); } }); viewFriends.setFocusable(true); ivFriends.setVisibility(View.VISIBLE); } if (friendsInCommon > 0) { psFriends.setVisibility(View.VISIBLE); psFriends.setUsersAndRemoteResourcesManager(user.getFriendsInCommon(), mRrm); } else { tvFriends.setPadding(tvFriends.getPaddingLeft(), tvTodos.getPaddingTop(), tvFriends.getPaddingRight(), tvTodos.getPaddingBottom()); } } } else { // Haven't done a full load. if (mStateHolder.getRanOnce()) { viewProgressBar.setVisibility(View.GONE); } } } else { // Haven't done a full load. if (mStateHolder.getRanOnce()) { viewProgressBar.setVisibility(View.GONE); } } // Regardless of load state, if running a task, show titlebar progress bar. if (mStateHolder.getIsTaskRunning()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } // Disable friend button if running friend task. if (mStateHolder.getIsRunningFriendTask()) { btnFriend.setEnabled(false); } else { btnFriend.setEnabled(true); } } private void ensureUiPhoto(User user) { ImageView ivPhoto = (ImageView)findViewById(R.id.userDetailsActivityPhoto); if (user == null || user.getPhoto() == null) { ivPhoto.setImageResource(R.drawable.blank_boy); return; } Uri uriPhoto = Uri.parse(user.getPhoto()); if (mRrm.exists(uriPhoto)) { try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(user .getPhoto()))); ivPhoto.setImageBitmap(bitmap); } catch (IOException e) { setUserPhotoMissing(ivPhoto, user); } } else { mRrm.request(uriPhoto); setUserPhotoMissing(ivPhoto, user); } ivPhoto.postInvalidate(); ivPhoto.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mStateHolder.getLoadType() == LOAD_TYPE_USER_FULL) { User user = mStateHolder.getUser(); // If "_thumbs" exists, remove it to get the url of the // full-size image. String photoUrl = user.getPhoto().replace("_thumbs", ""); // If we're viewing our own page, clicking the thumbnail should send the user // to our built-in image viewer. Here we can give them the option of setting // a new photo for themselves. Intent intent = new Intent(UserDetailsActivity.this, FetchImageForViewIntent.class); intent.putExtra(FetchImageForViewIntent.IMAGE_URL, photoUrl); intent.putExtra(FetchImageForViewIntent.PROGRESS_BAR_MESSAGE, getResources() .getString(R.string.user_activity_fetch_full_image_message)); if (mStateHolder.getIsLoggedInUser()) { intent.putExtra(FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION, false); startActivityForResult(intent, ACTIVITY_REQUEST_CODE_FETCH_IMAGE); } else { startActivity(intent); } } } }); } private void setUserPhotoMissing(ImageView ivPhoto, User user) { if (Foursquare.MALE.equals(user.getGender())) { ivPhoto.setImageResource(R.drawable.blank_boy); } else { ivPhoto.setImageResource(R.drawable.blank_girl); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTasks(null); return mStateHolder; } private void startBadgesActivity() { if (mStateHolder.getUser() != null) { Intent intent = new Intent(UserDetailsActivity.this, BadgesActivity.class); intent.putParcelableArrayListExtra(BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL, mStateHolder.getUser().getBadges()); intent.putExtra(BadgesActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); startActivity(intent); } } private void startMayorshipsActivity() { if (mStateHolder.getUser() != null) { Intent intent = new Intent(UserDetailsActivity.this, UserMayorshipsActivity.class); intent.putExtra(UserMayorshipsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId()); intent.putExtra(UserMayorshipsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); startActivity(intent); } } private void startCheckinsActivity() { Intent intent = new Intent(UserDetailsActivity.this, UserHistoryActivity.class); intent.putExtra(UserHistoryActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); startActivity(intent); } private void startFriendsFollowersActivity() { User user = mStateHolder.getUser(); Intent intent = null; if (user.getFollowerCount() > 0) { intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsFollowersActivity.class); intent.putExtra(UserDetailsFriendsFollowersActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); } else { intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsActivity.class); intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId()); intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); } startActivity(intent); } private void startAddFriendsActivity() { Intent intent = new Intent(UserDetailsActivity.this, AddFriendsActivity.class); startActivity(intent); } private void startFriendsInCommonActivity() { User user = mStateHolder.getUser(); Intent intent = null; if (user.getFriendsInCommon() != null && user.getFriendsInCommon().size() > 0) { intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsInCommonActivity.class); intent.putExtra(UserDetailsFriendsInCommonActivity.EXTRA_USER_PARCEL, mStateHolder.getUser()); } else { intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsActivity.class); intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId()); intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); } startActivity(intent); } private void startTodosActivity() { Intent intent = new Intent(UserDetailsActivity.this, TodosActivity.class); intent.putExtra(TodosActivity.INTENT_EXTRA_USER_ID, mStateHolder.getUser().getId()); intent.putExtra(TodosActivity.INTENT_EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); startActivity(intent); } private void startTipsActivity() { Intent intent = new Intent(UserDetailsActivity.this, UserDetailsTipsActivity.class); intent.putExtra(UserDetailsTipsActivity.INTENT_EXTRA_USER_ID, mStateHolder.getUser().getId()); intent.putExtra(UserDetailsTipsActivity.INTENT_EXTRA_USER_NAME, mStateHolder.getUser().getFirstname()); startActivity(intent); } private void startVenueActivity() { User user = mStateHolder.getUser(); if (user.getCheckin() != null && user.getCheckin().getVenue() != null) { Intent intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, user.getCheckin().getVenue()); startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); if (mStateHolder.getIsLoggedInUser()) { MenuUtils.addPreferencesToMenu(this, menu); } else { menu.add(Menu.NONE, MENU_CONTACT, Menu.NONE, R.string.user_details_activity_friends_menu_contact) .setIcon(R.drawable.ic_menu_user_contact); if (UserUtils.isFriend(mStateHolder.getUser())) { menu.add(Menu.NONE, MENU_PINGS, Menu.NONE, R.string.user_details_activity_friends_menu_pings) .setIcon(android.R.drawable.ic_menu_rotate); } } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { User user = mStateHolder.getUser(); MenuItem refresh = menu.findItem(MENU_REFRESH); MenuItem contact = menu.findItem(MENU_CONTACT); MenuItem pings = menu.findItem(MENU_PINGS); if (!mStateHolder.getIsRunningUserDetailsTask()) { refresh.setEnabled(true); if (contact != null) { boolean contactEnabled = !TextUtils.isEmpty(user.getFacebook()) || !TextUtils.isEmpty(user.getTwitter()) || !TextUtils.isEmpty(user.getEmail()) || !TextUtils.isEmpty(user.getPhone()); contact.setEnabled(contactEnabled); } if (pings != null) { pings.setEnabled(true); } } else { refresh.setEnabled(false); if (contact != null) { contact.setEnabled(false); } if (pings != null) { pings.setEnabled(false); } } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTaskUserDetails(this, mStateHolder.getUser().getId()); return true; case MENU_CONTACT: showDialog(DIALOG_CONTACTS); return true; case MENU_PINGS: Intent intentPings = new Intent(this, UserDetailsPingsActivity.class); intentPings.putExtra(UserDetailsPingsActivity.EXTRA_USER_PARCEL, mStateHolder.getUser()); startActivityForResult(intentPings, ACTIVITY_REQUEST_CODE_PINGS); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case ACTIVITY_REQUEST_CODE_PINGS: if (resultCode == Activity.RESULT_OK) { User user = (User)data.getParcelableExtra(UserDetailsPingsActivity.EXTRA_USER_RETURNED); if (user != null) { mStateHolder.getUser().getSettings().setGetPings(user.getSettings().getGetPings()); } } break; case ACTIVITY_REQUEST_CODE_FETCH_IMAGE: if (resultCode == Activity.RESULT_OK) { String imagePath = data.getStringExtra(FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED); if (mStateHolder.getIsLoggedInUser() && !TextUtils.isEmpty(imagePath)) { Intent intent = new Intent(this, FullSizeImageActivity.class); intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, imagePath); intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_ALLOW_SET_NEW_PHOTO, true); startActivityForResult(intent, ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE); } } break; case ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE: if (resultCode == Activity.RESULT_OK) { String imageUrl = data.getStringExtra(FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_URL); if (!TextUtils.isEmpty(imageUrl)) { mStateHolder.getUser().setPhoto(imageUrl); ensureUiPhoto(mStateHolder.getUser()); } } break; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CONTACTS: final UserContactAdapter adapter = new UserContactAdapter(this, mStateHolder.getUser()); AlertDialog dlgInfo = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.user_details_activity_friends_menu_contact)) .setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int pos) { UserContactAdapter.Action action = (UserContactAdapter.Action)adapter.getItem(pos); switch (action.getActionId()) { case UserContactAdapter.Action.ACTION_ID_SMS: UiUtil.startSmsIntent(UserDetailsActivity.this, mStateHolder.getUser().getPhone()); break; case UserContactAdapter.Action.ACTION_ID_EMAIL: UiUtil.startEmailIntent(UserDetailsActivity.this, mStateHolder.getUser().getEmail()); break; case UserContactAdapter.Action.ACTION_ID_PHONE: UiUtil.startDialer(UserDetailsActivity.this, mStateHolder.getUser().getPhone()); break; case UserContactAdapter.Action.ACTION_ID_TWITTER: UiUtil.startWebIntent(UserDetailsActivity.this, "http://www.twitter.com/" + mStateHolder.getUser().getTwitter()); break; case UserContactAdapter.Action.ACTION_ID_FACEBOOK: UiUtil.startWebIntent(UserDetailsActivity.this, "http://www.facebook.com/profile.php?id=" + mStateHolder.getUser().getFacebook()); break; } } }) .create(); return dlgInfo; } return null; } private void onUserDetailsTaskComplete(User user, Exception ex) { mStateHolder.setIsRunningUserDetailsTask(false); mStateHolder.setRanOnce(true); if (user != null) { mStateHolder.setUser(user); mStateHolder.setLoadType(LOAD_TYPE_USER_FULL); } else if (ex != null) { NotificationsUtil.ToastReasonForFailure(this, ex); } else { Toast.makeText(this, "A surprising new error has occurred!", Toast.LENGTH_SHORT).show(); } ensureUi(); } /** * Even if the caller supplies us with a User object parcelable, it won't * have all the badge etc extra info in it. As soon as the activity starts, * we launch this task to fetch a full user object, and merge it with * whatever is already supplied in mUser. */ private static class UserDetailsTask extends AsyncTask<String, Void, User> { private UserDetailsActivity mActivity; private Exception mReason; public UserDetailsTask(UserDetailsActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.ensureUi(); } @Override protected User doInBackground(String... params) { try { return ((Foursquared) mActivity.getApplication()).getFoursquare().user( params[0], true, true, true, LocationUtils.createFoursquareLocation(((Foursquared) mActivity .getApplication()).getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onUserDetailsTaskComplete(user, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onUserDetailsTaskComplete(null, mReason); } } public void setActivity(UserDetailsActivity activity) { mActivity = activity; } } private void onFriendTaskComplete(User user, int action, Exception ex) { mStateHolder.setIsRunningFriendTask(false); // The api isn't returning an updated friend status flag here, so we'll // overwrite it manually for now, assuming success if the user object // was not null. User userCurrent = mStateHolder.getUser(); if (user != null) { switch (action) { case StateHolder.TASK_FRIEND_ACCEPT: userCurrent.setFirstname(user.getFirstname()); userCurrent.setLastname(user.getLastname()); userCurrent.setFriendstatus("friend"); break; case StateHolder.TASK_FRIEND_ADD: userCurrent.setFriendstatus("pendingthem"); break; } } else { NotificationsUtil.ToastReasonForFailure(this, ex); } ensureUi(); } private static class FriendTask extends AsyncTask<Void, Void, User> { private UserDetailsActivity mActivity; private String mUserId; private int mAction; private Exception mReason; public FriendTask(UserDetailsActivity activity, String userId, int action) { mActivity = activity; mUserId = userId; mAction = action; } @Override protected void onPreExecute() { mActivity.ensureUi(); } @Override protected User doInBackground(Void... params) { Foursquare foursquare = ((Foursquared) mActivity.getApplication()).getFoursquare(); try { switch (mAction) { case StateHolder.TASK_FRIEND_ACCEPT: return foursquare.friendApprove(mUserId); case StateHolder.TASK_FRIEND_ADD: return foursquare.friendSendrequest(mUserId); default: throw new FoursquareException("Unknown action type supplied."); } } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onFriendTaskComplete(user, mAction, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFriendTaskComplete(null, mAction, mReason); } } public void setActivity(UserDetailsActivity activity) { mActivity = activity; } } private static class StateHolder { public static final int TASK_FRIEND_ACCEPT = 0; public static final int TASK_FRIEND_ADD = 1; private User mUser; private boolean mIsLoggedInUser; private UserDetailsTask mTaskUserDetails; private boolean mIsRunningUserDetailsTask; private boolean mRanOnce; private int mLoadType; private FriendTask mTaskFriend; private boolean mIsRunningFriendTask; public StateHolder() { mIsRunningUserDetailsTask = false; mIsRunningFriendTask = false; mIsLoggedInUser = false; mRanOnce = false; mLoadType = LOAD_TYPE_USER_NONE; } public boolean getIsLoggedInUser() { return mIsLoggedInUser; } public void setIsLoggedInUser(boolean isLoggedInUser) { mIsLoggedInUser = isLoggedInUser; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public int getLoadType() { return mLoadType; } public void setLoadType(int loadType) { mLoadType = loadType; } public void startTaskUserDetails(UserDetailsActivity activity, String userId) { if (!mIsRunningUserDetailsTask) { mIsRunningUserDetailsTask = true; mTaskUserDetails = new UserDetailsTask(activity); mTaskUserDetails.execute(userId); } } public void startTaskFriend(UserDetailsActivity activity, int action) { if (!mIsRunningFriendTask) { mIsRunningFriendTask = true; mTaskFriend = new FriendTask(activity, mUser.getId(), action); mTaskFriend.execute(); } } public void setActivityForTasks(UserDetailsActivity activity) { if (mTaskUserDetails != null) { mTaskUserDetails.setActivity(activity); } if (mTaskFriend != null) { mTaskFriend.setActivity(activity); } } public boolean getIsRunningUserDetailsTask() { return mIsRunningUserDetailsTask; } public void setIsRunningUserDetailsTask(boolean isRunning) { mIsRunningUserDetailsTask = isRunning; } public boolean getRanOnce() { return mRanOnce; } public void setRanOnce(boolean ranOnce) { mRanOnce = ranOnce; } public boolean getIsRunningFriendTask() { return mIsRunningFriendTask; } public void setIsRunningFriendTask(boolean isRunning) { mIsRunningFriendTask = isRunning; } public void cancelTasks() { if (mTaskUserDetails != null) { mTaskUserDetails.setActivity(null); mTaskUserDetails.cancel(true); } if (mTaskFriend != null) { mTaskFriend.setActivity(null); mTaskFriend.cancel(true); } } public boolean getIsTaskRunning() { return mIsRunningUserDetailsTask || mIsRunningFriendTask; } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mRunnableUpdateUserPhoto); } } private Runnable mRunnableUpdateUserPhoto = new Runnable() { @Override public void run() { ensureUiPhoto(mStateHolder.getUser()); } }; }
1031868817-hws
main/src/com/joelapenna/foursquared/UserDetailsActivity.java
Java
asf20
45,842
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.widget.CategoryPickerAdapter; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.AdapterView.OnItemClickListener; import java.io.IOException; /** * Presents the user with a list of all available categories from foursquare * that they can use to label a new venue. * * @date March 7, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class CategoryPickerDialog extends Dialog { private static final String TAG = "FriendRequestsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private Foursquared mApplication; private Group<Category> mCategories; private ViewFlipper mViewFlipper; private Category mChosenCategory; private int mFirstDialogHeight; public CategoryPickerDialog(Context context, Group<Category> categories, Foursquared application) { super(context); mApplication = application; mCategories = categories; mChosenCategory = null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.category_picker_dialog); setTitle(getContext().getResources().getString(R.string.category_picket_dialog_title)); mViewFlipper = (ViewFlipper) findViewById(R.id.categoryPickerViewFlipper); mFirstDialogHeight = -1; // By default we always have a top-level page. Category root = new Category(); root.setNodeName("root"); root.setChildCategories(mCategories); mViewFlipper.addView(makePage(root)); } private View makePage(Category category) { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.category_picker_page, null); CategoryPickerPage page = new CategoryPickerPage(); page.ensureUI(view, mPageListItemSelected, category, mApplication .getRemoteResourceManager()); view.setTag(page); if (mViewFlipper.getChildCount() == 1 && mFirstDialogHeight == -1) { mFirstDialogHeight = mViewFlipper.getChildAt(0).getHeight(); } if (mViewFlipper.getChildCount() > 0) { view.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, mFirstDialogHeight)); } return view; } @Override protected void onStop() { super.onStop(); cleanupPageAdapters(); } private void cleanupPageAdapters() { for (int i = 0; i < mViewFlipper.getChildCount(); i++) { CategoryPickerPage page = (CategoryPickerPage) mViewFlipper.getChildAt(i).getTag(); page.cleanup(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mViewFlipper.getChildCount() > 1) { mViewFlipper.removeViewAt(mViewFlipper.getChildCount() - 1); return true; } break; } return super.onKeyDown(keyCode, event); } /** * After the user has dismissed the dialog, the parent activity can use this * to see which category they picked, if any. Will return null if no * category was picked. */ public Category getChosenCategory() { return mChosenCategory; } private static class CategoryPickerPage { private CategoryPickerAdapter mListAdapter; private Category mCategory; private PageListItemSelected mClickListener; public void ensureUI(View view, PageListItemSelected clickListener, Category category, RemoteResourceManager rrm) { mCategory = category; mClickListener = clickListener; mListAdapter = new CategoryPickerAdapter(view.getContext(), rrm, category); ListView listview = (ListView) view.findViewById(R.id.categoryPickerListView); listview.setAdapter(mListAdapter); listview.setOnItemClickListener(mOnItemClickListener); LinearLayout llRootCategory = (LinearLayout) view .findViewById(R.id.categoryPickerRootCategoryButton); if (category.getNodeName().equals("root") == false) { ImageView iv = (ImageView) view.findViewById(R.id.categoryPickerIcon); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(Uri .parse(category.getIconUrl()))); iv.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.e(TAG, "Error loading category icon from disk.", e); } TextView tv = (TextView) view.findViewById(R.id.categoryPickerName); tv.setText(category.getNodeName()); llRootCategory.setClickable(true); llRootCategory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mClickListener.onCategorySelected(mCategory); } }); } else { llRootCategory.setVisibility(View.GONE); } } public void cleanup() { mListAdapter.removeObserver(); } private OnItemClickListener mOnItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { mClickListener.onPageListItemSelcected((Category) mListAdapter.getItem(position)); } }; } private PageListItemSelected mPageListItemSelected = new PageListItemSelected() { @Override public void onPageListItemSelcected(Category category) { // If the item has children, create a new page for it. if (category.getChildCategories() != null && category.getChildCategories().size() > 0) { mViewFlipper.addView(makePage(category)); mViewFlipper.showNext(); } else { // This is a leaf node, finally the user's selection. Record the // category // then cancel ourselves, parent activity should pick us up // after that. mChosenCategory = category; cancel(); } } @Override public void onCategorySelected(Category category) { // The user has chosen the category parent listed at the top of the // current page. mChosenCategory = category; cancel(); } }; private interface PageListItemSelected { public void onPageListItemSelcected(Category category); public void onCategorySelected(Category category); } }
1031868817-hws
main/src/com/joelapenna/foursquared/CategoryPickerDialog.java
Java
asf20
7,738
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.StringFormatters; /** * Lets the user add a todo for a venue. * * @date September 16, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class AddTodoActivity extends Activity { private static final String TAG = "AddTodoActivity"; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".AddTodoActivity.INTENT_EXTRA_VENUE"; public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME + ".AddTodoActivity.EXTRA_TODO_RETURNED"; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_todo_activity); StateHolder holder = (StateHolder) getLastNonConfigurationInstance(); if (holder != null) { mStateHolder = holder; mStateHolder.setActivityForTasks(this); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "AddTodoActivity must be given a venue parcel as intent extras."); finish(); return; } } ensureUi(); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTasks(null); return mStateHolder; } private void ensureUi() { TextView tvVenueName = (TextView)findViewById(R.id.addTodoActivityVenueName); tvVenueName.setText(mStateHolder.getVenue().getName()); TextView tvVenueAddress = (TextView)findViewById(R.id.addTodoActivityVenueAddress); tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity( mStateHolder.getVenue())); Button btn = (Button) findViewById(R.id.addTodoActivityButton); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText et = (EditText)findViewById(R.id.addTodoActivityText); String text = et.getText().toString(); mStateHolder.startTaskAddTodo(AddTodoActivity.this, mStateHolder.getVenue().getId(), text); } }); if (mStateHolder.getIsRunningTaskVenue()) { startProgressBar(); } } private void startProgressBar() { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, "", getResources().getString(R.string.add_tip_todo_activity_progress_message)); mDlgProgress.setCancelable(true); mDlgProgress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { Log.e(TAG, "User cancelled add todo."); mStateHolder.cancelTasks(); } }); } mDlgProgress.show(); setProgressBarIndeterminateVisibility(true); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } setProgressBarIndeterminateVisibility(false); } private static class TaskAddTodo extends AsyncTask<Void, Void, Todo> { private AddTodoActivity mActivity; private String mVenueId; private String mTipText; private Exception mReason; public TaskAddTodo(AddTodoActivity activity, String venueId, String tipText) { mActivity = activity; mVenueId = venueId; mTipText = tipText; } @Override protected void onPreExecute() { mActivity.startProgressBar(); } @Override protected Todo doInBackground(Void... params) { try { // If the user entered optional text, we need to use one endpoint, // if not, we need to use mark/todo. Foursquared foursquared = (Foursquared)mActivity.getApplication(); Todo todo = null; if (!TextUtils.isEmpty(mTipText)) { // The returned tip won't have the user object or venue attached to it // as part of the response. The venue is the parent venue and the user // is the logged-in user. Tip tip = foursquared.getFoursquare().addTip( mVenueId, mTipText, "todo", LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); // So fetch the full tip for convenience. Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId()); // The addtip API returns a tip instead of a todo, unlike the mark/todo endpoint, // so we create a dummy todo object for now to wrap the tip. String now = StringFormatters.createServerDateFormatV1(); todo = new Todo(); todo.setId("id_" + now); todo.setCreated(now); todo.setTip(tipFull); Log.i(TAG, "Added todo with wrapper ID: " + todo.getId()); } else { // No text, so in this case we need to mark the venue itself as a todo. todo = foursquared.getFoursquare().markTodoVenue(mVenueId); Log.i(TAG, "Added todo with ID: " + todo.getId()); } return todo; } catch (Exception e) { Log.e(TAG, "Error adding tip.", e); mReason = e; } return null; } @Override protected void onPostExecute(Todo todo) { mActivity.stopProgressBar(); mActivity.mStateHolder.setIsRunningTaskAddTip(false); if (todo != null) { Intent intent = new Intent(); intent.putExtra(EXTRA_TODO_RETURNED, todo); mActivity.setResult(Activity.RESULT_OK, intent); mActivity.finish(); } else { NotificationsUtil.ToastReasonForFailure(mActivity, mReason); mActivity.setResult(Activity.RESULT_CANCELED); mActivity.finish(); } } @Override protected void onCancelled() { mActivity.stopProgressBar(); mActivity.setResult(Activity.RESULT_CANCELED); mActivity.finish(); } public void setActivity(AddTodoActivity activity) { mActivity = activity; } } private static final class StateHolder { private Venue mVenue; private TaskAddTodo mTaskAddTodo; private boolean mIsRunningTaskAddTip; public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } public boolean getIsRunningTaskVenue() { return mIsRunningTaskAddTip; } public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) { mIsRunningTaskAddTip = isRunningTaskAddTip; } public void startTaskAddTodo(AddTodoActivity activity, String venueId, String text) { mIsRunningTaskAddTip = true; mTaskAddTodo = new TaskAddTodo(activity, venueId, text); mTaskAddTodo.execute(); } public void setActivityForTasks(AddTodoActivity activity) { if (mTaskAddTodo != null) { mTaskAddTodo.setActivity(activity); } } public void cancelTasks() { if (mTaskAddTodo != null) { mTaskAddTodo.cancel(true); } } } }
1031868817-hws
main/src/com/joelapenna/foursquared/AddTodoActivity.java
Java
asf20
8,752
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.providers; import android.content.SearchRecentSuggestionsProvider; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueQuerySuggestionsProvider extends SearchRecentSuggestionsProvider { public static final String AUTHORITY = "com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider"; public static final int MODE = DATABASE_MODE_QUERIES; public VenueQuerySuggestionsProvider() { super(); setupSuggestions(AUTHORITY, MODE); } }
1031868817-hws
main/src/com/joelapenna/foursquared/providers/VenueQuerySuggestionsProvider.java
Java
asf20
566
/** * Copyright 2010 Tauno Talimaa */ package com.joelapenna.foursquared.providers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.BestLocationListener; import com.joelapenna.foursquared.location.LocationUtils; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.util.Log; import java.io.IOException; /** * A ContentProvider for Foursquare search results. * * @author Tauno Talimaa (tauntz@gmail.com) */ public class GlobalSearchProvider extends ContentProvider { // TODO: Implement search for friends by name/phone number/twitter ID when // API is implemented in Foursquare.java private static final String TAG = GlobalSearchProvider.class.getSimpleName(); private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final String[] QSB_COLUMNS = { "_id", SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING, SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; private static final int URI_TYPE_QUERY = 1; private static final int URI_TYPE_SHORTCUT = 2; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_TYPE_QUERY); sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", URI_TYPE_SHORTCUT); } public static final String VENUE_DIRECTORY = "venue"; public static final String FRIEND_DIRECTORY = "friend"; // TODO: Use the argument from SUGGEST_PARAMETER_LIMIT from the Uri passed // to query() instead of the hardcoded value (this is available starting // from API level 5) private static final int VENUE_QUERY_LIMIT = 30; private Foursquare mFoursquare; @Override public boolean onCreate() { synchronized (this) { if (mFoursquare == null) mFoursquare = Foursquared.createFoursquare(getContext()); } return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String query = uri.getLastPathSegment(); MatrixCursor cursor = new MatrixCursor(QSB_COLUMNS); switch (sUriMatcher.match(uri)) { case URI_TYPE_QUERY: if (DEBUG) { Log.d(TAG, "Global search for venue name: " + query); } Group<Group<Venue>> venueGroups; try { venueGroups = mFoursquare.venues(LocationUtils .createFoursquareLocation(getBestRecentLocation()), query, VENUE_QUERY_LIMIT); } catch (FoursquareError e) { if (DEBUG) Log.e(TAG, "Could not get venue list for query: " + query, e); return cursor; } catch (FoursquareException e) { if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e); return cursor; } catch (LocationException e) { if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e); return cursor; } catch (IOException e) { if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e); return cursor; } for (int groupIndex = 0; groupIndex < venueGroups.size(); groupIndex++) { Group<Venue> venueGroup = venueGroups.get(groupIndex); if (DEBUG) { Log.d(TAG, venueGroup.size() + " results for group: " + venueGroup.getType()); } for (int venueIndex = 0; venueIndex < venueGroup.size(); venueIndex++) { Venue venue = venueGroup.get(venueIndex); if (DEBUG) { Log.d(TAG, "Venue " + venueIndex + ": " + venue.getName() + " (" + venue.getAddress() + ")"); } cursor.addRow(new Object[] { venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon, venue.getName(), venue.getAddress(), venue.getName(), venue.getId(), "true", VENUE_DIRECTORY, venue.getId() }); } } break; case URI_TYPE_SHORTCUT: if (DEBUG) { Log.d(TAG, "Global search for venue ID: " + query); } Venue venue; try { venue = mFoursquare.venue(query, LocationUtils .createFoursquareLocation(getBestRecentLocation())); } catch (FoursquareError e) { if (DEBUG) Log.e(TAG, "Could not get venue details for venue ID: " + query, e); return cursor; } catch (LocationException e) { if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e); return cursor; } catch (FoursquareException e) { if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e); return cursor; } catch (IOException e) { if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e); return cursor; } if (DEBUG) { Log.d(TAG, "Updated venue details: " + venue.getName() + " (" + venue.getAddress() + ")"); } cursor.addRow(new Object[] { venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon, venue.getName(), venue.getAddress(), venue.getName(), venue.getId(), "true", VENUE_DIRECTORY, venue.getId() }); break; case UriMatcher.NO_MATCH: if (DEBUG) { Log.d(TAG, "No matching URI for: " + uri); } break; } return cursor; } @Override public String getType(Uri uri) { return SearchManager.SUGGEST_MIME_TYPE; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } /** * Convenience method for getting the most recent Location * * @return the most recent Locations * @throws LocationException when no recent Location could be determined */ private Location getBestRecentLocation() throws LocationException { BestLocationListener locationListener = new BestLocationListener(); locationListener.updateLastKnownLocation((LocationManager) getContext().getSystemService( Context.LOCATION_SERVICE)); Location location = locationListener.getLastKnownLocation(); if (location != null) { return location; } throw new LocationException(); } }
1031868817-hws
main/src/com/joelapenna/foursquared/providers/GlobalSearchProvider.java
Java
asf20
8,688
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.util.IconUtils; import com.joelapenna.foursquared.app.FoursquaredService; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.BestLocationListener; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.JavaLoggingHandler; import com.joelapenna.foursquared.util.NullDiskCache; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.app.Application; import android.appwidget.AppWidgetManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.location.Location; import android.location.LocationManager; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.IOException; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Foursquared extends Application { private static final String TAG = "Foursquared"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; static { Logger.getLogger("com.joelapenna.foursquare").addHandler(new JavaLoggingHandler()); Logger.getLogger("com.joelapenna.foursquare").setLevel(Level.ALL); } public static final String PACKAGE_NAME = "com.joelapenna.foursquared"; public static final String INTENT_ACTION_LOGGED_OUT = "com.joelapenna.foursquared.intent.action.LOGGED_OUT"; public static final String INTENT_ACTION_LOGGED_IN = "com.joelapenna.foursquared.intent.action.LOGGED_IN"; private String mVersion = null; private TaskHandler mTaskHandler; private HandlerThread mTaskThread; private SharedPreferences mPrefs; private RemoteResourceManager mRemoteResourceManager; private Foursquare mFoursquare; private BestLocationListener mBestLocationListener = new BestLocationListener(); private boolean mIsFirstRun; @Override public void onCreate() { Log.i(TAG, "Using Debug Server:\t" + FoursquaredSettings.USE_DEBUG_SERVER); Log.i(TAG, "Using Dumpcatcher:\t" + FoursquaredSettings.USE_DUMPCATCHER); Log.i(TAG, "Using Debug Log:\t" + DEBUG); mVersion = getVersionString(this); // Check if this is a new install by seeing if our preference file exists on disk. mIsFirstRun = checkIfIsFirstRun(); // Setup Prefs (to load dumpcatcher) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Setup some defaults in our preferences if not set yet. Preferences.setupDefaults(mPrefs, getResources()); // If we're on a high density device, request higher res images. This singleton // is picked up by the parsers to replace their icon urls with high res versions. float screenDensity = getApplicationContext().getResources().getDisplayMetrics().density; IconUtils.get().setRequestHighDensityIcons(screenDensity > 1.0f); // Setup Dumpcatcher - We've outgrown this infrastructure but we'll // leave its calls in place for the day that someone pays for some // appengine quota. // if (FoursquaredSettings.USE_DUMPCATCHER) { // Resources resources = getResources(); // new DumpcatcherHelper(Preferences.createUniqueId(mPrefs), resources); // } // Sometimes we want the application to do some work on behalf of the // Activity. Lets do that // asynchronously. mTaskThread = new HandlerThread(TAG + "-AsyncThread"); mTaskThread.start(); mTaskHandler = new TaskHandler(mTaskThread.getLooper()); // Set up storage cache. loadResourceManagers(); // Catch sdcard state changes new MediaCardStateBroadcastReceiver().register(); // Catch logins or logouts. new LoggedInOutBroadcastReceiver().register(); // Log into Foursquare, if we can. loadFoursquare(); } public boolean isReady() { return getFoursquare().hasLoginAndPassword() && !TextUtils.isEmpty(getUserId()); } public Foursquare getFoursquare() { return mFoursquare; } public String getUserId() { return Preferences.getUserId(mPrefs); } public String getUserName() { return Preferences.getUserName(mPrefs); } public String getUserEmail() { return Preferences.getUserEmail(mPrefs); } public String getUserGender() { return Preferences.getUserGender(mPrefs); } public String getVersion() { if (mVersion != null) { return mVersion; } else { return ""; } } public String getLastSeenChangelogVersion() { return Preferences.getLastSeenChangelogVersion(mPrefs); } public void storeLastSeenChangelogVersion(String version) { Preferences.storeLastSeenChangelogVersion(mPrefs.edit(), version); } public boolean getUseNativeImageViewerForFullScreenImages() { return Preferences.getUseNativeImageViewerForFullScreenImages(mPrefs); } public RemoteResourceManager getRemoteResourceManager() { return mRemoteResourceManager; } public BestLocationListener requestLocationUpdates(boolean gps) { mBestLocationListener.register( (LocationManager) getSystemService(Context.LOCATION_SERVICE), gps); return mBestLocationListener; } public BestLocationListener requestLocationUpdates(Observer observer) { mBestLocationListener.addObserver(observer); mBestLocationListener.register( (LocationManager) getSystemService(Context.LOCATION_SERVICE), true); return mBestLocationListener; } public void removeLocationUpdates() { mBestLocationListener .unregister((LocationManager) getSystemService(Context.LOCATION_SERVICE)); } public void removeLocationUpdates(Observer observer) { mBestLocationListener.deleteObserver(observer); this.removeLocationUpdates(); } public Location getLastKnownLocation() { return mBestLocationListener.getLastKnownLocation(); } public Location getLastKnownLocationOrThrow() throws LocationException { Location location = mBestLocationListener.getLastKnownLocation(); if (location == null) { throw new LocationException(); } return location; } public void clearLastKnownLocation() { mBestLocationListener.clearLastKnownLocation(); } public void requestStartService() { mTaskHandler.sendMessage( // mTaskHandler.obtainMessage(TaskHandler.MESSAGE_START_SERVICE)); } public void requestUpdateUser() { mTaskHandler.sendEmptyMessage(TaskHandler.MESSAGE_UPDATE_USER); } private void loadFoursquare() { // Try logging in and setting up foursquare oauth, then user // credentials. if (FoursquaredSettings.USE_DEBUG_SERVER) { mFoursquare = new Foursquare(Foursquare.createHttpApi("10.0.2.2:8080", mVersion, false)); } else { mFoursquare = new Foursquare(Foursquare.createHttpApi(mVersion, false)); } if (FoursquaredSettings.DEBUG) Log.d(TAG, "loadCredentials()"); String phoneNumber = mPrefs.getString(Preferences.PREFERENCE_LOGIN, null); String password = mPrefs.getString(Preferences.PREFERENCE_PASSWORD, null); mFoursquare.setCredentials(phoneNumber, password); if (mFoursquare.hasLoginAndPassword()) { sendBroadcast(new Intent(INTENT_ACTION_LOGGED_IN)); } else { sendBroadcast(new Intent(INTENT_ACTION_LOGGED_OUT)); } } /** * Provides static access to a Foursquare instance. This instance is * initiated without user credentials. * * @param context the context to use when constructing the Foursquare * instance * @return the Foursquare instace */ public static Foursquare createFoursquare(Context context) { String version = getVersionString(context); if (FoursquaredSettings.USE_DEBUG_SERVER) { return new Foursquare(Foursquare.createHttpApi("10.0.2.2:8080", version, false)); } else { return new Foursquare(Foursquare.createHttpApi(version, false)); } } /** * Constructs the version string of the application. * * @param context the context to use for getting package info * @return the versions string of the application */ private static String getVersionString(Context context) { // Get a version string for the app. try { PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(PACKAGE_NAME, 0); return PACKAGE_NAME + ":" + String.valueOf(pi.versionCode); } catch (NameNotFoundException e) { if (DEBUG) Log.d(TAG, "Could not retrieve package info", e); throw new RuntimeException(e); } } private void loadResourceManagers() { // We probably don't have SD card access if we get an // IllegalStateException. If it did, lets // at least have some sort of disk cache so that things don't npe when // trying to access the // resource managers. try { if (DEBUG) Log.d(TAG, "Attempting to load RemoteResourceManager(cache)"); mRemoteResourceManager = new RemoteResourceManager("cache"); } catch (IllegalStateException e) { if (DEBUG) Log.d(TAG, "Falling back to NullDiskCache for RemoteResourceManager"); mRemoteResourceManager = new RemoteResourceManager(new NullDiskCache()); } } public boolean getIsFirstRun() { return mIsFirstRun; } private boolean checkIfIsFirstRun() { File file = new File( "/data/data/com.joelapenna.foursquared/shared_prefs/com.joelapenna.foursquared_preferences.xml"); return !file.exists(); } /** * Set up resource managers on the application depending on SD card state. * * @author Joe LaPenna (joe@joelapenna.com) */ private class MediaCardStateBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log .d(TAG, "Media state changed, reloading resource managers:" + intent.getAction()); if (Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) { getRemoteResourceManager().shutdown(); loadResourceManagers(); } else if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) { loadResourceManagers(); } } public void register() { // Register our media card broadcast receiver so we can // enable/disable the cache as // appropriate. IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); // intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED); // intentFilter.addAction(Intent.ACTION_MEDIA_SHARED); // intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); // intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE); // intentFilter.addAction(Intent.ACTION_MEDIA_NOFS); // intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); // intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addDataScheme("file"); registerReceiver(this, intentFilter); } } private class LoggedInOutBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (INTENT_ACTION_LOGGED_IN.equals(intent.getAction())) { requestUpdateUser(); } } public void register() { // Register our media card broadcast receiver so we can // enable/disable the cache as // appropriate. IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(INTENT_ACTION_LOGGED_IN); intentFilter.addAction(INTENT_ACTION_LOGGED_OUT); registerReceiver(this, intentFilter); } } private class TaskHandler extends Handler { private static final int MESSAGE_UPDATE_USER = 1; private static final int MESSAGE_START_SERVICE = 2; public TaskHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (DEBUG) Log.d(TAG, "handleMessage: " + msg.what); switch (msg.what) { case MESSAGE_UPDATE_USER: try { // Update user info Log.d(TAG, "Updating user."); // Use location when requesting user information, if we // have it. Foursquare.Location location = LocationUtils .createFoursquareLocation(getLastKnownLocation()); User user = getFoursquare().user( null, false, false, false, location); Editor editor = mPrefs.edit(); Preferences.storeUser(editor, user); editor.commit(); if (location == null) { // Pump the location listener, we don't have a // location in our listener yet. Log.d(TAG, "Priming Location from user city."); Location primeLocation = new Location("foursquare"); // Very inaccurate, right? primeLocation.setTime(System.currentTimeMillis()); mBestLocationListener.updateLocation(primeLocation); } } catch (FoursquareError e) { if (DEBUG) Log.d(TAG, "FoursquareError", e); // TODO Auto-generated catch block } catch (FoursquareException e) { if (DEBUG) Log.d(TAG, "FoursquareException", e); // TODO Auto-generated catch block } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); // TODO Auto-generated catch block } return; case MESSAGE_START_SERVICE: Intent serviceIntent = new Intent(Foursquared.this, FoursquaredService.class); serviceIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); startService(serviceIntent); return; } } } }
1031868817-hws
main/src/com/joelapenna/foursquared/Foursquared.java
Java
asf20
16,225
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.util.VenueUtils; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.TipsListAdapter; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.List; /** * Shows tips left at a venue as a sectioned list adapter. Groups are split * into tips left by friends and tips left by everyone else. * * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -modified to start TipActivity on tip click (2010-03-25) * -added photos for tips (2010-03-25) * -refactored for new VenueActivity design (2010-09-16) */ public class VenueTipsActivity extends LoadableListActivity { public static final String TAG = "VenueTipsActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueTipsActivity.INTENT_EXTRA_VENUE"; public static final String INTENT_EXTRA_RETURN_VENUE = Foursquared.PACKAGE_NAME + ".VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE"; private static final int ACTIVITY_TIP = 500; private SeparatedListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; setPreparedResultIntent(); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "VenueTipsActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getTipsFriends().size() > 0) { TipsListAdapter adapter = new TipsListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item); adapter.setDisplayTipVenueTitles(false); adapter.setGroup(mStateHolder.getTipsFriends()); mListAdapter.addSection(getString(R.string.venue_tips_activity_section_friends, mStateHolder.getTipsFriends().size()), adapter); } TipsListAdapter adapter = new TipsListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item); adapter.setDisplayTipVenueTitles(false); adapter.setGroup(mStateHolder.getTipsAll()); mListAdapter.addSection(getString(R.string.venue_tips_activity_section_all, mStateHolder.getTipsAll().size()), adapter); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setDividerHeight(0); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // The tip that was clicked won't have its venue member set, since we got // here by viewing the parent venue. In this case, we request that the tip // activity not let the user recursively start drilling down past here. // Create a dummy venue which has only the name and address filled in. Venue venue = new Venue(); venue.setName(mStateHolder.getVenue().getName()); venue.setAddress(mStateHolder.getVenue().getAddress()); venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet()); Tip tip = (Tip)parent.getAdapter().getItem(position); tip.setVenue(venue); Intent intent = new Intent(VenueTipsActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip); intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false); startActivityForResult(intent, ACTIVITY_TIP); } }); setTitle(getString(R.string.venue_tips_activity_title, mStateHolder.getVenue().getName())); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) { if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) { Tip tip = (Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED); Todo todo = data.hasExtra(TipActivity.EXTRA_TODO_RETURNED) ? (Todo)data.getParcelableExtra(TipActivity.EXTRA_TODO_RETURNED) : null; updateTip(tip, todo); } } } private void updateTip(Tip tip, Todo todo) { mStateHolder.updateTip(tip, todo); mListAdapter.notifyDataSetInvalidated(); prepareResultIntent(); } private void prepareResultIntent() { Intent intent = new Intent(); intent.putExtra(INTENT_EXTRA_RETURN_VENUE, mStateHolder.getVenue()); mStateHolder.setPreparedResult(intent); setPreparedResultIntent(); } private void setPreparedResultIntent() { if (mStateHolder.getPreparedResult() != null) { setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult()); } } private static class StateHolder { private Venue mVenue; private Group<Tip> mTipsFriends; private Group<Tip> mTipsAll; private Intent mPreparedResult; public StateHolder() { mPreparedResult = null; mTipsFriends = new Group<Tip>(); mTipsAll = new Group<Tip>(); } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; mTipsFriends.clear(); mTipsAll.clear(); for (Tip tip : venue.getTips()) { if (UserUtils.isFriend(tip.getUser())) { mTipsFriends.add(tip); } else { mTipsAll.add(tip); } } } public Group<Tip> getTipsFriends() { return mTipsFriends; } public Group<Tip> getTipsAll() { return mTipsAll; } public Intent getPreparedResult() { return mPreparedResult; } public void setPreparedResult(Intent intent) { mPreparedResult = intent; } public void updateTip(Tip tip, Todo todo) { // Changes to a tip status can produce or remove a to-do for its // parent venue. VenueUtils.handleTipChange(mVenue, tip, todo); // Also update the tip from wherever it appears in the separated // list adapter sections. updateTip(tip, mTipsFriends); updateTip(tip, mTipsAll); } private void updateTip(Tip tip, List<Tip> target) { for (Tip it : target) { if (it.getId().equals(tip.getId())) { it.setStatus(tip.getStatus()); break; } } } } }
1031868817-hws
main/src/com/joelapenna/foursquared/VenueTipsActivity.java
Java
asf20
9,133
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import com.joelapenna.foursquared.widget.TipsListAdapter; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import java.util.Observable; import java.util.Observer; /** * Shows a tips of a user, but not the logged-in user. This is pretty much a copy-paste * of TipsActivity, but there are enough small differences to put it in its own activity. * The direction of this activity is unknown too, so separating i here. * * @date September 23, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsTipsActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "UserDetailsTipsActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_USER_ID = Foursquared.PACKAGE_NAME + ".UserDetailsTipsActivity.INTENT_EXTRA_USER_ID"; public static final String INTENT_EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".UserDetailsTipsActivity.INTENT_EXTRA_USER_NAME"; private static final int ACTIVITY_TIP = 500; private StateHolder mStateHolder; private TipsListAdapter mListAdapter; private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private View mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { if (getIntent().hasExtra(INTENT_EXTRA_USER_ID) && getIntent().hasExtra(INTENT_EXTRA_USER_NAME)) { mStateHolder = new StateHolder( getIntent().getStringExtra(INTENT_EXTRA_USER_ID), getIntent().getStringExtra(INTENT_EXTRA_USER_NAME)); mStateHolder.setRecentOnly(true); } else { Log.e(TAG, TAG + " requires user ID and name in intent extras."); finish(); return; } } ensureUi(); // Friend tips is shown first by default so auto-fetch it if necessary. if (!mStateHolder.getRanOnceTipsRecent()) { mStateHolder.startTaskTips(this, true); } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); mLayoutEmpty = inflater.inflate(R.layout.tips_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new TipsListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_venue_list_item); if (mStateHolder.getRecentOnly()) { mListAdapter.setGroup(mStateHolder.getTipsRecent()); if (mStateHolder.getTipsRecent().size() == 0) { if (mStateHolder.getRanOnceTipsRecent()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } else { mListAdapter.setGroup(mStateHolder.getTipsPopular()); if (mStateHolder.getTipsPopular().size() == 0) { if (mStateHolder.getRanOnceTipsPopular()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.user_details_tips_activity_btn_recent), getString(R.string.user_details_tips_activity_btn_popular)); if (mStateHolder.mRecentOnly) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setRecentOnly(true); mListAdapter.setGroup(mStateHolder.getTipsRecent()); if (mStateHolder.getTipsRecent().size() < 1) { if (mStateHolder.getRanOnceTipsRecent()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskTips(UserDetailsTipsActivity.this, true); } } } else { mStateHolder.setRecentOnly(false); mListAdapter.setGroup(mStateHolder.getTipsPopular()); if (mStateHolder.getTipsPopular().size() < 1) { if (mStateHolder.getRanOnceTipsPopular()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskTips(UserDetailsTipsActivity.this, false); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tip tip = (Tip) parent.getAdapter().getItem(position); Intent intent = new Intent(UserDetailsTipsActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip); startActivityForResult(intent, ACTIVITY_TIP); } }); if (mStateHolder.getIsRunningTaskTipsRecent() || mStateHolder.getIsRunningTaskTipsPopular()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } setTitle(getString(R.string.user_details_tips_activity_title, mStateHolder.getUsername())); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTaskTips(this, mStateHolder.getRecentOnly()); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // We don't care about the returned to-do (if any) since we're not bound // to a venue in this activity for update. We just update the status member // of the target tip. if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) { if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) { Log.i(TAG, "onActivityResult(), return tip intent extra found, processing."); updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED)); } else { Log.i(TAG, "onActivityResult(), no return tip intent extra found."); } } } private void updateTip(Tip tip) { mStateHolder.updateTip(tip); mListAdapter.notifyDataSetInvalidated(); } private void onStartTaskTips() { if (mListAdapter != null) { if (mStateHolder.getRecentOnly()) { mStateHolder.setIsRunningTaskTipsRecent(true); mListAdapter.setGroup(mStateHolder.getTipsRecent()); } else { mStateHolder.setIsRunningTaskTipsPopular(true); mListAdapter.setGroup(mStateHolder.getTipsPopular()); } mListAdapter.notifyDataSetChanged(); } setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskTipsComplete(Group<Tip> group, boolean recentOnly, Exception ex) { SegmentedButton buttons = getHeaderButton(); boolean update = false; if (group != null) { if (recentOnly) { mStateHolder.setTipsRecent(group); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getTipsRecent()); update = true; } } else { mStateHolder.setTipsPopular(group); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getTipsPopular()); update = true; } } } else { if (recentOnly) { mStateHolder.setTipsRecent(new Group<Tip>()); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getTipsRecent()); update = true; } } else { mStateHolder.setTipsPopular(new Group<Tip>()); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getTipsPopular()); update = true; } } NotificationsUtil.ToastReasonForFailure(this, ex); } if (recentOnly) { mStateHolder.setIsRunningTaskTipsRecent(false); mStateHolder.setRanOnceTipsRecent(true); if (mStateHolder.getTipsRecent().size() == 0 && buttons.getSelectedButtonIndex() == 0) { setEmptyView(mLayoutEmpty); } } else { mStateHolder.setIsRunningTaskTipsPopular(false); mStateHolder.setRanOnceTipsPopular(true); if (mStateHolder.getTipsPopular().size() == 0 && buttons.getSelectedButtonIndex() == 1) { setEmptyView(mLayoutEmpty); } } if (update) { mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } if (!mStateHolder.getIsRunningTaskTipsRecent() && !mStateHolder.getIsRunningTaskTipsPopular()) { setProgressBarIndeterminateVisibility(false); } } private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> { private String mUserId; private UserDetailsTipsActivity mActivity; private boolean mRecentOnly; private Exception mReason; public TaskTips(UserDetailsTipsActivity activity, String userId, boolean recentOnly) { mActivity = activity; mUserId = userId; mRecentOnly = recentOnly; } @Override protected void onPreExecute() { mActivity.onStartTaskTips(); } @Override protected Group<Tip> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location loc = foursquared.getLastKnownLocation(); if (loc == null) { try { Thread.sleep(3000); } catch (InterruptedException ex) {} loc = foursquared.getLastKnownLocation(); if (loc == null) { throw new FoursquareException("Your location could not be determined!"); } } return foursquare.tips( LocationUtils.createFoursquareLocation(loc), mUserId, "nearby", mRecentOnly ? "recent" : "popular", 30); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<Tip> tips) { if (mActivity != null) { mActivity.onTaskTipsComplete(tips, mRecentOnly, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskTipsComplete(null, mRecentOnly, mReason); } } public void setActivity(UserDetailsTipsActivity activity) { mActivity = activity; } } private static class StateHolder { private String mUserId; private String mUsername; private Group<Tip> mTipsRecent; private Group<Tip> mTipsPopular; private TaskTips mTaskTipsRecent; private TaskTips mTaskTipsPopular; private boolean mIsRunningTaskTipsRecent; private boolean mIsRunningTaskTipsPopular; private boolean mRecentOnly; private boolean mRanOnceTipsRecent; private boolean mRanOnceTipsPopular; public StateHolder(String userId, String username) { mUserId = userId; mUsername = username; mIsRunningTaskTipsRecent = false; mIsRunningTaskTipsPopular = false; mRanOnceTipsRecent = false; mRanOnceTipsPopular = false; mTipsRecent = new Group<Tip>(); mTipsPopular = new Group<Tip>(); mRecentOnly = true; } public String getUsername() { return mUsername; } public Group<Tip> getTipsRecent() { return mTipsRecent; } public void setTipsRecent(Group<Tip> tipsRecent) { mTipsRecent = tipsRecent; } public Group<Tip> getTipsPopular() { return mTipsPopular; } public void setTipsPopular(Group<Tip> tipsPopular) { mTipsPopular = tipsPopular; } public void startTaskTips(UserDetailsTipsActivity activity, boolean recentOnly) { if (recentOnly) { if (mIsRunningTaskTipsRecent) { return; } mIsRunningTaskTipsRecent = true; mTaskTipsRecent = new TaskTips(activity, mUserId, recentOnly); mTaskTipsRecent.execute(); } else { if (mIsRunningTaskTipsPopular) { return; } mIsRunningTaskTipsPopular = true; mTaskTipsPopular = new TaskTips(activity, mUserId, recentOnly); mTaskTipsPopular.execute(); } } public void setActivity(UserDetailsTipsActivity activity) { if (mTaskTipsRecent != null) { mTaskTipsRecent.setActivity(activity); } if (mTaskTipsPopular != null) { mTaskTipsPopular.setActivity(activity); } } public boolean getIsRunningTaskTipsRecent() { return mIsRunningTaskTipsRecent; } public void setIsRunningTaskTipsRecent(boolean isRunning) { mIsRunningTaskTipsRecent = isRunning; } public boolean getIsRunningTaskTipsPopular() { return mIsRunningTaskTipsPopular; } public void setIsRunningTaskTipsPopular(boolean isRunning) { mIsRunningTaskTipsPopular = isRunning; } public void cancelTasks() { if (mTaskTipsRecent != null) { mTaskTipsRecent.setActivity(null); mTaskTipsRecent.cancel(true); } if (mTaskTipsPopular != null) { mTaskTipsPopular.setActivity(null); mTaskTipsPopular.cancel(true); } } public boolean getRecentOnly() { return mRecentOnly; } public void setRecentOnly(boolean recentOnly) { mRecentOnly = recentOnly; } public boolean getRanOnceTipsRecent() { return mRanOnceTipsRecent; } public void setRanOnceTipsRecent(boolean ranOnce) { mRanOnceTipsRecent = ranOnce; } public boolean getRanOnceTipsPopular() { return mRanOnceTipsPopular; } public void setRanOnceTipsPopular(boolean ranOnce) { mRanOnceTipsPopular = ranOnce; } public void updateTip(Tip tip) { updateTipFromArray(tip, mTipsRecent); updateTipFromArray(tip, mTipsPopular); } private void updateTipFromArray(Tip tip, Group<Tip> target) { for (Tip it : target) { if (it.getId().equals(tip.getId())) { it.setStatus(tip.getStatus()); break; } } } } private class SearchLocationObserver implements Observer { @Override public void update(Observable observable, Object data) { } } }
1031868817-hws
main/src/com/joelapenna/foursquared/UserDetailsTipsActivity.java
Java
asf20
20,048
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquared.preferences.Preferences; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceChangeListener; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -added notifications settings (May 21, 2010). * -removed user update, moved to NotificationSettingsActivity (June 2, 2010) */ public class PreferenceActivity extends android.preference.PreferenceActivity { private static final String TAG = "PreferenceActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int DIALOG_TOS_PRIVACY = 1; private static final int DIALOG_PROFILE_SETTINGS = 2; private static final String URL_TOS = "http://foursquare.com/legal/terms"; private static final String URL_PRIVACY = "http://foursquare.com/legal/privacy"; private SharedPreferences mPrefs; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); addPreferencesFromResource(R.xml.preferences); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); Preference advanceSettingsPreference = getPreferenceScreen().findPreference( Preferences.PREFERENCE_ADVANCED_SETTINGS); advanceSettingsPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { ((Foursquared) getApplication()).requestUpdateUser(); return false; } }); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (DEBUG) Log.d(TAG, "onPreferenceTreeClick"); String key = preference.getKey(); if (Preferences.PREFERENCE_LOGOUT.equals(key)) { mPrefs.edit().clear().commit(); // TODO: If we re-implement oAuth, we'll have to call // clearAllCrendentials here. ((Foursquared) getApplication()).getFoursquare().setCredentials(null, null); Intent intent = new Intent(this, LoginActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP); sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT)); } else if (Preferences.PREFERENCE_ADVANCED_SETTINGS.equals(key)) { startActivity(new Intent( // Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_PREFERENCES))); } else if (Preferences.PREFERENCE_HELP.equals(key)) { Intent intent = new Intent(this, WebViewActivity.class); intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, "http://foursquare.com/help/android"); startActivity(intent); } else if (Preferences.PREFERENCE_SEND_FEEDBACK.equals(key)) { startActivity(new Intent(this, SendLogActivity.class)); } else if (Preferences.PREFERENCE_FRIEND_ADD.equals(key)) { startActivity(new Intent(this, AddFriendsActivity.class)); } else if (Preferences.PREFERENCE_FRIEND_REQUESTS.equals(key)) { startActivity(new Intent(this, FriendRequestsActivity.class)); } else if (Preferences.PREFERENCE_CHANGELOG.equals(key)) { startActivity(new Intent(this, ChangelogActivity.class)); } else if (Preferences.PREFERENCE_PINGS.equals(key)) { startActivity(new Intent(this, PingsSettingsActivity.class)); } else if (Preferences.PREFERENCE_TOS_PRIVACY.equals(key)) { showDialog(DIALOG_TOS_PRIVACY); } else if (Preferences.PREFERENCE_PROFILE_SETTINGS.equals(key)) { showDialog(DIALOG_PROFILE_SETTINGS); } return true; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_TOS_PRIVACY: ArrayAdapter<String> adapterTos = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); adapterTos.add(getResources().getString(R.string.preference_activity_tos)); adapterTos.add(getResources().getString(R.string.preference_activity_privacy)); AlertDialog dlgInfo = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.preference_activity_tos_privacy_dlg_title)) .setAdapter(adapterTos, new OnClickListener() { @Override public void onClick(DialogInterface dlg, int pos) { Intent intent = new Intent(PreferenceActivity.this, WebViewActivity.class); switch (pos) { case 0: intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, URL_TOS); break; case 1: intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, URL_PRIVACY); break; default: return; } startActivity(intent); } }) .create(); return dlgInfo; case DIALOG_PROFILE_SETTINGS: String userId = ((Foursquared) getApplication()).getUserId(); String userName = ((Foursquared) getApplication()).getUserName(); String userEmail = ((Foursquared) getApplication()).getUserEmail(); LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.settings_user_info, (ViewGroup) findViewById(R.id.settings_user_info_layout_root)); TextView tvUserId = (TextView)layout.findViewById(R.id.settings_user_info_label_user_id); TextView tvUserName = (TextView)layout.findViewById(R.id.settings_user_info_label_user_name); TextView tvUserEmail = (TextView)layout.findViewById(R.id.settings_user_info_label_user_email); tvUserId.setText(userId); tvUserName.setText(userName); tvUserEmail.setText(userEmail); AlertDialog dlgProfileSettings = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.preference_activity_profile_settings_dlg_title)) .setView(layout) .create(); return dlgProfileSettings; } return null; } }
1031868817-hws
main/src/com/joelapenna/foursquared/PreferenceActivity.java
Java
asf20
8,363
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Stats; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.maps.VenueItemizedOverlay; import com.joelapenna.foursquared.widget.MapCalloutView; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class SearchVenuesMapActivity extends MapActivity { public static final String TAG = "SearchVenuesMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private String mTappedVenueId; private Observer mSearchResultsObserver; private MapCalloutView mCallout; private MapView mMapView; private MapController mMapController; private VenueItemizedOverlay mVenueItemizedOverlay; private MyLocationOverlay mMyLocationOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_map_activity); initMap(); mCallout = (MapCalloutView) findViewById(R.id.map_callout); mCallout.setVisibility(View.GONE); mCallout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(SearchVenuesMapActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, mTappedVenueId); startActivity(intent); } }); mSearchResultsObserver = new Observer() { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Observed search results change."); clearMap(); loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults()); recenterMap(); } }; } @Override public void onResume() { super.onResume(); if (DEBUG) Log.d(TAG, "onResume()"); mMyLocationOverlay.enableMyLocation(); // mMyLocationOverlay.enableCompass(); // Disabled due to a sdk 1.5 emulator bug clearMap(); loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults()); recenterMap(); SearchVenuesActivity.searchResultsObservable.addObserver(mSearchResultsObserver); } @Override public void onPause() { super.onPause(); if (DEBUG) Log.d(TAG, "onPause()"); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); SearchVenuesActivity.searchResultsObservable.deleteObserver(mSearchResultsObserver); } @Override protected boolean isRouteDisplayed() { return false; } private void initMap() { mMapView = (MapView)findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { if (DEBUG) Log.d(TAG, "runOnFirstFix()"); mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation()); mMapView.getController().setZoom(16); } }); } private void loadSearchResults(Group<Group<Venue>> searchResults) { if (searchResults == null) { if (DEBUG) Log.d(TAG, "no search results. Not loading."); return; } if (DEBUG) Log.d(TAG, "Loading search results"); // Put our location on the map. mMapView.getOverlays().add(mMyLocationOverlay); Group<Venue> mappableVenues = new Group<Venue>(); mappableVenues.setType("Mappable Venues"); // For each group of venues. final int groupCount = searchResults.size(); for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) { Group<Venue> group = searchResults.get(groupIndex); // For each venue group final int venueCount = group.size(); for (int venueIndex = 0; venueIndex < venueCount; venueIndex++) { Venue venue = group.get(venueIndex); if (VenueUtils.hasValidLocation(venue)) { mappableVenues.add(venue); } } } // Construct the venues overlay and attach it if we have a mappable set of venues. if (mappableVenues.size() > 0) { mVenueItemizedOverlay = new VenueItemizedOverlayWithButton( // this.getResources().getDrawable(R.drawable.map_marker_blue), // this.getResources().getDrawable(R.drawable.map_marker_blue_muted)); mVenueItemizedOverlay.setGroup(mappableVenues); mMapView.getOverlays().add(mVenueItemizedOverlay); } } private void clearMap() { if (DEBUG) Log.d(TAG, "clearMap()"); mMapView.getOverlays().clear(); mMapView.postInvalidate(); } private void recenterMap() { if (DEBUG) Log.d(TAG, "Recentering map."); GeoPoint center = mMyLocationOverlay.getMyLocation(); // if we have venues in a search result, focus on those. if (mVenueItemizedOverlay != null && mVenueItemizedOverlay.size() > 0) { if (DEBUG) Log.d(TAG, "Centering on venues: " + String.valueOf(mVenueItemizedOverlay.getLatSpanE6()) + " " + String.valueOf(mVenueItemizedOverlay.getLonSpanE6())); mMapController.setCenter(mVenueItemizedOverlay.getCenter()); mMapController.zoomToSpan(mVenueItemizedOverlay.getLatSpanE6(), mVenueItemizedOverlay .getLonSpanE6()); } else if (center != null && SearchVenuesActivity.searchResultsObservable.getQuery() == SearchVenuesActivity.QUERY_NEARBY) { if (DEBUG) Log.d(TAG, "recenterMap via MyLocation as we are doing a nearby search"); mMapController.animateTo(center); mMapController.zoomToSpan(center.getLatitudeE6(), center.getLongitudeE6()); } else if (center != null) { if (DEBUG) Log.d(TAG, "Fallback, recenterMap via MyLocation overlay"); mMapController.animateTo(center); mMapController.setZoom(16); return; } } private class VenueItemizedOverlayWithButton extends VenueItemizedOverlay { public static final String TAG = "VenueItemizedOverlayWithButton"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private Drawable mBeenThereMarker; public VenueItemizedOverlayWithButton(Drawable defaultMarker, Drawable beenThereMarker) { super(defaultMarker); mBeenThereMarker = boundCenterBottom(beenThereMarker); } @Override public OverlayItem createItem(int i) { VenueOverlayItem item = (VenueOverlayItem)super.createItem(i); Stats stats = item.getVenue().getStats(); if (stats != null && stats.getBeenhere() != null && stats.getBeenhere().me()) { if (DEBUG) Log.d(TAG, "using the beenThereMarker for: " + item.getVenue()); item.setMarker(mBeenThereMarker); } return item; } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + this + " " + p + " " + mapView); mCallout.setVisibility(View.GONE); return super.onTap(p, mapView); } @Override protected boolean onTap(int i) { if (DEBUG) Log.d(TAG, "onTap: " + this + " " + i); VenueOverlayItem item = (VenueOverlayItem)getItem(i); mTappedVenueId = item.getVenue().getId(); mCallout.setTitle(item.getVenue().getName()); mCallout.setMessage(item.getVenue().getAddress()); mCallout.setVisibility(View.VISIBLE); return true; } } }
1031868817-hws
main/src/com/joelapenna/foursquared/SearchVenuesMapActivity.java
Java
asf20
8,920
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import android.view.View; import android.widget.TabHost; import android.widget.TabHost.TabSpec; /** * Acts as an interface to the TabSpec class for setting the content view. * The level 3 SDK doesn't support setting a View for the content sections * of the tab, so we can only use the big native tab style. The level 4 * SDK and up support specifying a custom view for the tab. * * @date March 9, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class TabsUtil4 { private TabsUtil4() { } public static void setTabIndicator(TabSpec spec, View view) { spec.setIndicator(view); } public static int getTabCount(TabHost tabHost) { return tabHost.getTabWidget().getTabCount(); } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/TabsUtil4.java
Java
asf20
841
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.util; import com.joelapenna.foursquared.FoursquaredSettings; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.Observable; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.zip.GZIPInputStream; /** * @author Joe LaPenna (joe@joelapenna.com) */ class RemoteResourceFetcher extends Observable { public static final String TAG = "RemoteResourceFetcher"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private DiskCache mResourceCache; private ExecutorService mExecutor; private HttpClient mHttpClient; private ConcurrentHashMap<Request, Callable<Request>> mActiveRequestsMap = new ConcurrentHashMap<Request, Callable<Request>>(); public RemoteResourceFetcher(DiskCache cache) { mResourceCache = cache; mHttpClient = createHttpClient(); mExecutor = Executors.newCachedThreadPool(); } @Override public void notifyObservers(Object data) { setChanged(); super.notifyObservers(data); } public Future<Request> fetch(Uri uri, String hash) { Request request = new Request(uri, hash); synchronized (mActiveRequestsMap) { Callable<Request> fetcher = newRequestCall(request); if (mActiveRequestsMap.putIfAbsent(request, fetcher) == null) { if (DEBUG) Log.d(TAG, "issuing new request for: " + uri); return mExecutor.submit(fetcher); } else { if (DEBUG) Log.d(TAG, "Already have a pending request for: " + uri); } } return null; } public void shutdown() { mExecutor.shutdownNow(); } private Callable<Request> newRequestCall(final Request request) { return new Callable<Request>() { public Request call() { try { if (DEBUG) Log.d(TAG, "Requesting: " + request.uri); HttpGet httpGet = new HttpGet(request.uri.toString()); httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = mHttpClient.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream is = getUngzippedContent(entity); mResourceCache.store(request.hash, is); if (DEBUG) Log.d(TAG, "Request successful: " + request.uri); } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); } finally { if (DEBUG) Log.d(TAG, "Request finished: " + request.uri); mActiveRequestsMap.remove(request); notifyObservers(request.uri); } return request; } }; } /** * Gets the input stream from a response entity. If the entity is gzipped then this will get a * stream over the uncompressed data. * * @param entity the entity whose content should be read * @return the input stream to read from * @throws IOException */ public static InputStream getUngzippedContent(HttpEntity entity) throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) { return responseStream; } Header header = entity.getContentEncoding(); if (header == null) { return responseStream; } String contentEncoding = header.getValue(); if (contentEncoding == null) { return responseStream; } if (contentEncoding.contains("gzip")) { responseStream = new GZIPInputStream(responseStream); } return responseStream; } /** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Shamelessly cribbed from AndroidHttpClient HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 10 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 10 * 1000); HttpConnectionParams.setSoTimeout(params, 10 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes); return new DefaultHttpClient(ccm, params); } private static class Request { Uri uri; String hash; public Request(Uri requestUri, String requestHash) { uri = requestUri; hash = requestHash; } @Override public int hashCode() { return hash.hashCode(); } } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/RemoteResourceFetcher.java
Java
asf20
6,456
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import android.text.TextUtils; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; /** * @date September 2, 2010. * @author Mark Wyszomierski (markww@gmail.com) */ public class TipUtils { public static final String TIP_STATUS_TODO = "todo"; public static final String TIP_STATUS_DONE = "done"; public static boolean isTodo(Tip tip) { if (tip != null) { if (!TextUtils.isEmpty(tip.getStatus())) { return tip.getStatus().equals(TIP_STATUS_TODO); } } return false; } public static boolean isDone(Tip tip) { if (tip != null) { if (!TextUtils.isEmpty(tip.getStatus())) { return tip.getStatus().equals(TIP_STATUS_DONE); } } return false; } public static boolean areEqual(FoursquareType tipOrTodo1, FoursquareType tipOrTodo2) { if (tipOrTodo1 instanceof Tip) { if (tipOrTodo2 instanceof Todo) { return false; } Tip tip1 = (Tip)tipOrTodo1; Tip tip2 = (Tip)tipOrTodo2; if (!tip1.getId().equals(tip2.getId())) { return false; } if (!TextUtils.isEmpty(tip1.getStatus()) && !TextUtils.isEmpty(tip2.getStatus())) { return tip1.getStatus().equals(tip2.getStatus()); } else if (TextUtils.isEmpty(tip1.getStatus()) && TextUtils.isEmpty(tip2.getStatus())) { return true; } else { return false; } } else if (tipOrTodo1 instanceof Todo) { if (tipOrTodo2 instanceof Tip) { return false; } Todo todo1 = (Todo)tipOrTodo1; Todo todo2 = (Todo)tipOrTodo2; if (!todo1.getId().equals(todo2.getId())) { return false; } if (todo1.getTip().getId().equals(todo2.getId())) { return true; } } return false; } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/TipUtils.java
Java
asf20
2,077
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import android.app.Activity; import android.os.Build; /** * Acts as an interface to the contacts API which has changed between SDK 4 to * 5. * * @date February 14, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public abstract class AddressBookUtils { public abstract String getAllContactsPhoneNumbers(Activity activity); public abstract String getAllContactsEmailAddresses(Activity activity); public abstract AddressBookEmailBuilder getAllContactsEmailAddressesInfo( Activity activity); public static AddressBookUtils addressBookUtils() { int sdk = new Integer(Build.VERSION.SDK).intValue(); if (sdk < 5) { return new AddressBookUtils3and4(); } else { return new AddressBookUtils5(); } } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/AddressBookUtils.java
Java
asf20
902
// Copyright 2003-2009 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland // www.source-code.biz, www.inventec.ch/chdh // // This module is multi-licensed and may be used under the terms // of any of the following licenses: // // EPL, Eclipse Public License, http://www.eclipse.org/legal // LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html // AL, Apache License, http://www.apache.org/licenses // BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php // // Please contact the author if you need another license. // This module is provided "as is", without warranties of any kind. package com.joelapenna.foursquared.util; /** * A Base64 Encoder/Decoder. * <p> * This class is used to encode and decode data in Base64 format as described in * RFC 1521. * <p> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br> * Multi-licensed: EPL/LGPL/AL/BSD. * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> * 2009-07-16: Additional licenses (EPL/AL) added.<br> * 2009-09-16: Additional license (BSD) added.<br> */ public class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i = 0; for (char c = 'A'; c <= 'Z'; c++) map1[i++] = c; for (char c = 'a'; c <= 'z'; c++) map1[i++] = c; for (char c = '0'; c <= '9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i = 0; i < map2.length; i++) map2[i] = -1; for (int i = 0; i < 64; i++) map2[map1[i]] = (byte) i; } /** * Encodes a string into Base64 format. No blanks or line breaks are * inserted. * * @param s a String to be encoded. * @return A String with the Base64 encoded data. */ public static String encodeString(String s) { return new String(encode(s.getBytes())); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted. * * @param in an array containing the data bytes to be encoded. * @return A character array with the Base64 encoded data. */ public static char[] encode(byte[] in) { return encode(in, in.length); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted. * * @param in an array containing the data bytes to be encoded. * @param iLen number of bytes to process in <code>in</code>. * @return A character array with the Base64 encoded data. */ public static char[] encode(byte[] in, int iLen) { int oDataLen = (iLen * 4 + 2) / 3; // output length without padding int oLen = ((iLen + 2) / 3) * 4; // output length including padding char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++] & 0xff; int i1 = ip < iLen ? in[ip++] & 0xff : 0; int i2 = ip < iLen ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. * * @param s a Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException if the input is not valid Base64 encoded * data. */ public static String decodeString(String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format. * * @param s a Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded * data. */ public static byte[] decode(String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. No blanks or line breaks are * allowed within the Base64 encoded data. * * @param in a character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded * data. */ public static byte[] decode(char[] in) { int iLen = in.length; if (iLen % 4 != 0) throw new IllegalArgumentException( "Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iLen - 1] == '=') iLen--; int oLen = (iLen * 3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int o0 = (b0 << 2) | (b1 >>> 4); int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); int o2 = ((b2 & 3) << 6) | b3; out[op++] = (byte) o0; if (op < oLen) out[op++] = (byte) o1; if (op < oLen) out[op++] = (byte) o2; } return out; } // Dummy constructor. private Base64Coder() { } } // end class Base64Coder
1031868817-hws
main/src/com/joelapenna/foursquared/util/Base64Coder.java
Java
asf20
6,665
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.util; import com.joelapenna.foursquared.FoursquaredSettings; import android.os.Environment; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class BaseDiskCache implements DiskCache { private static final String TAG = "BaseDiskCache"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final String NOMEDIA = ".nomedia"; private static final int MIN_FILE_SIZE_IN_BYTES = 100; private File mStorageDirectory; BaseDiskCache(String dirPath, String name) { // Lets make sure we can actually cache things! File baseDirectory = new File(Environment.getExternalStorageDirectory(), dirPath); File storageDirectory = new File(baseDirectory, name); createDirectory(storageDirectory); mStorageDirectory = storageDirectory; // cleanup(); // Remove invalid files that may have shown up. cleanupSimple(); } /* * (non-Javadoc) * @see com.joelapenna.foursquared.util.DiskCache#exists(java.lang.String) */ @Override public boolean exists(String key) { return getFile(key).exists(); } /** * This is silly, but our content provider *has* to serve content: URIs as File/FileDescriptors * using ContentProvider.openAssetFile, this is a limitation of the StreamLoader that is used by * the WebView. So, we handle this by writing the file to disk, and returning a File pointer to * it. * * @param guid * @return */ public File getFile(String hash) { return new File(mStorageDirectory.toString() + File.separator + hash); } public InputStream getInputStream(String hash) throws IOException { return (InputStream)new FileInputStream(getFile(hash)); } /* * (non-Javadoc) * @see com.joelapenna.everdroid.evernote.NoteResourceDataBodyCache#storeResource (com * .evernote.edam.type.Resource) */ public void store(String key, InputStream is) { if (DEBUG) Log.d(TAG, "store: " + key); is = new BufferedInputStream(is); try { OutputStream os = new BufferedOutputStream(new FileOutputStream(getFile(key))); byte[] b = new byte[2048]; int count; int total = 0; while ((count = is.read(b)) > 0) { os.write(b, 0, count); total += count; } os.close(); if (DEBUG) Log.d(TAG, "store complete: " + key); } catch (IOException e) { if (DEBUG) Log.d(TAG, "store failed to store: " + key, e); return; } } public void invalidate(String key) { getFile(key).delete(); } public void cleanup() { // removes files that are too small to be valid. Cheap and cheater way to remove files that // were corrupted during download. String[] children = mStorageDirectory.list(); if (children != null) { // children will be null if hte directyr does not exist. for (int i = 0; i < children.length; i++) { File child = new File(mStorageDirectory, children[i]); if (!child.equals(new File(mStorageDirectory, NOMEDIA)) && child.length() <= MIN_FILE_SIZE_IN_BYTES) { if (DEBUG) Log.d(TAG, "Deleting: " + child); child.delete(); } } } } /** * Temporary fix until we rework this disk cache. We delete the first 50 youngest files * if we find the cache has more than 1000 images in it. */ public void cleanupSimple() { final int maxNumFiles = 1000; final int numFilesToDelete = 50; String[] children = mStorageDirectory.list(); if (children != null) { if (DEBUG) Log.d(TAG, "Found disk cache length to be: " + children.length); if (children.length > maxNumFiles) { if (DEBUG) Log.d(TAG, "Disk cache found to : " + children); for (int i = children.length - 1, m = i - numFilesToDelete; i > m; i--) { File child = new File(mStorageDirectory, children[i]); if (DEBUG) Log.d(TAG, " deleting: " + child.getName()); child.delete(); } } } } public void clear() { // Clear the whole cache. Coolness. String[] children = mStorageDirectory.list(); if (children != null) { // children will be null if hte directyr does not exist. for (int i = 0; i < children.length; i++) { File child = new File(mStorageDirectory, children[i]); if (!child.equals(new File(mStorageDirectory, NOMEDIA))) { if (DEBUG) Log.d(TAG, "Deleting: " + child); child.delete(); } } } mStorageDirectory.delete(); } private static final void createDirectory(File storageDirectory) { if (!storageDirectory.exists()) { Log.d(TAG, "Trying to create storageDirectory: " + String.valueOf(storageDirectory.mkdirs())); Log.d(TAG, "Exists: " + storageDirectory + " " + String.valueOf(storageDirectory.exists())); Log.d(TAG, "State: " + Environment.getExternalStorageState()); Log.d(TAG, "Isdir: " + storageDirectory + " " + String.valueOf(storageDirectory.isDirectory())); Log.d(TAG, "Readable: " + storageDirectory + " " + String.valueOf(storageDirectory.canRead())); Log.d(TAG, "Writable: " + storageDirectory + " " + String.valueOf(storageDirectory.canWrite())); File tmp = storageDirectory.getParentFile(); Log.d(TAG, "Exists: " + tmp + " " + String.valueOf(tmp.exists())); Log.d(TAG, "Isdir: " + tmp + " " + String.valueOf(tmp.isDirectory())); Log.d(TAG, "Readable: " + tmp + " " + String.valueOf(tmp.canRead())); Log.d(TAG, "Writable: " + tmp + " " + String.valueOf(tmp.canWrite())); tmp = tmp.getParentFile(); Log.d(TAG, "Exists: " + tmp + " " + String.valueOf(tmp.exists())); Log.d(TAG, "Isdir: " + tmp + " " + String.valueOf(tmp.isDirectory())); Log.d(TAG, "Readable: " + tmp + " " + String.valueOf(tmp.canRead())); Log.d(TAG, "Writable: " + tmp + " " + String.valueOf(tmp.canWrite())); } File nomediaFile = new File(storageDirectory, NOMEDIA); if (!nomediaFile.exists()) { try { Log.d(TAG, "Created file: " + nomediaFile + " " + String.valueOf(nomediaFile.createNewFile())); } catch (IOException e) { Log.d(TAG, "Unable to create .nomedia file for some reason.", e); throw new IllegalStateException("Unable to create nomedia file."); } } // After we best-effort try to create the file-structure we need, // lets make sure it worked. if (!(storageDirectory.isDirectory() && nomediaFile.exists())) { throw new RuntimeException("Unable to create storage directory and nomedia file."); } } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/BaseDiskCache.java
Java
asf20
7,683
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import com.google.android.maps.GeoPoint; import android.content.Context; import android.location.Location; import android.location.LocationManager; import java.util.List; /** * @date June 30, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class GeoUtils { /** * To be used if you just want a one-shot best last location, iterates over * all providers and returns the most accurate result. */ public static Location getBestLastGeolocation(Context context) { LocationManager manager = (LocationManager)context.getSystemService( Context.LOCATION_SERVICE); List<String> providers = manager.getAllProviders(); Location bestLocation = null; for (String it : providers) { Location location = manager.getLastKnownLocation(it); if (location != null) { if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } } return bestLocation; } public static GeoPoint locationToGeoPoint(Location location) { if (location != null) { GeoPoint pt = new GeoPoint( (int)(location.getLatitude() * 1E6 + 0.5), (int)(location.getLongitude() * 1E6 + 0.5)); return pt; } else { return null; } } public static GeoPoint stringLocationToGeoPoint(String strlat, String strlon) { try { double lat = Double.parseDouble(strlat); double lon = Double.parseDouble(strlon); GeoPoint pt = new GeoPoint( (int)(lat * 1E6 + 0.5), (int)(lon * 1E6 + 0.5)); return pt; } catch (Exception ex) { return null; } } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/GeoUtils.java
Java
asf20
1,993
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import android.os.Parcel; import android.text.TextUtils; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.Venue; /** * @date September 16, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class VenueUtils { public static void handleTipChange(Venue venue, Tip tip, Todo todo) { // Update the tip in the tips group, if it exists. updateTip(venue, tip); // If it is a to-do, then make sure a to-do exists for it // in the to-do group. if (TipUtils.isTodo(tip)) { addTodo(venue, tip, todo); } else { // If it is not a to-do, make sure it does not exist in the // to-do group. removeTodo(venue, tip); } } private static void updateTip(Venue venue, Tip tip) { if (venue.getTips() != null) { for (Tip it : venue.getTips()) { if (it.getId().equals(tip.getId())) { it.setStatus(tip.getStatus()); break; } } } } public static void addTodo(Venue venue, Tip tip, Todo todo) { venue.setHasTodo(true); if (venue.getTodos() == null) { venue.setTodos(new Group<Todo>()); } // If found a to-do linked to the tip ID, then overwrite to-do attributes // with newer to-do object. for (Todo it : venue.getTodos()) { if (it.getTip().getId().equals(tip.getId())) { it.setId(todo.getId()); it.setCreated(todo.getCreated()); return; } } venue.getTodos().add(todo); } public static void addTip(Venue venue, Tip tip) { if (venue.getTips() == null) { venue.setTips(new Group<Tip>()); } for (Tip it : venue.getTips()) { if (it.getId().equals(tip.getId())) { return; } } venue.getTips().add(tip); } private static void removeTodo(Venue venue, Tip tip) { for (Todo it : venue.getTodos()) { if (it.getTip().getId().equals(tip.getId())) { venue.getTodos().remove(it); break; } } if (venue.getTodos().size() > 0) { venue.setHasTodo(true); } else { venue.setHasTodo(false); } } public static void replaceTipsAndTodos(Venue venueTarget, Venue venueSource) { if (venueTarget.getTips() == null) { venueTarget.setTips(new Group<Tip>()); } if (venueTarget.getTodos() == null) { venueTarget.setTodos(new Group<Todo>()); } if (venueSource.getTips() == null) { venueSource.setTips(new Group<Tip>()); } if (venueSource.getTodos() == null) { venueSource.setTodos(new Group<Todo>()); } venueTarget.getTips().clear(); venueTarget.getTips().addAll(venueSource.getTips()); venueTarget.getTodos().clear(); venueTarget.getTodos().addAll(venueSource.getTodos()); if (venueTarget.getTodos().size() > 0) { venueTarget.setHasTodo(true); } else { venueTarget.setHasTodo(false); } } public static boolean getSpecialHere(Venue venue) { if (venue != null && venue.getSpecials() != null && venue.getSpecials().size() > 0) { Venue specialVenue = venue.getSpecials().get(0).getVenue(); if (specialVenue == null || specialVenue.getId().equals(venue.getId())) { return true; } } return false; } /** * Creates a copy of the passed venue. This should really be implemented * as a copy constructor. */ public static Venue cloneVenue(Venue venue) { Parcel p1 = Parcel.obtain(); Parcel p2 = Parcel.obtain(); byte[] bytes = null; p1.writeValue(venue); bytes = p1.marshall(); p2.unmarshall(bytes, 0, bytes.length); p2.setDataPosition(0); Venue venueNew = (Venue)p2.readValue(Venue.class.getClassLoader()); p1.recycle(); p2.recycle(); return venueNew; } public static String toStringVenueShare(Venue venue) { StringBuilder sb = new StringBuilder(); sb.append(venue.getName()); sb.append("\n"); sb.append(StringFormatters.getVenueLocationFull(venue)); if (!TextUtils.isEmpty(venue.getPhone())) { sb.append("\n"); sb.append(venue.getPhone()); } return sb.toString(); } /** * Dumps some info about a venue. This can be moved into the Venue class. */ public static String toString(Venue venue) { StringBuilder sb = new StringBuilder(); sb.append(venue.toString()); sb.append(":\n"); sb.append(" id: "); sb.append(venue.getId()); sb.append("\n"); sb.append(" name: "); sb.append(venue.getName()); sb.append("\n"); sb.append(" address: "); sb.append(venue.getAddress()); sb.append("\n"); sb.append(" cross: "); sb.append(venue.getCrossstreet()); sb.append("\n"); sb.append(" hastodo: "); sb.append(venue.getHasTodo()); sb.append("\n"); sb.append(" tips: "); sb.append(venue.getTips() == null ? "(null)" : venue.getTips().size()); sb.append("\n"); sb.append(" todos: "); sb.append(venue.getTodos() == null ? "(null)" : venue.getTodos().size()); sb.append("\n"); sb.append(" specials: "); sb.append(venue.getSpecials() == null ? "(null)" : venue.getSpecials().size()); sb.append("\n"); return sb.toString(); } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/VenueUtils.java
Java
asf20
5,574
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.util; import com.joelapenna.foursquared.FoursquaredSettings; import android.net.Uri; import android.util.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class RemoteResourceManager extends Observable { private static final String TAG = "RemoteResourceManager"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private DiskCache mDiskCache; private RemoteResourceFetcher mRemoteResourceFetcher; private FetcherObserver mFetcherObserver = new FetcherObserver(); public RemoteResourceManager(String cacheName) { this(new BaseDiskCache("foursquare", cacheName)); } public RemoteResourceManager(DiskCache cache) { mDiskCache = cache; mRemoteResourceFetcher = new RemoteResourceFetcher(mDiskCache); mRemoteResourceFetcher.addObserver(mFetcherObserver); } public boolean exists(Uri uri) { return mDiskCache.exists(Uri.encode(uri.toString())); } /** * If IOException is thrown, we don't have the resource available. */ public File getFile(Uri uri) { if (DEBUG) Log.d(TAG, "getInputStream(): " + uri); return mDiskCache.getFile(Uri.encode(uri.toString())); } /** * If IOException is thrown, we don't have the resource available. */ public InputStream getInputStream(Uri uri) throws IOException { if (DEBUG) Log.d(TAG, "getInputStream(): " + uri); return mDiskCache.getInputStream(Uri.encode(uri.toString())); } /** * Request a resource be downloaded. Useful to call after a IOException from getInputStream. */ public void request(Uri uri) { if (DEBUG) Log.d(TAG, "request(): " + uri); mRemoteResourceFetcher.fetch(uri, Uri.encode(uri.toString())); } /** * Explicitly expire an individual item. */ public void invalidate(Uri uri) { mDiskCache.invalidate(Uri.encode(uri.toString())); } public void shutdown() { mRemoteResourceFetcher.shutdown(); mDiskCache.cleanup(); } public void clear() { mRemoteResourceFetcher.shutdown(); mDiskCache.clear(); } public static abstract class ResourceRequestObserver implements Observer { private Uri mRequestUri; abstract public void requestReceived(Observable observable, Uri uri); public ResourceRequestObserver(Uri requestUri) { mRequestUri = requestUri; } @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Recieved update: " + data); Uri dataUri = (Uri)data; if (dataUri == mRequestUri) { if (DEBUG) Log.d(TAG, "requestReceived: " + dataUri); requestReceived(observable, dataUri); } } } /** * Relay the observed download to this controlling class. */ private class FetcherObserver implements Observer { @Override public void update(Observable observable, Object data) { setChanged(); notifyObservers(data); } } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/RemoteResourceManager.java
Java
asf20
3,347
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import com.joelapenna.foursquared.R; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TextView; import android.widget.TabHost.TabSpec; /** * Acts as an interface to the TabSpec class for setting the content view. The * level 3 SDK doesn't support setting a View for the content sections of the * tab, so we can only use the big native tab style. The level 4 SDK and up * support specifying a custom view for the tab. * * @date March 9, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public abstract class TabsUtil { private static void setTabIndicator(TabSpec spec, String title, Drawable drawable, View view) { int sdk = new Integer(Build.VERSION.SDK).intValue(); if (sdk < 4) { TabsUtil3.setTabIndicator(spec, title, drawable); } else { TabsUtil4.setTabIndicator(spec, view); } } public static void addTab(TabHost host, String title, int drawable, int index, int layout) { TabHost.TabSpec spec = host.newTabSpec("tab" + index); spec.setContent(layout); View view = prepareTabView(host.getContext(), title, drawable); TabsUtil.setTabIndicator(spec, title, host.getContext().getResources().getDrawable(drawable), view); host.addTab(spec); } public static void addTab(TabHost host, String title, int drawable, int index, Intent intent) { TabHost.TabSpec spec = host.newTabSpec("tab" + index); spec.setContent(intent); View view = prepareTabView(host.getContext(), title, drawable); TabsUtil.setTabIndicator(spec, title, host.getContext().getResources().getDrawable(drawable), view); host.addTab(spec); } private static View prepareTabView(Context context, String text, int drawable) { View view = LayoutInflater.from(context).inflate(R.layout.tab_main_nav, null); TextView tv = (TextView) view.findViewById(R.id.tvTitle); tv.setText(text); ImageView iv = (ImageView) view.findViewById(R.id.ivIcon); iv.setImageResource(drawable); return view; } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/TabsUtil.java
Java
asf20
2,428
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.util; import android.media.ExifInterface; import android.text.TextUtils; /** * @date July 24, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ExifUtils { private ExifUtils() { } public static int getExifRotation(String imgPath) { try { ExifInterface exif = new ExifInterface(imgPath); String rotationAmount = exif.getAttribute(ExifInterface.TAG_ORIENTATION); if (!TextUtils.isEmpty(rotationAmount)) { int rotationParam = Integer.parseInt(rotationAmount); switch (rotationParam) { case ExifInterface.ORIENTATION_NORMAL: return 0; case ExifInterface.ORIENTATION_ROTATE_90: return 90; case ExifInterface.ORIENTATION_ROTATE_180: return 180; case ExifInterface.ORIENTATION_ROTATE_270: return 270; default: return 0; } } else { return 0; } } catch (Exception ex) { return 0; } } }
1031868817-hws
main/src/com/joelapenna/foursquared/util/ExifUtils.java
Java
asf20
1,279