Skip to content

Commit

Permalink
Aula 3 - OneBitCode
Browse files Browse the repository at this point in the history
  • Loading branch information
RuanAyram committed Nov 26, 2018
1 parent 2f4dafb commit 7b21222
Show file tree
Hide file tree
Showing 33 changed files with 386 additions and 11 deletions.
3 changes: 3 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ gem 'devise', '~> 4.5.0'
# Progressive Web Apps for Rails
gem 'pwa', '~> 4.0.5'

# Transforma o app em um PWA
gem "serviceworker-rails"

group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ GEM
selenium-webdriver (3.141.0)
childprocess (~> 0.5)
rubyzip (~> 1.2, >= 1.2.2)
serviceworker-rails (0.5.5)
railties (>= 3.1)
spring (2.0.2)
activesupport (>= 4.2)
spring-watcher-listen (2.0.1)
Expand Down Expand Up @@ -235,6 +237,7 @@ DEPENDENCIES
rails (~> 5.2.1)
sass-rails (~> 5.0)
selenium-webdriver
serviceworker-rails
spring
spring-watcher-listen (~> 2.0.0)
sqlite3
Expand Down
1 change: 1 addition & 0 deletions app/assets/javascripts/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@
//= require turbolinks
//= require jquery/dist/jquery.min
//= require_tree .
//= require serviceworker-companion
3 changes: 3 additions & 0 deletions app/assets/javascripts/favorites.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
19 changes: 19 additions & 0 deletions app/assets/javascripts/manifest.json.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<% icon_sizes = Rails.configuration.serviceworker.icon_sizes %>
{
"name": "Spotcode - Música na hora",
"short_name": "Spotcode",
"start_url": "/",
"icons": [
<% icon_sizes.map { |s| "#{s}x#{s}" }.each.with_index do |dim, i| %>
{
"src": "<%= image_path "serviceworker-rails/heart-#{dim}.png" %>",
"sizes": "<%= dim %>",
"type": "image/png"
}<%= i == (icon_sizes.length - 1) ? '' : ',' %>
<% end %>
],
"theme_color": "#000000",
"background_color": "#FFFFFF",
"display": "fullscreen",
"orientation": "portrait"
}
61 changes: 61 additions & 0 deletions app/assets/javascripts/player.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
$(document).on("turbolinks:load", function(){
const player = $("audio#song-player");
let currentSong = null;

$("div.play-button a").click(function(){
button = $(this);
if ($(this).closest("div.song-item").is(currentSong)) {
if (player[0].paused) {
resumeSong(button);
} else {
pauseSong(button)
}
} else {
playNewSong(button);
}
});

$("button#play-all").click(function(){
button = $("div.song-item:eq(0) div.play-button a");
playNewSong(button);
});

player.on('ended', function(){
playing = $("div.song-item.playing");
next = playing.next();
if (next.length > 0) {
play_button = $(next[0]).find('div.play-button a');
playNewSong(play_button);
}
});

function playNewSong(button) {
$("div.song-item").removeClass("playing");
$(button).closest("div.song-item").addClass("playing");
$("div.song-item div.play-button i").removeClass("fa-pause-circle").addClass("fa-play-circle");
player.prop("src", $(button).data("song"));
resumeSong(button);
sendRecentlyHeard(button);
currentSong = button.closest("div.song-item");
}

function pauseSong(button) {
$(button).children().filter("div.play-button i").removeClass("fa-pause-circle").addClass("fa-play-circle");
player[0].pause();
}

function resumeSong(button) {
$(button).children().filter("i").removeClass("fa-play-circle").addClass("fa-pause-circle");
player[0].play();
}

function sendRecentlyHeard(button) {
token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
url: button.data('url'),
headers: { 'X-CSRF-Token': token },
success: () => {}
});
}
});
3 changes: 3 additions & 0 deletions app/assets/javascripts/recently_heards.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
6 changes: 6 additions & 0 deletions app/assets/javascripts/serviceworker-companion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js', { scope: './' })
.then(function(reg) {
console.log('[Companion]', 'Service worker registered!');
});
}
64 changes: 64 additions & 0 deletions app/assets/javascripts/serviceworker.js.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
var CACHE_VERSION = 'v1';
var CACHE_NAME = CACHE_VERSION + ':sw-cache-';

function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([

// make sure serviceworker.js is not required by application.js
// if you want to reference application.js from here
'<%#= asset_path "application.js" %>',

'<%= asset_path "application.css" %>',

'/offline.html',

]);
})
);
}

function onActivate(event) {
console.log('[Serviceworker]', "Activating!", event);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
return cacheName.indexOf(CACHE_VERSION) !== 0;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
}

// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
event.respondWith(
// try to return untouched request from network first
fetch(event.request).catch(function() {
// if it fails, try to return request from the cache
return caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// if not found in cache, return default offline content for navigate requests
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
console.log('[Serviceworker]', "Fetching offline content", event);
return caches.match('/offline.html');
}
})
})
);
}

self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);
2 changes: 1 addition & 1 deletion app/assets/stylesheets/application.scss
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
* files in this directory. Styles in this file should be added after the last require_* statement.
* It is generally better to create a new file per style scope.
*
*= require_tree .
*= require_self
*= require_tree .
*/

@import "bulma/bulma";
Expand Down
3 changes: 3 additions & 0 deletions app/assets/stylesheets/favorites.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Place all the styles related to the favorites controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
3 changes: 3 additions & 0 deletions app/assets/stylesheets/recently_heards.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Place all the styles related to the recently_heards controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
7 changes: 4 additions & 3 deletions app/assets/stylesheets/shared/_tab.scss
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
div.tabs.shared {
li {
a {
//color: $white;
color: white;
}

&.is-active {
a {
//color: $primary;
//border-bottom-color: $primary;
color: green;
border-bottom-color: green;
}
Expand All @@ -23,5 +20,9 @@ div.tabs-content {
&.active {
display: block;
}

button#play-all{
margin-bottom: 15px;
}
}
}
5 changes: 4 additions & 1 deletion app/assets/stylesheets/songs/_song.scss
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
div.song-item {
//border-top: 1px solid $white;
border-top: 1px solid white;

div.play-button {
margin-top: 12px;
}

div.favorite {
margin-top: 10px;
}

&:first-child {
border-top: none;
}
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/dashboard_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def index

private
def load_recent_heard
@recent_albums = current_user.recently_heards.order("created_at DESC").limit(4).map(&:album)
@recent_albums = current_user.recently_heards.order("created_at DESC").group(:album_id).limit(4).map(&:album)
end

def load_recommendations
Expand Down
17 changes: 17 additions & 0 deletions app/controllers/favorites_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class FavoritesController < ApplicationController
def index
@favorite_albums = current_user.favorites.where(favoritable_type: "Album").map(&:favoritable)
@favorite_songs = current_user.favorites.where(favoritable_type: "Song").map(&:favoritable)
@favorite_artists = current_user.favorites.where(favoritable_type: "Artist").map(&:favoritable)
end

def create
@favoritable = current_user.favorites.new(favoritable_type: params[:favoritable_type], favoritable_id: params[:id])
@favoritable.save
end

def destroy
@favoritable = current_user.favorites.find_by(favoritable_type: params[:favoritable_type], favoritable_id: params[:id])
@favoritable.destroy
end
end
7 changes: 7 additions & 0 deletions app/controllers/recently_heards_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class RecentlyHeardsController < ApplicationController
def create
@recently_heard = current_user.recently_heards.new(album_id: params[:album_id])
@recently_heard.save
head :ok
end
end
18 changes: 18 additions & 0 deletions app/helpers/favorites_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module FavoritesHelper
def favorite_button(favoritable)
if current_user.favorites.where(favoritable: favoritable).exists?
render_button(favoritable.id, favoritable.class, :delete, :fas)
else
render_button(favoritable.id, favoritable.class, :post, :far)
end
end


private
def render_button(id, type, method, icon_format)
url = send("favorite_#{type.to_s.downcase}_path", id)
link_to url, class: "has-text-white", data: { remote: true, method: method, kind: type.to_s, id: id } do
content_tag :i, "", class: "#{icon_format} fa-heart fa-2x"
end
end
end
2 changes: 2 additions & 0 deletions app/helpers/recently_heards_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
module RecentlyHeardsHelper
end
8 changes: 7 additions & 1 deletion app/views/albums/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@
<h2 class="is-size-5 has-text-weight-bold">Músicas</h2>
<br />

<div class="columns is-multiline songs">
<div class="columns is-multiline songs has-text-centered">
<div class="column is-12">
<button id="play-all" class="button is-primary is-medium">
<span class="icon"><i class="fas fa-play-circle"></i></span>
<span>Tocar Todas</span>
</button>
</div>
<%= render @album.songs %>
</div>
</section>
5 changes: 5 additions & 0 deletions app/views/favorites/create.js.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
link_filter = "a[data-kind='<%= @favoritable.favoritable_type %>'][data-id='<%= @favoritable.favoritable_id %>']";

$('${link_filter}').attr('data-method', 'delete');

$('${link_filter} i').removeClass('far').addClass('fas');
5 changes: 5 additions & 0 deletions app/views/favorites/destroy.js.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
link_filter = "a[data-kind='<%= @favoritable.favoritable_type %>'][data-id='<%= @favoritable.favoritable_id %>']";

$('${link_filter}').attr('data-method', 'post');

$('${link_filter} i').removeClass('fas').addClass('far');
6 changes: 6 additions & 0 deletions app/views/favorites/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<section class="section has-text-white has-text-centered">
<h2 class="is-size-4 has-text-weight-bold">Favoritos</h2>
<br />

<%= render "shared/tabs", artists: @favorite_artists, songs: @favorite_songs, albums: @favorite_albums %>
</section>
3 changes: 3 additions & 0 deletions app/views/layouts/application.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<link rel="manifest" href="/manifest.json" />
<meta name="apple-mobile-web-app-capable" content="yes">
</head>

<body class="has-background-dark">
<%= render "shared/menu" %>
<%= yield %>
<audio id="song-player" src="#"></audio>
<%= render "shared/toolbar" %>
</body>
</html>
2 changes: 2 additions & 0 deletions app/views/recently_heards/create.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h1>RecentlyHeards#create</h1>
<p>Find me in app/views/recently_heards/create.html.erb</p>
2 changes: 1 addition & 1 deletion app/views/shared/_toolbar.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
</div>

<div class="column has-text-centered">
<%= link_to "", class: "has-text-white" do %>
<%= link_to favorites_path, class: "has-text-white" do %>
<i class="fas fa-heart fa-lg"></i>
<% end %>
</div>
Expand Down
5 changes: 4 additions & 1 deletion app/views/songs/_song.html.erb
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
<div class="column is-full has-text-left song-item">
<div class="columns is-mobile">
<div class="column is-2-mobile is-1-desktop play-button">
<%= link_to "", class: "has-text-white" do %>
<%= link_to "javascript:void(0);", class: "has-text-white", data: { song: url_for(song.file), url: album_recently_heards_path(song.album) } do %>
<i class="fas fa-play-circle fa-2x"></i>
<% end %>
</div>
<div class="column">
<h2 class="is-size-5"><%= song.title %></h2>
<p><%= song.album.artist.name %></p>
</div>
<div class="column is-2-mobile is-1-desktop is-pulled-right favorite">
<%= favorite_button(song) %>
</div>
</div>
</div>
Loading

0 comments on commit 7b21222

Please sign in to comment.